qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
141,146
<p>I want to know if my server is running Subversion 1.5.</p> <p>How can I find that out?</p> <p>Also would be nice to know my SVN client version number. <code>svn help</code> hasn't been helpful.</p> <p><strong>Note:</strong> I don't want my <em>project's</em> revision number, etc. This question is about the <em>Subversion software</em> itself.</p>
[ { "answer_id": 141479, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 5, "selected": false, "text": "<p>For an HTTP-based server there is a Python script to find the server version at:\n<a href=\"http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/server-version.py\" rel=\"noreferrer\">http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/server-version.py</a></p>\n\n<p>You can get the client version with</p>\n\n<pre><code>`svn --version`\n</code></pre>\n" }, { "answer_id": 142061, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": false, "text": "<p>On the server: <code>svnserve --version</code></p>\n\n<p>in case of svnserve-based configuration (svn:// and svn+xxx://).</p>\n\n<p>(For completeness).</p>\n" }, { "answer_id": 209189, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>To find the version of the subversion REPOSITORY you can:</p>\n\n<ol>\n<li>Look to the repository on the web and on the bottom of the page it will say something like:<br>\n\"Powered by Subversion version 1.5.2 (r32768).\"</li>\n<li>From the command line: &lt;insert curl, grep oneliner here&gt;</li>\n</ol>\n\n<p>If not displayed, view source of the page</p>\n\n<pre><code>&lt;svn version=\"1.6.13 (r1002816)\" href=\"http://subversion.tigris.org/\"&gt; \n</code></pre>\n\n<p>Now for the subversion CLIENT:</p>\n\n<pre><code>svn --version\n</code></pre>\n\n<p>will suffice</p>\n" }, { "answer_id": 1148254, "author": "jaredjacobs", "author_id": 140743, "author_profile": "https://Stackoverflow.com/users/140743", "pm_score": 6, "selected": false, "text": "<p>Here's the simplest way to get the SVN server version. <a href=\"http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol\" rel=\"noreferrer\">HTTP</a> works even if your SVN repository requires <a href=\"http://en.wikipedia.org/wiki/HTTP_Secure\" rel=\"noreferrer\">HTTPS</a>.</p>\n\n<pre>\n<b>$ curl -X OPTIONS http://my-svn-domain/</b>\n&lt;!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n&lt;html>&lt;head>...&lt;/head>\n&lt;body>...\n&lt;address>Apache/2.2.11 (Debian) DAV/2 <b>SVN/1.5.6</b> PHP/5.2.9-4 ...&lt;/address>\n&lt;/body><br>&lt;/html>\n</pre>\n" }, { "answer_id": 1356116, "author": "Glenn", "author_id": 165843, "author_profile": "https://Stackoverflow.com/users/165843", "pm_score": 2, "selected": false, "text": "<p>For a svn+ssh configuration, use ssh to run svnserve --version on the host machine:</p>\n\n<blockquote>\n <p>$ ssh user@host svnserve --version</p>\n</blockquote>\n\n<p>It is necessary to run the svnserve command on the machine that is actually serving as the server.</p>\n" }, { "answer_id": 1427401, "author": "eaubin", "author_id": 88114, "author_profile": "https://Stackoverflow.com/users/88114", "pm_score": 1, "selected": false, "text": "<p>You can connect to your Subversion server using <a href=\"http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol\" rel=\"nofollow noreferrer\">HTTP</a> and find the version number in the HTTP header.</p>\n" }, { "answer_id": 2742515, "author": "Christopher", "author_id": 193617, "author_profile": "https://Stackoverflow.com/users/193617", "pm_score": 5, "selected": false, "text": "<p>If the Subversion server version is not printed in the HTML listing, it is available in the HTTP RESPONSE header returned by the server. You can get it using this shell command</p>\n\n<pre><code>wget -S --no-check-certificate \\\n --spider 'http://svn.server.net/svn/repository' 2&gt;&amp;1 \\\n | sed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p';\n</code></pre>\n\n<p>If the SVN server requires you provide a user name and password, then add the <code>wget</code> parameters <code>--user</code> and <code>--password</code> to the command like this</p>\n\n<pre><code>wget -S --no-check-certificate \\\n --user='username' --password='password' \\\n --spider 'http://svn.server.net/svn/repository' 2&gt;&amp;1 \\\n | sed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p';\n</code></pre>\n" }, { "answer_id": 7079945, "author": "N0thing", "author_id": 158179, "author_profile": "https://Stackoverflow.com/users/158179", "pm_score": 2, "selected": false, "text": "<p>Just use a web browser to go to the SVN address. Check the source code (<kbd>Ctrl</kbd> + <kbd>U</kbd>). Then you will find something like in the HTML code:</p>\n\n<pre><code>&lt;svn version=\"1.6. ...\" ...\n</code></pre>\n" }, { "answer_id": 9502906, "author": "Lars Nordin", "author_id": 570450, "author_profile": "https://Stackoverflow.com/users/570450", "pm_score": 7, "selected": false, "text": "<p>Let's merge these responses:</p>\n\n<h2>For REPOSITORY / SERVER (the original question):</h2>\n\n<h3>If able to access the Subversion server:</h3>\n\n<ul>\n<li><p>From an earlier <a href=\"https://stackoverflow.com/questions/141146/how-to-find-my-subversion-server-version-number/1172703#1172703\">answer</a> by <a href=\"https://stackoverflow.com/users/143838/manuel\">Manuel</a>, run the following on the SVN server:</p>\n\n<pre><code>svnadmin --version\n</code></pre></li>\n</ul>\n\n<h3>If HTTP/HTTPS access:</h3>\n\n<ul>\n<li><p>See the \"powered by Subversion\" line when accessing the server via a browser.</p></li>\n<li><p>Access the repository via browser and then look for the version string embedded in the HTML source. From <a href=\"https://stackoverflow.com/questions/141146/how-to-find-my-subversion-server-version-number/1148254#1148254\">earlier answers by elviejo</a> and <a href=\"https://stackoverflow.com/users/140743/jaredjacobs\">jaredjacobs</a>. Similarly, from ??, use your browser's developer tools (usually <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd>) to read the full response. This is also the easiest (non-automated) way to deal with certificates and authorization - your browser does it for you.</p></li>\n<li><p>Check the response tags (these are not shown in the HTML source), from <a href=\"https://stackoverflow.com/questions/141146/how-to-find-my-subversion-server-version-number/2742515#2742515\">an earlier answer</a> by <a href=\"https://stackoverflow.com/users/193617/christopher\">Christopher</a></p>\n\n<pre><code>wget -S --spider 'http://svn.server.net/svn/repository' 2&gt;&amp;1 |\nsed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p'\n</code></pre></li>\n</ul>\n\n<h3>If svn:// or ssh+svn access</h3>\n\n<ul>\n<li><p>From <a href=\"https://stackoverflow.com/questions/141146/how-to-find-my-subversion-server-version-number/142061#142061\">an earlier answer</a> by <a href=\"https://stackoverflow.com/users/15785/milen-a-radev\">Milen</a></p>\n\n<pre><code>svnserve --version (run on svn server)\n</code></pre></li>\n<li><p>From <a href=\"https://stackoverflow.com/questions/141146/how-to-find-my-subversion-server-version-number/1356116#1356116\">an earlier answer</a> by <a href=\"https://stackoverflow.com/users/165843/glenn\">Glenn</a></p>\n\n<pre><code>ssh user@host svnserve --version\n</code></pre></li>\n</ul>\n\n<h3>If GoogleCode SVN servers</h3>\n\n<pre><code> Check out the current version in a FAQ: \n http://code.google.com/p/support/wiki/SubversionFAQ#What_version_of_Subversion_do_you_use?\n</code></pre>\n\n<h3>If another custom SVN servers</h3>\n\n<pre><code> TBD\n</code></pre>\n\n<p><strong><em>Please edit to finish this answer</em></strong></p>\n\n<h2>For CLIENT (not the original question):</h2>\n\n<pre><code>svn --version\n</code></pre>\n" }, { "answer_id": 11345699, "author": "Jason H", "author_id": 1504173, "author_profile": "https://Stackoverflow.com/users/1504173", "pm_score": 2, "selected": false, "text": "<p>Browse the repository with Firefox and inspect the element with <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"nofollow\">Firebug</a>. Under the NET tab, you can check the Header of the page. It will have something like:</p>\n\n<pre><code>Server: Apache/2.2.14 (Win32) DAV/2 SVN/1.X.X\n</code></pre>\n" }, { "answer_id": 12038934, "author": "Conrad", "author_id": 610090, "author_profile": "https://Stackoverflow.com/users/610090", "pm_score": 3, "selected": false, "text": "<p>One more option: If you have Firefox (I am using 14.0.1) and a SVN web interface:</p>\n\n<ul>\n<li>Open <strong>Tools->Web Developer->Web Console</strong> on a repo page</li>\n<li>Refresh page</li>\n<li>Click on the <strong>GET</strong> line</li>\n<li>Look in the <strong>Response Headers</strong> section at the <strong>Server:</strong> line</li>\n</ul>\n\n<p>There should be an \"SVN/1.7.4\" string or similar there. Again, this will probably only work if you have \"ServerTokens Full\" as mentioned above.</p>\n" }, { "answer_id": 14227707, "author": "mettkea", "author_id": 1468064, "author_profile": "https://Stackoverflow.com/users/1468064", "pm_score": 1, "selected": false, "text": "<p>For Subversion 1.7 and above, the server doesn't provide a footer that indicates the server version. But you can run the following command to gain the version from the response headers</p>\n\n<pre><code>$ curl -s -D - http://svn.server.net/svn/repository\nHTTP/1.1 401 Authorization Required\nDate: Wed, 09 Jan 2013 03:01:43 GMT\nServer: Apache/2.2.9 (Unix) DAV/2 SVN/1.7.4\n</code></pre>\n\n<p>Note that this also works on Subversion servers where you don't have authorization to access.</p>\n" }, { "answer_id": 16527826, "author": "David W.", "author_id": 368630, "author_profile": "https://Stackoverflow.com/users/368630", "pm_score": 3, "selected": false, "text": "<p>There really isn't an <strong><em>easy</em></strong> way to find out what version of Subversion your server is running -- except to get onto the server and see for yourself.</p>\n\n<p>However, this may not be as big a problem as you may think. Subversion clients is were much of the grunt work is handled, and most versions of the Subversion clients can work with almost any version of the server.</p>\n\n<p>The last release where the server version really made a difference to the client was the change from release 1.4 to release 1.5 when merge tracking was added. Merge tracking had been greatly improved in version 1.6, but that doesn't really affect the interactions between the client and server.</p>\n\n<p>Let's take the latest changes in Subversion 1.8:</p>\n\n<ul>\n<li><strong><code>svn move</code> is now a first class operation</strong>: Subversion finally understands the <code>svn move</code> is not a <code>svn copy</code> and <code>svn delete</code>. However, this is something that the client handles and doesn't really affect the server version.</li>\n<li><strong><code>svn merge --reintegrate</code> deprecated</strong>: Again, as long as the server is at version 1.5 or greater this isn't an issue.</li>\n<li><strong>Property Inheritance</strong>: This is another 1.8 release update, but this will work with any Subversion server -- although Subversion servers running 1.8 will deliver better performance on inheritable properties.</li>\n<li><strong>Two new inheritable properties - <code>svn:global-ignores</code> and <code>svn:auto-props</code></strong>: Alas! What we really wanted. A way to setup these two properties without depending upon the Subversion configuration file itself. However, this is a client-only issue, so it again doesn't matter what version of the server you're using.</li>\n<li><strong>gnu-agent memory caching</strong>: Another client-only feature.</li>\n<li>fsfs performance enhancements and authz in-repository authentication. Nice features, but these work no matter what version of the client you're using.</li>\n</ul>\n\n<p>Of all the features, only one depends upon the version of the server being 1.5 or greater (and 1.4 has been obsolete for quite a while. The newer features of 1.8 will improve performance of your working copy, but the server being at revision 1.8 isn't necessary. You're much more affected by your client version than your server version.</p>\n\n<p>I know this isn't the answer you wanted (no official way to see the server version), but fortunately the server version doesn't really affect you that much.</p>\n" }, { "answer_id": 21335321, "author": "ejaenv", "author_id": 599971, "author_profile": "https://Stackoverflow.com/users/599971", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>ssh your_user@your_server svnserve --version\n\nsvnserve, version 1.3.1 (r19032)\n compiled May 8 2006, 07:38:44\n</code></pre>\n\n<p>I hope it helps.</p>\n" }, { "answer_id": 60887240, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 2, "selected": false, "text": "<p>If you use VisualSVN Server, you can find out the version number by several different means.</p>\n\n<h2>Use VisualSVN Server Manager</h2>\n\n<p>Follow these steps to find out the version via the management console:</p>\n\n<ol>\n<li>Start the <strong>VisualSVN Server Manager</strong> console.</li>\n<li>See the <strong>Version</strong> at the bottom-right corner of the dashboard.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/AfPjW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AfPjW.png\" alt=\"enter image description here\"></a></p>\n\n<p>If you click <strong>Version</strong> you will also see the versions of the components.</p>\n\n<p><a href=\"https://i.stack.imgur.com/PtNJ2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PtNJ2.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Check the README.txt file</h2>\n\n<p>Follow these steps to find out the version from the readme.txt file:</p>\n\n<ol>\n<li>Start <strong>notepad.exe</strong>.</li>\n<li>Open the <strong>%VISUALSVN_SERVER%README.txt</strong> file. The first line shows the version number.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/HrxKt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HrxKt.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to know if my server is running Subversion 1.5. How can I find that out? Also would be nice to know my SVN client version number. `svn help` hasn't been helpful. **Note:** I don't want my *project's* revision number, etc. This question is about the *Subversion software* itself.
To find the version of the subversion REPOSITORY you can: 1. Look to the repository on the web and on the bottom of the page it will say something like: "Powered by Subversion version 1.5.2 (r32768)." 2. From the command line: <insert curl, grep oneliner here> If not displayed, view source of the page ``` <svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> ``` Now for the subversion CLIENT: ``` svn --version ``` will suffice
141,154
<p>I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.</p>
[ { "answer_id": 141166, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 6, "selected": false, "text": "<p>You could query this registry value to get the SQL version directly:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\90\\Tools\\ClientSetup\\CurrentVersion\n</code></pre>\n\n<p>Alternatively you can query your instance name and then use sqlcmd with your instance name that you would like: </p>\n\n<p>To see your instance name:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\n</code></pre>\n\n<p>Then execute this:</p>\n\n<pre><code>SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/34065/how-to-read-a-value-from-the-windows-registry#35717\">If you are using C++ you can use this code to get the registry information.</a></p>\n" }, { "answer_id": 141172, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>SQL Server Browser Service <a href=\"http://msdn.microsoft.com/en-us/library/ms181087.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms181087.aspx</a></p>\n" }, { "answer_id": 141180, "author": "dotnetengineer", "author_id": 8033, "author_profile": "https://Stackoverflow.com/users/8033", "pm_score": 6, "selected": false, "text": "<p>All of the instances installed should show up in the Services Snap-In in the Microsoft Management Console. To get the instance names, go to Start | Run | type Services.msc and look for all entries with \"Sql Server (Instance Name)\".</p>\n" }, { "answer_id": 141211, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 9, "selected": true, "text": "<p>At a command line:</p>\n\n<pre><code>SQLCMD -L\n</code></pre>\n\n<p>or </p>\n\n<pre><code>OSQL -L\n</code></pre>\n\n<p>(Note: must be a capital L)</p>\n\n<p>This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this...</p>\n\n<p>At command line:</p>\n\n<pre><code>svrnetcn\n</code></pre>\n\n<p>In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.</p>\n" }, { "answer_id": 143292, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 4, "selected": false, "text": "<p>If you just want to see what's installed on the machine you're currently logged in to, I think the most straightforward manual process is to just open the SQL Server Configuration Manager (from the Start menu), which displays all the SQL Services (and <em>only</em> SQL services) on that hardware (running or not). This assumes SQL Server 2005, or greater; <a href=\"https://stackoverflow.com/questions/141154/how-can-i-determine-installed-sql-server-versions#141180\">dotnetengineer</a>'s recommendation to use the Services Management Console will show you all services, and should always be available (if you're running earlier versions of SQL Server, for example).</p>\n\n<p>If you're looking for a broader discovery process, however, you might consider third party tools such as SQLRecon and SQLPing, which will scan your network and build a report of all SQL Service instances found on any server to which they have access. It's been a while since I've used tools like this, but I was surprised at what they found (namely, a handful of instances that I didn't know existed). YMMV. You might Google for details, but I believe this page has the relevant downloads: <a href=\"http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx\" rel=\"nofollow noreferrer\">http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx</a></p>\n" }, { "answer_id": 4508239, "author": "Daniel", "author_id": 551066, "author_profile": "https://Stackoverflow.com/users/551066", "pm_score": 2, "selected": false, "text": "<p>I had the same problem. The \"osql -L\" command displayed only a list of servers but without instance names (only the instance of my local SQL Sever was displayed).\nWith Wireshark, sqlbrowser.exe (which can by found in the shared folder of your SQL installation) I found a solution for my problem.</p>\n\n<p>The local instance is resolved by registry entry. The remote instances are resolved by UDP broadcast (port 1434) and SMB.\nUse \"sqlbrowser.exe -c\" to list the requests.</p>\n\n<p>My configuration uses 1 physical and 3 virtual network adapters. \nIf I used the \"osql -L\" command the sqlbrowser displayed a request from one of the virtual adaptors (which is in another network segment), instead of the physical one.\nosql selects the adpater by its metric. You can see the metric with command \"route print\".\nFor my configuration the routing table showed a lower metric for teh virtual adapter then for the physical. So I changed the interface metric in the network properties by deselecting automatic metric in the advanced network settings.\nosql now uses the physical adapter.</p>\n" }, { "answer_id": 6431060, "author": "Dale Sykora", "author_id": 809149, "author_profile": "https://Stackoverflow.com/users/809149", "pm_score": 3, "selected": false, "text": "<p>If you are interested in determining this in a script, you can try the following:</p>\n\n<pre><code>sc \\\\server_name query | grep MSSQL\n</code></pre>\n\n<p>Note: grep is part of gnuwin32 tools</p>\n" }, { "answer_id": 8498208, "author": "Moulde", "author_id": 48211, "author_profile": "https://Stackoverflow.com/users/48211", "pm_score": 1, "selected": false, "text": "<p>I just installed Sql server 2008, but i was unable to connect to any database instances.\nThe commands @G Mastros posted listed no active instances.</p>\n\n<p>So i looked in services and found that the SQL server agent was disabled. I fixed it by setting it to automatic and then starting it.</p>\n" }, { "answer_id": 9464754, "author": "Mohammed Ifteqar Ahmed", "author_id": 1235533, "author_profile": "https://Stackoverflow.com/users/1235533", "pm_score": 6, "selected": false, "text": "<p>-- T-SQL Query to find list of Instances Installed on a machine</p>\n\n<pre><code>DECLARE @GetInstances TABLE\n( Value nvarchar(100),\n InstanceNames nvarchar(100),\n Data nvarchar(100))\n\nInsert into @GetInstances\nEXECUTE xp_regread\n @rootkey = 'HKEY_LOCAL_MACHINE',\n @key = 'SOFTWARE\\Microsoft\\Microsoft SQL Server',\n @value_name = 'InstalledInstances'\n\nSelect InstanceNames from @GetInstances \n</code></pre>\n" }, { "answer_id": 9813050, "author": "Ian", "author_id": 1266771, "author_profile": "https://Stackoverflow.com/users/1266771", "pm_score": 3, "selected": false, "text": "<p>SQL Server permits applications to find SQL Server instances within the current network. The SqlDataSourceEnumerator class exposes this information to the application developer, providing a DataTable containing information about all the visible servers. This returned table contains a list of server instances available on the network that matches the list provided when a user attempts to create a new connection, and expands the drop-down list containing all the available servers on the Connection Properties dialog box. The results displayed are not always complete.\nIn order to retrieve the table containing information about the available SQL Server instances, you must first retrieve an enumerator, using the shared/static Instance property:</p>\n\n<pre><code>using System.Data.Sql;\n\nclass Program\n{\n static void Main()\n {\n // Retrieve the enumerator instance and then the data.\n SqlDataSourceEnumerator instance =\n SqlDataSourceEnumerator.Instance;\n System.Data.DataTable table = instance.GetDataSources();\n\n // Display the contents of the table.\n DisplayData(table);\n\n Console.WriteLine(\"Press any key to continue.\");\n Console.ReadKey();\n }\n\n private static void DisplayData(System.Data.DataTable table)\n {\n foreach (System.Data.DataRow row in table.Rows)\n {\n foreach (System.Data.DataColumn col in table.Columns)\n {\n Console.WriteLine(\"{0} = {1}\", col.ColumnName, row[col]);\n }\n Console.WriteLine(\"============================\");\n }\n }\n}\n</code></pre>\n\n<p>from msdn <a href=\"http://msdn.microsoft.com/en-us/library/a6t1z9x2(v=vs.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/a6t1z9x2(v=vs.80).aspx</a></p>\n" }, { "answer_id": 11632418, "author": "Badar", "author_id": 576750, "author_profile": "https://Stackoverflow.com/users/576750", "pm_score": 0, "selected": false, "text": "<p>Here is a simple method:\ngo to \nStart then\nPrograms then \nMicrosoft SQL Server 2005 then\nConfiguration Tools then\nSQL Server Configuration Manager then\nSQL Server 2005 Network Configuration then\nHere you can locate all the instance installed onto your machine.</p>\n" }, { "answer_id": 12065138, "author": "Anonymous", "author_id": 1615648, "author_profile": "https://Stackoverflow.com/users/1615648", "pm_score": 3, "selected": false, "text": "<p>This query should get you the server name and instance name : </p>\n\n<pre><code>SELECT @@SERVERNAME, @@SERVICENAME\n</code></pre>\n" }, { "answer_id": 15688565, "author": "AbuTaareq", "author_id": 1460063, "author_profile": "https://Stackoverflow.com/users/1460063", "pm_score": 1, "selected": false, "text": "<p>I had this same issue when I was assessing 100+ servers, I had a script written in C# to browse the service names consist of SQL. When instances installed on the server, SQL Server adds a service for each instance with service name. It may vary for different versions like 2000 to 2008 but for sure there is a service with instance name. </p>\n\n<p>I take the service name and obtain instance name from the service name. Here is the sample code used with WMI Query Result:</p>\n\n<pre><code>if (ServiceData.DisplayName == \"MSSQLSERVER\" || ServiceData.DisplayName == \"SQL Server (MSSQLSERVER)\")\n {\n InstanceData.Name = \"DEFAULT\";\n InstanceData.ConnectionName = CurrentMachine.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n else\n if (ServiceData.DisplayName.Contains(\"SQL Server (\") == true)\n {\n InstanceData.Name = ServiceData.DisplayName.Substring(\n ServiceData.DisplayName.IndexOf(\"(\") + 1,\n ServiceData.DisplayName.IndexOf(\")\") - ServiceData.DisplayName.IndexOf(\"(\") - 1\n );\n InstanceData.ConnectionName = CurrentMachine.Name + \"\\\\\" + InstanceData.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n else\n if (ServiceData.DisplayName.Contains(\"MSSQL$\") == true)\n {\n InstanceData.Name = ServiceData.DisplayName.Substring(\n ServiceData.DisplayName.IndexOf(\"$\") + 1,\n ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf(\"$\") - 1\n );\n\n InstanceData.ConnectionName = CurrentMachine.Name + \"\\\\\" + InstanceData.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n</code></pre>\n" }, { "answer_id": 19229905, "author": "jimbo", "author_id": 2855472, "author_profile": "https://Stackoverflow.com/users/2855472", "pm_score": 3, "selected": false, "text": "<p>From Windows command-line, type:</p>\n\n<pre><code>SC \\\\server_name query | find /I \"SQL Server (\"\n</code></pre>\n\n<p>Where \"server_name\" is the name of any remote server on which you wish to display the SQL instances.</p>\n\n<p>This requires enough permissions of course.</p>\n" }, { "answer_id": 32438789, "author": "Craig", "author_id": 5309093, "author_profile": "https://Stackoverflow.com/users/5309093", "pm_score": -1, "selected": false, "text": "<p>If your within SSMS you might find it easier to use:</p>\n\n<pre><code>SELECT @@Version\n</code></pre>\n" }, { "answer_id": 40598322, "author": "John Denton", "author_id": 4623995, "author_profile": "https://Stackoverflow.com/users/4623995", "pm_score": 5, "selected": false, "text": "<p>I know this thread is a bit old, but I came across this thread before I found the answer I was looking for and thought I'd share. If you are using SQLExpress (or localdb) there is a simpler way to find your instance names.\nAt a command line type:</p>\n\n<pre><code>&gt; sqllocaldb i\n</code></pre>\n\n<p>This will list the instance names you have installed locally. So your full server name should include (localdb)\\ in front of the instance name to connect. Also, sqllocaldb allows you to create new instances or delete them as well as configure them. See: <a href=\"https://msdn.microsoft.com/en-us/library/hh212961.aspx\" rel=\"noreferrer\">SqlLocalDB Utility</a>.</p>\n" }, { "answer_id": 40914787, "author": "akhil vangala", "author_id": 1133052, "author_profile": "https://Stackoverflow.com/users/1133052", "pm_score": 0, "selected": false, "text": "<p>I know its an old post but I found a nice solution with PoweShell where you can find SQL instances installed on local or a remote machine including the version and also be extend get other properties. </p>\n\n<pre><code>$MachineName = ‘.’ # Default local computer Replace . with server name for a remote computer\n\n$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’, $MachineName)\n$regKey= $reg.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Microsoft SQL Server\\\\Instance Names\\\\SQL\" )\n$values = $regkey.GetValueNames()\n$values | ForEach-Object {$value = $_ ; $inst = $regKey.GetValue($value); \n $path = \"SOFTWARE\\\\Microsoft\\\\Microsoft SQL Server\\\\\"+$inst+\"\\\\MSSQLServer\\\\\"+\"CurrentVersion\";\n #write-host $path; \n $version = $reg.OpenSubKey($path).GetValue(\"CurrentVersion\");\n write-host \"Instance\" $value;\n write-host \"Version\" $version}\n</code></pre>\n" }, { "answer_id": 48284086, "author": "TheGameiswar", "author_id": 2975396, "author_profile": "https://Stackoverflow.com/users/2975396", "pm_score": 3, "selected": false, "text": "<p>One more option would be to run SQLSERVER discovery report..go to installation media of sqlserver and double click setup.exe </p>\n\n<p><a href=\"https://i.stack.imgur.com/bcNp1.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bcNp1.gif\" alt=\"enter image description here\"></a></p>\n\n<p>and in the next screen,go to tools and click discovery report as shown below</p>\n\n<p><a href=\"https://i.stack.imgur.com/Y1tg0.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Y1tg0.gif\" alt=\"enter image description here\"></a></p>\n\n<p>This will show you all the instances present along with entire features..below is a snapshot on my pc\n<a href=\"https://i.stack.imgur.com/G2fpm.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/G2fpm.gif\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 58435310, "author": "Erk", "author_id": 386587, "author_profile": "https://Stackoverflow.com/users/386587", "pm_score": 1, "selected": false, "text": "<p>The commands <code>OSQL -L</code> and <code>SQLCMD -L</code> will show you all instances <em>on the network</em>.</p>\n\n<p>If you want to have a list of all instances <em>on the server</em> and doesn't feel like doing scripting or programming, do this:</p>\n\n<ol>\n<li>Start Windows Task Manager</li>\n<li>Tick the checkbox \"Show processes from all users\" or equivalent</li>\n<li>Sort the processes by \"Image Name\"</li>\n<li>Locate all <code>sqlsrvr.exe</code> images</li>\n</ol>\n\n<p>The instances should be listed in the \"User Name\" column as <code>MSSQL$INSTANCE_NAME</code>.</p>\n\n<p>And I went from thinking the poor server was running 63 instances to realizing it was running three (out of which one was behaving like a total bully with the CPU load...)</p>\n" }, { "answer_id": 60255804, "author": "siva", "author_id": 1111577, "author_profile": "https://Stackoverflow.com/users/1111577", "pm_score": 1, "selected": false, "text": "<p>Will get the instances of SQL server \nreg query \"HKLM\\Software\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL\"</p>\n\n<p>or Use \nSQLCMD -L</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.
At a command line: ``` SQLCMD -L ``` or ``` OSQL -L ``` (Note: must be a capital L) This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this... At command line: ``` svrnetcn ``` In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'.
141,162
<p>I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu).</p> <p>I already have the PID I am looking for, just need to see if it is currently running.</p> <hr> <p>UPDATE:</p> <p>Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.</p>
[ { "answer_id": 141165, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"https://stackoverflow.com/questions/138097/how-do-i-find-my-pid-in-java-or-jruby-on-linux#138098\">my answer to this question</a>, I was thinking of just using procfs again, by checking if the given directory exists via File.exist? \"/proc/#{pid}\". This worked in jirb:</p>\n\n<pre>\nirb(main):001:0> File.exist? \"/proc/5555\"\n=> false\nirb(main):002:0> File.exist? \"/proc/7677\"\n=> true\n</pre>\n\n<p>However, I would still prefer to use a method that specifically exists to detect if a process is running... like Process.exist?(pid)... which unfortunately doesn't exist that I've seen.</p>\n" }, { "answer_id": 141191, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 0, "selected": false, "text": "<p>I can't speak for JRuby, but in Java, the only way to check is if you launched the process from Java (in which case you would have an instance of <a href=\"http://java.sun.com/javase/6/docs/api/index.html?java/lang/Process.html\" rel=\"nofollow noreferrer\">Process</a> that you could do things with).</p>\n" }, { "answer_id": 141285, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 0, "selected": false, "text": "<p>You'll probably want to double check for the JVM that you're using. But if you send a <strong>SIGQUIT</strong> signal kill -3 I believe, (I don't have a terminal handy). That should generate a Javacore file which will have stack traces of the in use thread, check for JRuby packages in that file.</p>\n\n<p>It shouldn't terminate or anything but as always be careful sending signals.</p>\n" }, { "answer_id": 141663, "author": "Bribles", "author_id": 5916, "author_profile": "https://Stackoverflow.com/users/5916", "pm_score": 0, "selected": false, "text": "<p>If you don't mind creating a whole new process then this lazy way should work:</p>\n\n<pre><code>def pid_exists? (pid)\n system \"ps -p #{pid} &gt; /dev/null\"\n return $? == 0\nend\n</code></pre>\n\n<p>For most variations of <em>ps</em>, it should return 0 on success and non-zero on error. The usual error with the usage above will be not finding the process with the given PID. The version of <em>ps</em> I have under Ubuntu returns 256 in this case.</p>\n\n<p>You could also use Process.kill to send a signal of 0 to the process (signal 0 indicates if a signal may be sent), but that seems to only work if you own the process you're sending the signal to (or otherwise have permissions to send it signals).</p>\n" }, { "answer_id": 141731, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "<p>Unix has a special feature of the kill system call around signal zero. Error checking is performed, but no signal is sent.</p>\n\n<pre><code>def pid_exists? (pid)\n system \"kill -0 #{pid}\"\n return $? == 0\nend\n</code></pre>\n\n<p>One caveat: this won't detect processes with that pid that you don't have permission to signal.</p>\n" }, { "answer_id": 200568, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/141162/how-can-i-determine-if-a-different-process-id-is-running-using-java-or-jruby-on#141731\">Darron's comment</a> was spot on, but rather than calling the \"kill\" binary, you can just use Ruby's Process.kill method with the 0 signal:</p>\n\n<pre><code>#!/usr/bin/ruby \n\npid = ARGV[0].to_i\n\nbegin\n Process.kill(0, pid)\n puts \"#{pid} is running\"\nrescue Errno::EPERM # changed uid\n puts \"No permission to query #{pid}!\";\nrescue Errno::ESRCH\n puts \"#{pid} is NOT running.\"; # or zombied\nrescue\n puts \"Unable to determine status for #{pid} : #{$!}\"\nend\n</code></pre>\n\n<blockquote>\n <p>[user@host user]$ ./is_running.rb 14302 <br />\n 14302 is running</p>\n \n <p>[user@host user]$ ./is_running.rb 99999 <br />\n 99999 is NOT running. </p>\n \n <p>[user@host user]$ ./is_running.rb 37 <br />\n No permission to query 37! </p>\n \n <p>[user@host user]$ sudo ./is_running.rb 37 <br />\n 37 is running</p>\n</blockquote>\n\n<p>Reference: <a href=\"http://pleac.sourceforge.net/pleac_ruby/processmanagementetc.html\" rel=\"nofollow noreferrer\">http://pleac.sourceforge.net/pleac_ruby/processmanagementetc.html</a></p>\n" }, { "answer_id": 4279029, "author": "Martin Gross", "author_id": 520353, "author_profile": "https://Stackoverflow.com/users/520353", "pm_score": 0, "selected": false, "text": "<p>You could use the command line tool <code>jps</code> which comes with your java installation. jps lists all java Processes of a user.</p>\n\n<p>E.g.</p>\n\n<pre><code>&gt;jps -l\n5960 org.jruby.Main\n2124 org.jruby.Main\n5376 org.jruby.Main\n4428 sun.tools.jps.Jps\n</code></pre>\n\n<p>Or if you need to get the results into your script you could use %x[..]:</p>\n\n<pre><code>&gt;&gt; result = %x[jps -l]\n=&gt; \"5960 org.jruby.Main\\n2264 sun.tools.jps.Jps\\n2124 org.jruby.Main\\n5376 org.jruby.Main\\n\"\n&gt;&gt; p result\n\"5960 org.jruby.Main\\n2264 sun.tools.jps.Jps\\n2124 org.jruby.Main\\n5376 org.jruby.Main\\n\"\n=&gt; nil\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu). I already have the PID I am looking for, just need to see if it is currently running. --- UPDATE: Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.
[Darron's comment](https://stackoverflow.com/questions/141162/how-can-i-determine-if-a-different-process-id-is-running-using-java-or-jruby-on#141731) was spot on, but rather than calling the "kill" binary, you can just use Ruby's Process.kill method with the 0 signal: ``` #!/usr/bin/ruby pid = ARGV[0].to_i begin Process.kill(0, pid) puts "#{pid} is running" rescue Errno::EPERM # changed uid puts "No permission to query #{pid}!"; rescue Errno::ESRCH puts "#{pid} is NOT running."; # or zombied rescue puts "Unable to determine status for #{pid} : #{$!}" end ``` > > [user@host user]$ ./is\_running.rb 14302 > > 14302 is running > > > [user@host user]$ ./is\_running.rb 99999 > > 99999 is NOT running. > > > [user@host user]$ ./is\_running.rb 37 > > No permission to query 37! > > > [user@host user]$ sudo ./is\_running.rb 37 > > 37 is running > > > Reference: <http://pleac.sourceforge.net/pleac_ruby/processmanagementetc.html>
141,169
<p>So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.</p> <p>The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.</p> <p>I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?</p> <p>Thanks!</p>
[ { "answer_id": 141195, "author": "Mike J", "author_id": 4443, "author_profile": "https://Stackoverflow.com/users/4443", "pm_score": 1, "selected": false, "text": "<p>You need to re-add the dynamically created controls, in the onload, so that they can be in the page hierarchy and fire their event.</p>\n" }, { "answer_id": 201301, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 2, "selected": false, "text": "<p>This is my favorite trick :)</p>\n\n<p>Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events.</p>\n\n<p>The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the <code>LoadViewState()</code> call, but you must create the controls before that call to have the events fired correctly.</p>\n\n<p>The trick is to override <code>LoadViewState()</code> and <code>SaveViewState()</code> so we can control things.</p>\n\n<p><em>(note that the code below is rough, from memory and probably has issues)</em></p>\n\n<pre><code>private string searchQuery = null;\n\nprivate void SearchButton(object sender, EventArgs e)\n{\n searchQuery = searchBox.Text;\n var results = DataLayer.PerformSearch(searchQuery);\n CreateLinkButtonControls(results);\n}\n\n// We save both the base state object, plus our query string. Everything here must be serializable.\nprotected override object SaveViewState()\n{\n object baseState = base.SaveViewState();\n return new object[] { baseState, searchQuery };\n}\n\n// The parameter to this method is the exact object we returned from SaveViewState().\nprotected override void LoadViewState(object savedState)\n{\n object[] stateArray = (object[])savedState;\n\n searchQuery = stateArray[1] as string;\n\n // Re-run the query\n var results = DataLayer.PerformSearch(searchQuery);\n\n // Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.\n CreateLinkButtonControls(results);\n\n // Very important - load the rest of the ViewState, including our controls above.\n base.LoadViewState(stateArray[0]);\n}\n</code></pre>\n" }, { "answer_id": 2559375, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": -1, "selected": false, "text": "<p>A dirty hack I just came up with, is to create dummy LinkButtons with the same IDs as the real buttons.\nSo let's say you are going to create a LinkButton \"foo\" at Pre_Render (which is too late), then also create a dummy foo at Page_Load:</p>\n\n<pre><code> var link = new LinkButton();\n link.ID = \"foo\";\n link.Click += fooEventHandler;\n dummyButtons.Controls.Add(link);\n</code></pre>\n\n<p>(Where \"dummyButtons\" is just a PlaceHolder on the page with Visibility set to false.)\nIt's ugly, but it works.</p>\n" }, { "answer_id": 41589644, "author": "M.Rahmani", "author_id": 5467185, "author_profile": "https://Stackoverflow.com/users/5467185", "pm_score": 0, "selected": false, "text": "<pre><code> LinkButton link= new LinkButton();\n link.Command +=new CommandEventHandler(LinkButton1_Command);\n\n protected void LinkButton1_Command(object sender, CommandEventArgs e)\n{\n try\n {\n System.Threading.Thread.Sleep(300);\n if (e.CommandName == \"link\")\n {\n //////////\n }\n }\n catch\n {\n\n }\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19086/" ]
So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page. The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed. I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this? Thanks!
This is my favorite trick :) Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events. The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the `LoadViewState()` call, but you must create the controls before that call to have the events fired correctly. The trick is to override `LoadViewState()` and `SaveViewState()` so we can control things. *(note that the code below is rough, from memory and probably has issues)* ``` private string searchQuery = null; private void SearchButton(object sender, EventArgs e) { searchQuery = searchBox.Text; var results = DataLayer.PerformSearch(searchQuery); CreateLinkButtonControls(results); } // We save both the base state object, plus our query string. Everything here must be serializable. protected override object SaveViewState() { object baseState = base.SaveViewState(); return new object[] { baseState, searchQuery }; } // The parameter to this method is the exact object we returned from SaveViewState(). protected override void LoadViewState(object savedState) { object[] stateArray = (object[])savedState; searchQuery = stateArray[1] as string; // Re-run the query var results = DataLayer.PerformSearch(searchQuery); // Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break. CreateLinkButtonControls(results); // Very important - load the rest of the ViewState, including our controls above. base.LoadViewState(stateArray[0]); } ```
141,201
<p>I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.</p> <p>I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:</p> <pre><code>class Foo &lt; ActiveRecord::Base establish_connection(('foo_' + ENV['RAILS_ENV']).intern) end </code></pre>
[ { "answer_id": 141314, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 3, "selected": false, "text": "<p>Heh. I was right! More cleanly:</p>\n\n<pre><code>class Foo &lt; ActiveRecord::Base\n establish_connection \"foo_#{ENV['RAILS_ENV']}\"\nend\n</code></pre>\n\n<p>Great post <a href=\"http://pragdave.me/blog/2006/01/03/sharing-external-activerecord-connections/\" rel=\"nofollow noreferrer\">at pragedave.pragprog.com</a>.</p>\n" }, { "answer_id": 143357, "author": "Priit", "author_id": 22964, "author_profile": "https://Stackoverflow.com/users/22964", "pm_score": 5, "selected": true, "text": "<p>Also, it is a good idea to subclass your model that uses different database, such as:</p>\n\n<pre><code>class AnotherBase &lt; ActiveRecord::Base\n self.abstract_class = true\n establish_connection \"anotherbase_#{RAILS_ENV}\"\nend\n</code></pre>\n\n<p>And in your model</p>\n\n<pre><code>class Foo &lt; AnotherBase\nend\n</code></pre>\n\n<p>It is useful when you need to add subsequent models that access the same, another database.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809/" ]
I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well. I understand that establish\_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work: ``` class Foo < ActiveRecord::Base establish_connection(('foo_' + ENV['RAILS_ENV']).intern) end ```
Also, it is a good idea to subclass your model that uses different database, such as: ``` class AnotherBase < ActiveRecord::Base self.abstract_class = true establish_connection "anotherbase_#{RAILS_ENV}" end ``` And in your model ``` class Foo < AnotherBase end ``` It is useful when you need to add subsequent models that access the same, another database.
141,203
<p>I'm trying to grok the purpose of .NET's SecureString. From MSDN:</p> <blockquote> <p>An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.</p> <p>A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.</p> <p>The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.</p> </blockquote> <p>Is the automatic encryption the big payoff?</p> <p>And why can't I just say:</p> <pre><code>SecureString password = new SecureString(&quot;password&quot;); </code></pre> <p>instead of</p> <pre><code>SecureString pass = new SecureString(); foreach (char c in &quot;password&quot;.ToCharArray()) pass.AppendChar(c); </code></pre> <p>What aspect of SecureString am I missing?</p>
[ { "answer_id": 141213, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>I guess it's because the string is meant to be secure, i.e. a hacker should not be able to read it. If you initialize it with a string, the hacker could read the original string.</p>\n" }, { "answer_id": 141223, "author": "JoshReedSchramm", "author_id": 7018, "author_profile": "https://Stackoverflow.com/users/7018", "pm_score": 4, "selected": false, "text": "<p>I believe the reason why you have to do character appending instead of one flat instantiation is because in the background passing \"password\" to the constructor of SecureString puts that \"password\" string in memory defeating the purpose of secure string. </p>\n\n<p>By appending you are only putting a character at a time into memory which is likley not to be adjacent to each other physically making it much harder to reconstruct the original string. I could be wrong here but that's how it was explained to me. </p>\n\n<p>The purpose of the class is to prevent secure data from being exposed via a memory dump or similar tool. </p>\n" }, { "answer_id": 141227, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 4, "selected": false, "text": "<p>MS found that on certain instances of causing the server (desktop, whatever) to crash there were times when the runtime environment would do a memory dump exposing the contents of what's in memory. Secure String encrypts it in memory to prevent the attacker from being able to retrieve the contents of the string. </p>\n" }, { "answer_id": 141234, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 2, "selected": false, "text": "<p>Well, as the description states, the value is stored encrypted, with means that a memory dump of your process won't reveal the string's value (without some fairly serious work).</p>\n\n<p>The reason you can't just construct a SecureString from a constant string is because then you <em>would</em> have an unencrypted version of the string in memory. Limiting you to creating the string in pieces reduces the risk of having the whole string in memory at once.</p>\n" }, { "answer_id": 141258, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 3, "selected": false, "text": "<p>One of the big benefits of a SecureString is that it is supposed avoid the possibility of your data being stored to disk due to page caching. If you have a password in memory and then load a large program or data set, your password may get written to the swap file as your program is paged out of memory. With a SecureString, at least the data will not be sitting around indefinitely on your disk in clear text.</p>\n" }, { "answer_id": 141297, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 4, "selected": false, "text": "<p>There are very few scenarios where you can sensibly use SecureString in the current version of the Framework. It's really only useful for interacting with unmanaged APIs - you can marshal it using Marshal.SecureStringToGlobalAllocUnicode. </p>\n\n<p>As soon as you convert it to/from a System.String, you've defeated its purpose.</p>\n\n<p>The MSDN <a href=\"http://msdn.microsoft.com/en-us/library/07b9wyhy.aspx\" rel=\"noreferrer\">sample</a> generates the SecureString a character at a time from console input and passes the secure string to an unmanaged API. It's rather convoluted and unrealistic.</p>\n\n<p>You might expect future versions of .NET to have more support for SecureString that will make it more useful, e.g.:</p>\n\n<ul>\n<li><p>SecureString Console.ReadLineSecure() or similar to read console input into a SecureString without all the convoluted code in the sample.</p></li>\n<li><p>WinForms TextBox replacement that stores its TextBox.Text property as a secure string so that passwords can be entered securely.</p></li>\n<li><p>Extensions to security-related APIs to allow passwords to be passed as SecureString.</p></li>\n</ul>\n\n<p>Without the above, SecureString will be of limited value.</p>\n" }, { "answer_id": 141393, "author": "Chris Wenham", "author_id": 5548, "author_profile": "https://Stackoverflow.com/users/5548", "pm_score": 7, "selected": false, "text": "<p>Some parts of the framework that currently use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureString</code></a>:</p>\n\n<ul>\n<li>WPF's <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.passwordbox\" rel=\"noreferrer\"><code>System.Windows.Controls.PasswordBox</code></a> control keeps the password as a SecureString internally (exposed as a copy through <code>PasswordBox::SecurePassword</code>)</li>\n<li>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.password\" rel=\"noreferrer\"><code>System.Diagnostics.ProcessStartInfo::Password</code></a> property is a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureString</code></a></li>\n<li>The constructor for <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2\" rel=\"noreferrer\"><code>X509Certificate2</code></a> takes a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureString</code></a> for the password</li>\n</ul>\n\n<p>The main purpose is to reduce the attack surface, rather than eliminate it. <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureStrings</code></a> are \"pinned\" in RAM so the Garbage Collector won't move it around or make copies of it. It also makes sure the plain text won't get written to the Swap file or in core dumps. The encryption is more like obfuscation and won't stop a determined hacker, though, who would be able to find the <a href=\"https://en.wikipedia.org/wiki/Symmetric-key_algorithm\" rel=\"noreferrer\">symmetric key</a> used to encrypt and decrypt it.</p>\n\n<p>As others have said, the reason you have to create a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureString</code></a> character-by-character is because of the first obvious flaw of doing otherwise: you presumably have the secret value as a plain string already, so what's the point? </p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring\" rel=\"noreferrer\"><code>SecureString</code></a>s are the first step in solving a Chicken-and-Egg problem, so even though most current scenarios require converting them back into regular strings to make any use of them at all, their existence in the framework now means better support for them in the future - at least to a point where your program doesn't have to be the weak link.</p>\n" }, { "answer_id": 143475, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 5, "selected": false, "text": "<p><strong>Edit</strong>: <em>Don't use SecureString</em></p>\n\n<p>Current guidance now says the class should not be used. The details can be found at this link: <a href=\"https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md\" rel=\"nofollow noreferrer\">https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md</a></p>\n\n<p>From the article:</p>\n\n<h1>DE0001: SecureString shouldn't be used</h1>\n\n<h2>Motivation</h2>\n\n<ul>\n<li>The purpose of <a href=\"https://learn.microsoft.com/dotnet/api/system.security.securestring\" rel=\"nofollow noreferrer\"><code>SecureString</code></a> is to avoid having secrets stored in the process\nmemory as plain text.</li>\n<li>However, even on Windows, <a href=\"https://learn.microsoft.com/dotnet/api/system.security.securestring\" rel=\"nofollow noreferrer\"><code>SecureString</code></a> doesn't exist as an OS concept.\n\n<ul>\n<li>It just makes the window getting the plain text shorter; it doesn't fully\nprevent it as .NET still has to convert the string to a plain text\nrepresentation.</li>\n<li>The benefit is that the plain text representation doesn't hang around\nas an instance of <a href=\"https://learn.microsoft.com/dotnet/api/system.string\" rel=\"nofollow noreferrer\"><code>System.String</code></a> -- the lifetime of the native buffer is\nshorter.</li>\n</ul></li>\n<li>The contents of the array is unencrypted except on .NET Framework.\n\n<ul>\n<li>In .NET Framework, the contents of the internal char array is encrypted.\n.NET doesn't support encryption in all environments, either\ndue to missing APIs or key management issues.</li>\n</ul></li>\n</ul>\n\n<h2>Recommendation</h2>\n\n<p>Don't use <a href=\"https://learn.microsoft.com/dotnet/api/system.security.securestring\" rel=\"nofollow noreferrer\"><code>SecureString</code></a> for new code. When porting code to .NET Core, consider\nthat the contents of the array are not encrypted in memory.</p>\n\n<p>The general approach of dealing with credentials is to avoid them and instead\nrely on other means to authenticate, such as certificates or Windows\nauthentication.</p>\n\n<p><strong>End Edit : Original Summary below</strong></p>\n\n<p>Lots of great answers; here’s a quick synopsis of what has been discussed.</p>\n\n<p>Microsoft has implemented the SecureString class in an effort to provide better security with sensitive information (like credit cards, passwords, etc.). It automatically provides:</p>\n\n<ul>\n<li>encryption (in case of memory dumps\nor page caching) </li>\n<li>pinning in memory</li>\n<li>ability to mark as read-only (to prevent any further modifications) </li>\n<li>safe construction by NOT allowing a constant string to be passed in</li>\n</ul>\n\n<p>Currently, SecureString is limited in use but expect better adoption in the future.</p>\n\n<p>Based on this information, the constructor of the SecureString should not just take a string and slice it up to char array as having the string spelled out defeats the purpose of SecureString.</p>\n\n<p>Additional info: </p>\n\n<ul>\n<li>A <a href=\"http://blogs.msdn.com/shawnfa/archive/2004/05/27/143254.aspx\" rel=\"nofollow noreferrer\">post</a> from the .NET Security\nblog talking about much the same as\ncovered here. </li>\n<li>And another <a href=\"http://blogs.msdn.com/shawnfa/archive/2006/11/01/securestring-redux.aspx\" rel=\"nofollow noreferrer\">one</a>\nrevisiting it and mentioning a tool\nthat CAN dump the contents of the\nSecureString.</li>\n</ul>\n\n<p>Edit: I found it tough to pick the best answer as there's good information in many; too bad there is no assisted answer options.</p>\n" }, { "answer_id": 38492801, "author": "Joe Healy", "author_id": 1564317, "author_profile": "https://Stackoverflow.com/users/1564317", "pm_score": 3, "selected": true, "text": "<p>I would stop using SecureString . Looks like PG guys are dropping support for it. Possibly even pull it in the future - <a href=\"https://github.com/dotnet/apireviews/tree/master/2015-07-14-securestring\" rel=\"nofollow\">https://github.com/dotnet/apireviews/tree/master/2015-07-14-securestring</a> .</p>\n\n<blockquote>\n <p>We should remove encryption from SecureString across all platforms in .NET Core - We should obsolete SecureString - We probably shouldn't expose SecureString in .NET Core</p>\n</blockquote>\n" }, { "answer_id": 41192547, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "<h2>Short Answer</h2>\n\n<blockquote>\n <p>why can't I just say:</p>\n\n<pre><code>SecureString password = new SecureString(\"password\");\n</code></pre>\n</blockquote>\n\n<p>Because now you have <code>password</code> in memory; with no way to wipe it - which is exactly the point of <strong>SecureString</strong>.</p>\n\n<h2>Long Answer</h2>\n\n<p>The reason <strong>SecureString</strong> exists is because you cannot use <strong>ZeroMemory</strong> to wipe sensitive data when you're done with it. It exists to solve an issue that exists <strong>because</strong> of the CLR. </p>\n\n<p>In a regular <em>native</em> application you would call <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366877%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396\" rel=\"noreferrer\"><code>SecureZeroMemory</code></a>:</p>\n\n<blockquote>\n <p>Fills a block of memory with zeros.</p>\n</blockquote>\n\n<p><strong>Note</strong>: SecureZeroMemory is is identical to <code>ZeroMemory</code>, <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20130529-00/?p=4223\" rel=\"noreferrer\">except the compiler won't optimize it away.</a></p>\n\n<p>The problem is that you <strong>can't</strong> call <code>ZeroMemory</code> or <code>SecureZeroMemory</code> inside .NET. And in .NET strings are immutable; you can't even <em>overwrite</em> the contents of the string like you can do in other languages:</p>\n\n<pre><code>//Wipe out the password\nfor (int i=0; i&lt;password.Length; i++)\n password[i] = \\0;\n</code></pre>\n\n<p>So what can you do? How do we provide the ability in .NET to wipe a password, or credit card number from memory when we're done with it?</p>\n\n<p>The only way it can be done would be to place the string in some <em>native</em> memory block, where you <strong>can</strong> then call <code>ZeroMemory</code>. A native memory object such as:</p>\n\n<ul>\n<li>a BSTR</li>\n<li>an HGLOBAL</li>\n<li>CoTaskMem unmanaged memory</li>\n</ul>\n\n<h2>SecureString gives the lost ability back</h2>\n\n<p>In .NET, Strings cannot be wiped when you are done with them:</p>\n\n<ul>\n<li>they are immutable; you cannot overwrite their contents</li>\n<li>you cannot <code>Dispose</code> of them</li>\n<li>their cleanup is at the mercy of the garbage collector</li>\n</ul>\n\n<p>SecureString exists as a way to pass around strings safety, and be able to guarantee their cleanup when you need to.</p>\n\n<p>You asked the question:</p>\n\n<blockquote>\n <p>why can't I just say:</p>\n\n<pre><code>SecureString password = new SecureString(\"password\");\n</code></pre>\n</blockquote>\n\n<p>Because now you have <code>password</code> in memory; with no way to wipe it. It's stuck there until the CLR happens to decide to re-use that memory. You've put us right back where we started; a running application with a password we can't get rid of, and where a memory dump (or Process Monitor) can see the password.</p>\n\n<p>SecureString uses the Data Protection API to store the string encrypted in memory; that way the string will not exist in swapfiles, crash dumps, or even in the local variables window with a colleague looking over your should.</p>\n\n<h2>How do i read the password?</h2>\n\n<p>Then is the question: how do i interact with the string? You absolutely <strong>don't</strong> want a method like:</p>\n\n<pre><code>String connectionString = secureConnectionString.ToString()\n</code></pre>\n\n<p>because now you're right back where you started - a password you cannot get rid of. You want to <strong>force</strong> developers to handle the sensitive string correctly - so that it <em>can</em> be wiped from memory. </p>\n\n<p>That is why .NET provides three handy helper functions to marshall a SecureString into a unmanaged memory:</p>\n\n<ul>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.securestringtobstr(v=vs.110).aspx\" rel=\"noreferrer\">SecureStringToBSTR</a> <em>(freed with <a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.zerofreecotaskmemunicode(v=vs.110).aspx\" rel=\"noreferrer\">ZeroFreeCoTaskMemUnicode</a>)</em></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.securestringtocotaskmemunicode%28v=vs.110%29.aspx?f=255&amp;MSPPError=-2147217396\" rel=\"noreferrer\">SecureStringToCoTaskMemUnicode</a> <em>(freed with <a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.zerofreecotaskmemunicode(v=vs.110).aspx\" rel=\"noreferrer\">ZeroFreeCoTaskMemUnicode</a>)</em></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.securestringtoglobalallocunicode(v=vs.110).aspx\" rel=\"noreferrer\">SecureStringToGlobalAllocUnicode</a> <em>(freed with <a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.zerofreeglobalallocunicode(v=vs.110).aspx\" rel=\"noreferrer\">ZeroFreeGlobalAllocUnicode</a>)</em></li>\n</ul>\n\n<p>You convert the string into an unmanaged memory blob, handle it, and then wipe it again. </p>\n\n<p>Some APIs accept <strong>SecureStrings</strong>. For example in ADO.net 4.5 the <strong>SqlConnection.Credential</strong> takes a set <strong>SqlCredential</strong>:</p>\n\n<pre><code>SqlCredential cred = new SqlCredential(userid, password); //password is SecureString\nSqlConnection conn = new SqlConnection(connectionString);\nconn.Credential = cred;\nconn.Open();\n</code></pre>\n\n<p>You can also change the password within a Connection String:</p>\n\n<pre><code>SqlConnection.ChangePassword(connectionString, cred, newPassword);\n</code></pre>\n\n<p>And there are a lot of places inside .NET where they continue to accept a plain String for compatibility purposes, then quickly turn around an put it into a SecureString. </p>\n\n<h2>How to put text into the SecureString?</h2>\n\n<p>This still leaves the problem:</p>\n\n<blockquote>\n <p>How do i get a password into the SecureString in the first place?</p>\n</blockquote>\n\n<p>This is the challenge, but the point is to get you thinking about security. </p>\n\n<p>Sometimes the functionality is already provided for you. For example, the WPF <strong>PasswordBox</strong> control can return you the entered password as a <strong>SecureString</strong> directly:</p>\n\n<blockquote>\n <h2><a href=\"https://msdn.microsoft.com/en-us/library/system.windows.controls.passwordbox.securepassword(v=vs.110).aspx\" rel=\"noreferrer\">PasswordBox.SecurePassword Property</a></h2>\n \n <p>Gets the password currently held by the <a href=\"https://msdn.microsoft.com/en-us/library/system.windows.controls.passwordbox(v=vs.110).aspx\" rel=\"noreferrer\">PasswordBox</a> as a <a href=\"https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx\" rel=\"noreferrer\">SecureString</a>.</p>\n</blockquote>\n\n<p>This is helpful because everywhere you used to pass around a raw string, you now have the type system complaining that SecureString is incompatible with String. You want to go as long as possible before having to convert your SecureString back into regular string. </p>\n\n<p>Converting a SecureString is easy enough:</p>\n\n<ul>\n<li>SecureStringToBSTR</li>\n<li>PtrToStringBSTR</li>\n</ul>\n\n<p>as in:</p>\n\n<pre><code>private static string CreateString(SecureString secureString)\n{\n IntPtr intPtr = IntPtr.Zero;\n if (secureString == null || secureString.Length == 0)\n {\n return string.Empty;\n }\n string result;\n try\n {\n intPtr = Marshal.SecureStringToBSTR(secureString);\n result = Marshal.PtrToStringBSTR(intPtr);\n }\n finally\n {\n if (intPtr != IntPtr.Zero)\n {\n Marshal.ZeroFreeBSTR(intPtr);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>They just really don't want you doing it.</p>\n\n<p>But how do i get a string into a SecureString? Well what you need to do is stop having a password in a <strong>String</strong> in the first place. You needed to have it in <em>something</em> else. Even a <code>Char[]</code> array would be helpful.</p>\n\n<p>That's when you can append each character <strong>and</strong> wipe the plaintext when you're done:</p>\n\n<pre><code>for (int i=0; i &lt; PasswordArray.Length; i++)\n{\n password.AppendChar(PasswordArray[i]);\n PasswordArray[i] = (Char)0;\n}\n</code></pre>\n\n<p>You need your password stored in <strong>some</strong> memory that you can wipe. Load it into the SecureString from there.</p>\n\n<hr>\n\n<p>tl;dr: <strong>SecureString</strong> exists to provide the equivalent of <strong>ZeroMemory</strong>.</p>\n\n<p>Some people don't see the point in <a href=\"https://www.apple.com/business/docs/iOS_Security_Guide.pdf\" rel=\"noreferrer\">wiping the user's password from memory when a device is locked</a>, or wiping <a href=\"https://ostif.org/the-veracrypt-audit-results/\" rel=\"noreferrer\">wiping keystrokes from memory after they'authenticated</a>. Those people do not use SecureString.</p>\n" }, { "answer_id": 47027447, "author": "Roman", "author_id": 1055909, "author_profile": "https://Stackoverflow.com/users/1055909", "pm_score": 1, "selected": false, "text": "<p>Another use case is when you are working with payment applications (POS) and you simply <em>can't use immutable data structures</em> in order to store sensitive data because you are careful developer. For instance: if I will store sensitive card data or authorisation metadata into immutable string there always would be the case when this data will be available in memory for significant amount of time after it was discarded. I cannot simply overwrite it. Another huge advantage where such sensitive data being kept in memory encrypted.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ]
I'm trying to grok the purpose of .NET's SecureString. From MSDN: > > An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory. > > > A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector. > > > The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method. > > > Is the automatic encryption the big payoff? And why can't I just say: ``` SecureString password = new SecureString("password"); ``` instead of ``` SecureString pass = new SecureString(); foreach (char c in "password".ToCharArray()) pass.AppendChar(c); ``` What aspect of SecureString am I missing?
I would stop using SecureString . Looks like PG guys are dropping support for it. Possibly even pull it in the future - <https://github.com/dotnet/apireviews/tree/master/2015-07-14-securestring> . > > We should remove encryption from SecureString across all platforms in .NET Core - We should obsolete SecureString - We probably shouldn't expose SecureString in .NET Core > > >
141,204
<p>I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.</p> <p>Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?</p> <pre><code>public class SomeDataClass : IDisposable { private SqlConnection _conn; //constructors and methods private DoSomethingWithTheSqlConnection() { //some code excluded for brevity try { using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection)) { _SqlConnection.Open(); countOfSomething = Convert.ToInt32(cmd.ExecuteScalar()); } } finally { //is this the best way? if (_SqlConnection.State == ConnectionState.Closed) _SqlConnection.Close(); } //some code excluded for brevity } public Dispose() { _conn.Dispose(); } } </code></pre>
[ { "answer_id": 141215, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 7, "selected": true, "text": "<p>Wrap your database handling code inside a \"using\"</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection (...))\n{\n // Whatever happens in here, the connection is \n // disposed of (closed) at the end.\n}\n</code></pre>\n" }, { "answer_id": 141217, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 1, "selected": false, "text": "<p>Since you're using IDisposables anyway. You can use the 'using' keyword, which is basically equivalent to calling dispose in a finally block, but it looks better.</p>\n" }, { "answer_id": 141228, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>I'm guessing that by <code>_SqlConnection.State == ConnectionState.Closed</code> you meant <code>!=</code></p>\n\n<p>This will certainly work. I think it is more customary to contain the connection object itself inside a using statement, but what you have is good if you want to reuse the same connection object for some reason.</p>\n\n<p>One thing that you should definitely change, though, is the <code>Dispose()</code> method. You should not reference the connection object in dispose, because it may have already been finalized at that point. You should follow the recommended Dispose pattern instead.</p>\n" }, { "answer_id": 141235, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": -1, "selected": false, "text": "<p>Might I suggest this:</p>\n\n<pre><code>\n class SqlOpener : IDisposable\n {\n SqlConnection _connection;\n\n public SqlOpener(SqlConnection connection)\n {\n _connection = connection;\n _connection.Open();\n\n }\n\n void IDisposable.Dispose()\n {\n _connection.Close();\n }\n }\n\n public class SomeDataClass : IDisposable\n {\n private SqlConnection _conn;\n\n //constructors and methods\n\n private void DoSomethingWithTheSqlConnection()\n {\n //some code excluded for brevity\n using (SqlCommand cmd = new SqlCommand(\"some sql query\", _conn))\n using(new SqlOpener(_conn))\n {\n int countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());\n }\n //some code excluded for brevity\n }\n\n public void Dispose()\n {\n _conn.Dispose();\n }\n }\n</code></pre>\n\n<p>Hope that helps :)</p>\n" }, { "answer_id": 141240, "author": "Ed Schwehm", "author_id": 1206, "author_profile": "https://Stackoverflow.com/users/1206", "pm_score": 1, "selected": false, "text": "<p>Put the connection close code inside a \"Finally\" block like you show. Finally blocks are executed before the exception is thrown. Using a \"using\" block works just as well, but I find the explicit \"Finally\" method more clear.</p>\n\n<p>Using statements are old hat to many developers, but younger developers might not know that off hand.</p>\n" }, { "answer_id": 141257, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 3, "selected": false, "text": "<p>The .Net Framework mantains a connection pool for a reason. Trust it! :)\nYou don't have to write so much code just to connect to the database and release the connection.</p>\n\n<p>You can just use the 'using' statement and rest assured that 'IDBConnection.Release()' will close the connection for you.</p>\n\n<p>Highly elaborate 'solutions' tend to result in buggy code. Simple is better.</p>\n" }, { "answer_id": 141261, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx\" rel=\"noreferrer\">MSDN Docs</a> make this pretty clear...</p>\n\n<ul>\n<li>The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. </li>\n</ul>\n\n<p>You probably haven't (and don't want to) disable connection pooling, so the pool ultimately manages the state of the connection after you call \"Close\". This could be important as you may be confused looking from the database server side at all the open connections.</p>\n\n<hr>\n\n<ul>\n<li>An application can call Close more than one time. No exception is generated. </li>\n</ul>\n\n<p>So why bother testing for Closed? Just call Close().</p>\n\n<hr>\n\n<ul>\n<li>Close and Dispose are functionally equivalent.</li>\n</ul>\n\n<p>This is why a <em>using</em> block results in a closed connection. <em>using</em> calls Dispose for you.</p>\n\n<hr>\n\n<ul>\n<li>Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class.</li>\n</ul>\n\n<p>Important safety tip. Thanks, Egon.</p>\n" }, { "answer_id": 141298, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 1, "selected": false, "text": "<p>See this question for the answer:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/61092/close-and-dispose-which-to-call#61131\">Close and Dispose - which to call?</a></p>\n\n<p>If your connection lifetime is a single method call, use the <code>using</code> feature of the language to ensure the proper clean-up of the connection. While a <code>try/finally</code> block is functionally the same, it requires more code and IMO is less readable. There is no need to check the state of the connection, you can call <code>Dispose</code> regardless and it will handle cleaning-up the connection.</p>\n\n<p>If your connection lifetime corresponds to the lifetime of a containing class, then implement <code>IDisposable</code> and clean-up the connection in <code>Dispose</code>.</p>\n" }, { "answer_id": 518231, "author": "BlackTigerX", "author_id": 8411, "author_profile": "https://Stackoverflow.com/users/8411", "pm_score": 0, "selected": false, "text": "<p>no need for a try..finally around a \"using\", the using <strong>IS</strong> a try..finally</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here. Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately? ``` public class SomeDataClass : IDisposable { private SqlConnection _conn; //constructors and methods private DoSomethingWithTheSqlConnection() { //some code excluded for brevity try { using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection)) { _SqlConnection.Open(); countOfSomething = Convert.ToInt32(cmd.ExecuteScalar()); } } finally { //is this the best way? if (_SqlConnection.State == ConnectionState.Closed) _SqlConnection.Close(); } //some code excluded for brevity } public Dispose() { _conn.Dispose(); } } ```
Wrap your database handling code inside a "using" ``` using (SqlConnection conn = new SqlConnection (...)) { // Whatever happens in here, the connection is // disposed of (closed) at the end. } ```
141,241
<p>I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?</p>
[ { "answer_id": 141267, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 6, "selected": true, "text": "<p>Yes. Java 1.7 introduced the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"noreferrer\">try-with-resources</a> construct allowing you to write:</p>\n\n<pre><code>try(InputStream is1 = new FileInputStream(\"/tmp/foo\");\n InputStream is2 = new FileInputStream(\"/tmp/bar\")) {\n /* do stuff with is1 and is2 */\n}\n</code></pre>\n\n<p>... just like a <code>using</code> statement.</p>\n\n<p>Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:</p>\n\n<pre><code>InputStream is1 = new FileInputStream(\"/tmp/foo\");\ntry{\n\n InputStream is2 = new FileInputStream(\"/tmp/bar\");\n try{\n /* do stuff with is1 and is 2 */\n\n } finally {\n is2.close();\n }\n} finally {\n is1.close();\n}\n</code></pre>\n" }, { "answer_id": 141268, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>Not that I'm aware of. You can somewhat simulate with a try...finally block, but it's still not quite the same.</p>\n" }, { "answer_id": 141269, "author": "user10059", "author_id": 10059, "author_profile": "https://Stackoverflow.com/users/10059", "pm_score": -1, "selected": false, "text": "<p>No, there is no using in Java, the most similar functionality is the \"import\" keyword.</p>\n" }, { "answer_id": 141279, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": -1, "selected": false, "text": "<p>No there isn't.</p>\n\n<p>You can</p>\n\n<pre><code>public void func(){\n\n {\n ArrayList l = new ArrayList();\n }\n System.out.println(\"Hello\");\n\n}\n</code></pre>\n\n<p>This gives you the limited scope of the using clause, but there isn't any IDisposable interface to call finalization code. You can use try{}catch(){}Finally{}, but it doesn't have the sugar of using. Incidentally using finalizers in Java is generally a bad idea.</p>\n" }, { "answer_id": 141304, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 1, "selected": false, "text": "<p>I think you can achieve something similar to the \"using\" block, implementing an anonymous inner class. Like Spring does with the \"Dao Templates\".</p>\n" }, { "answer_id": 141506, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<p>The closest you can get in Java is try/finally. Also, Java does not provide an implicit Disposable type.</p>\n\n<p><strong>C#: scoping the variable outside a using block</strong></p>\n\n<pre><code>public class X : System.IDisposable {\n\n public void Dispose() {\n System.Console.WriteLine(\"dispose\");\n }\n\n private static void Demo() {\n X x = new X();\n using(x) {\n int i = 1;\n i = i/0;\n }\n }\n\n public static void Main(System.String[] args) {\n try {\n Demo();\n } catch (System.DivideByZeroException) {}\n }\n\n}\n</code></pre>\n\n<p><strong>Java: scoping the variable outside a block</strong></p>\n\n<pre><code>public class X {\n\n public void dispose() {\n System.out.println(\"dispose\");\n }\n\n private static void demo() {\n X x = new X();\n try {\n int i = 1 / 0;\n } finally {\n x.dispose();\n } \n }\n\n public static void main(String[] args) {\n try {\n demo();\n } catch(ArithmeticException e) {}\n }\n\n}\n</code></pre>\n\n<p><strong>C#: scoping the variable inside a block</strong></p>\n\n<pre><code>public class X : System.IDisposable {\n\n public void Dispose() {\n System.Console.WriteLine(\"dispose\");\n }\n\n private static void Demo() {\n using(X x = new X()) {\n int i = 1;\n i = i/0;\n }\n }\n\n public static void Main(System.String[] args) {\n try {\n Demo();\n } catch (System.DivideByZeroException) {}\n }\n\n}\n</code></pre>\n\n<p><strong>Java: scoping the variable inside a block</strong></p>\n\n<pre><code>public class X {\n\n public void dispose() {\n System.out.println(\"dispose\");\n }\n\n private static void demo() {\n {\n X x = new X();\n try {\n int i = 1 / 0;\n } finally {\n x.dispose();\n }\n }\n }\n\n public static void main(String[] args) {\n try {\n demo();\n } catch(ArithmeticException e) {}\n }\n\n}\n</code></pre>\n" }, { "answer_id": 143462, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 0, "selected": false, "text": "<p>Well, using was syntactic sugar anyway so Java fellows, don't sweat it.</p>\n" }, { "answer_id": 143690, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "<p>The nearest equivalent within the language is to use try-finally.</p>\n\n<pre><code>using (InputStream in as FileInputStream(\"myfile\")) {\n ... use in ...\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>final InputStream in = FileInputStream(\"myfile\");\ntry {\n ... use in ...\n} finally {\n in.close();\n}\n</code></pre>\n\n<p>Note the general form is always:</p>\n\n<pre><code>acquire;\ntry {\n use;\n} finally {\n release;\n}\n</code></pre>\n\n<p>If acquisition is within the try block, you will release in the case that the acquisition fails. In some cases you might be able to hack around with unnecessary code (typically testing for null in the above example), but in the case of, say, ReentrantLock bad things will happen.</p>\n\n<p>If you're doing the same thing often, you can use the \"execute around\" idiom. Unfortunately Java's syntax is verbose, so there is a lot of bolier plate.</p>\n\n<pre><code>fileInput(\"myfile\", new FileInput&lt;Void&gt;() {\n public Void read(InputStream in) throws IOException {\n ... use in ...\n return null;\n }\n});\n</code></pre>\n\n<p>where</p>\n\n<pre><code>public static &lt;T&gt; T fileInput(FileInput&lt;T&gt; handler) throws IOException {\n final InputStream in = FileInputStream(\"myfile\");\n try {\n handler.read(in);\n } finally {\n in.close();\n }\n}\n</code></pre>\n\n<p>More complicated example my, for instance, wrap exceptions.</p>\n" }, { "answer_id": 178359, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": "<p>If we get BGGA closures in Java, this would also open up for similar structures in Java. Gafter has used this example in his slides, for example:</p>\n\n<pre><code>withLock(lock) { //closure }\n</code></pre>\n" }, { "answer_id": 500004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The actual idiom used by most programmers for the first example is this:</p>\n\n<pre><code>InputStream is1 = null;\nInputStream is2 = null;\ntry{\n is1 = new FileInputStream(\"/tmp/bar\");\n is2 = new FileInputStream(\"/tmp/foo\");\n\n /* do stuff with is1 and is 2 */\n\n} finally {\n if (is1 != null) {\n is1.close();\n }\n if (is2 != null) {\n is2.close();\n }\n}\n</code></pre>\n\n<p>There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.</p>\n\n<p>Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.</p>\n" }, { "answer_id": 12742736, "author": "Tim", "author_id": 140985, "author_profile": "https://Stackoverflow.com/users/140985", "pm_score": 2, "selected": false, "text": "<p>It was a long time coming but with Java 7 the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources statement</a> was added, along with the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html\" rel=\"nofollow\">AutoCloseable</a> interface.</p>\n" }, { "answer_id": 18931324, "author": "Lodewijk Bogaards", "author_id": 1860591, "author_profile": "https://Stackoverflow.com/users/1860591", "pm_score": 3, "selected": false, "text": "<p>Yes, since Java 7 you can rewrite:</p>\n\n<pre><code>InputStream is1 = new FileInputStream(\"/tmp/foo\");\ntry{\n\n InputStream is2 = new FileInputStream(\"/tmp/bar\");\n try{\n /* do stuff with is1 and is2 */\n\n } finally {\n is2.close();\n }\n} finally {\n is1.close();\n}\n</code></pre>\n\n<p>As </p>\n\n<pre><code>try(InputStream is1 = new FileInputStream(\"/tmp/foo\");\n InputStream is2 = new FileInputStream(\"/tmp/bar\")) {\n /* do stuff with is1 and is2 */\n}\n</code></pre>\n\n<p>The objects passed as parameters to the try statement should implement <code>java.lang.AutoCloseable</code>.Have a look at the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">official docs</a>.</p>\n\n<p>For older versions of Java checkout <a href=\"https://stackoverflow.com/a/141267/1860591\">this answer</a> and <a href=\"https://stackoverflow.com/a/143690/1860591\">this answer</a>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?
Yes. Java 1.7 introduced the [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct allowing you to write: ``` try(InputStream is1 = new FileInputStream("/tmp/foo"); InputStream is2 = new FileInputStream("/tmp/bar")) { /* do stuff with is1 and is2 */ } ``` ... just like a `using` statement. Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6: ``` InputStream is1 = new FileInputStream("/tmp/foo"); try{ InputStream is2 = new FileInputStream("/tmp/bar"); try{ /* do stuff with is1 and is 2 */ } finally { is2.close(); } } finally { is1.close(); } ```
141,251
<p>This is really annoying, we've switched our client downloads page to a different site and want to send a link out with our installer. When the link is created and overwrites the existing file, the metadata in windows XP still points to the same place even though the contents of the .url shows the correct address. I can change that URL property to google.com and it points to the same place when I copy over the file. </p> <pre> [InternetShortcut] URL=https://www.xxxx.com/?goto=clientlogon.php IDList= HotKey=0 </pre> <p>It works if we rename our link .url file. But we expect that the directory will be reused and that would result in one bad link and one good link which is more confusing than it is cool. </p>
[ { "answer_id": 144213, "author": "DougN", "author_id": 7442, "author_profile": "https://Stackoverflow.com/users/7442", "pm_score": 1, "selected": false, "text": "<p>.URL files are wierd (are they documented anywhere?)</p>\n\n<p>Mine look like this and I don't seem to have that problem (maybe because of the Modified entry?)</p>\n\n<pre><code>[DEFAULT]\nBASEURL=http://www.xxxx.com/Help\n[InternetShortcut]\nURL=http://www.xxxx.com/Help\nModified=60D0EDADF1CAC5014B\n</code></pre>\n" }, { "answer_id": 144215, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 3, "selected": true, "text": "<p>Take a look at here: <a href=\"http://www.cyanwerks.com/file-format-url.html\" rel=\"nofollow noreferrer\">http://www.cyanwerks.com/file-format-url.html</a></p>\n\n<p>It explains there's a Modified field you can add to the .url file. It also explains how to interpret it.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
This is really annoying, we've switched our client downloads page to a different site and want to send a link out with our installer. When the link is created and overwrites the existing file, the metadata in windows XP still points to the same place even though the contents of the .url shows the correct address. I can change that URL property to google.com and it points to the same place when I copy over the file. ``` [InternetShortcut] URL=https://www.xxxx.com/?goto=clientlogon.php IDList= HotKey=0 ``` It works if we rename our link .url file. But we expect that the directory will be reused and that would result in one bad link and one good link which is more confusing than it is cool.
Take a look at here: <http://www.cyanwerks.com/file-format-url.html> It explains there's a Modified field you can add to the .url file. It also explains how to interpret it.
141,278
<p>I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like:</p> <pre><code>WHERE id IN (SELECT id FROM ...) </code></pre> <p><strong>The refactored query runs about 100x faster.</strong> (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something?</p> <p><strong>Update</strong> - Explain results:</p> <p>The difference is in the second part of the "where id in ()" query - </p> <pre><code>2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where </code></pre> <p>vs 1 indexed row with the join:</p> <pre><code> SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index </code></pre>
[ { "answer_id": 141290, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>Look at the query plan for each query.</p>\n\n<p><em>Where in</em> and <em>Join</em> can <strong>typically</strong> be implemented using the same execution plan, so <strong>typically</strong> there is zero speed-up from changing between them.</p>\n" }, { "answer_id": 141292, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 5, "selected": false, "text": "<p>You are running the subquery <strong>once for every row</strong> whereas the join happens on indexes.</p>\n" }, { "answer_id": 141294, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>Optimizer didn't do a very good job. Usually they can be transformed without any difference and the optimizer can do this.</p>\n" }, { "answer_id": 141299, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>With a subquery, you have to re-execute the 2nd SELECT for each result, and each execution typically returns 1 row. </p>\n\n<p>With a join, the 2nd SELECT returns a lot more rows, but you only have to execute it once. The advantage is that now you can join on the results, and joining relations is what a database is supposed to be good at. For example, maybe the optimizer can spot how to take better advantage of an index now.</p>\n" }, { "answer_id": 141305, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<p>It isn't so much the subquery as the IN clause, although joins are at the foundation of at least Oracle's SQL engine and run extremely quickly.</p>\n" }, { "answer_id": 141306, "author": "igelkott", "author_id": 2052165, "author_profile": "https://Stackoverflow.com/users/2052165", "pm_score": 2, "selected": false, "text": "<p>The subquery was probably executing a \"full table scan\". In other words, not using the index and returning way too many rows that the Where from the main query were needing to filter out.</p>\n\n<p>Just a guess without details of course but that's the common situation.</p>\n" }, { "answer_id": 141308, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "<p>Usually its the result of the optimizer not being able to figure out that the subquery can be executed as a join in which case it executes the subquery for each record in the table rather then join the table in the subquery against the table you are querying. Some of the more \"enterprisey\" database are better at this, but they still miss it sometimes.</p>\n" }, { "answer_id": 141310, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 8, "selected": true, "text": "<p>A \"correlated subquery\" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically.</p>\n\n<p>But, yeah, explain-plan will give you the dirty details.</p>\n" }, { "answer_id": 141321, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 3, "selected": false, "text": "<p>This question is somewhat general, so here's a general answer:</p>\n\n<p>Basically, queries take longer when MySQL has tons of rows to sort through.</p>\n\n<p>Do this:</p>\n\n<p>Run an EXPLAIN on each of the queries (the JOIN'ed one, then the Subqueried one), and post the results here.</p>\n\n<p>I think seeing the difference in MySQL's interpretation of those queries would be a learning experience for everyone.</p>\n" }, { "answer_id": 141325, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 3, "selected": false, "text": "<p>before the queries are run against the dataset they are put through a query optimizer, the optimizer attempts to organize the query in such a fashion that it can remove as many tuples (rows) from the result set as quickly as it can. Often when you use subqueries (especially bad ones) the tuples can't be pruned out of the result set until the outer query starts to run. </p>\n\n<p>With out seeing the the query its hard to say what was so bad about the original, but my guess would be it was something that the optimizer just couldn't make much better. Running 'explain' will show you the optimizers method for retrieving the data. </p>\n" }, { "answer_id": 141382, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 3, "selected": false, "text": "<p>The where subquery has to run 1 query for each returned row. The inner join just has to run 1 query.</p>\n" }, { "answer_id": 145411, "author": "Giuseppe Maxia", "author_id": 18535, "author_profile": "https://Stackoverflow.com/users/18535", "pm_score": 4, "selected": false, "text": "<p>Here's an example of how <a href=\"http://datacharmer.blogspot.com/2008/09/drizzling-mysql.html\" rel=\"noreferrer\">subqueries are evaluated in MySQL 6.0</a>.</p>\n\n<p>The new optimizer will convert this kind of subqueries into joins.</p>\n" }, { "answer_id": 39595601, "author": "simhumileco", "author_id": 4217744, "author_profile": "https://Stackoverflow.com/users/4217744", "pm_score": 2, "selected": false, "text": "<p>Taken from the Reference Manual (<a href=\"http://dev.mysql.com/doc/refman/5.7/en/rewriting-subqueries.html\" rel=\"nofollow\">14.2.10.11 Rewriting Subqueries as Joins</a>):</p>\n\n<blockquote>\n <p>A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.</p>\n</blockquote>\n\n<p>So subqueries can be slower than LEFT [OUTER] JOINS.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521/" ]
I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like: ``` WHERE id IN (SELECT id FROM ...) ``` **The refactored query runs about 100x faster.** (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something? **Update** - Explain results: The difference is in the second part of the "where id in ()" query - ``` 2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where ``` vs 1 indexed row with the join: ``` SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index ```
A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically. But, yeah, explain-plan will give you the dirty details.
141,280
<p>What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. </p> <p>Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.</p>
[ { "answer_id": 141311, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 1, "selected": false, "text": "<p>Try to split you string on words and count the resulting words, then sort on the counts.</p>\n" }, { "answer_id": 141323, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>Once you have that array of words cleaned up, and let's say you call it <code>wordArray</code>:</p>\n\n<pre><code>var keywordRegistry = {};\n\nfor(var i = 0; i &lt; wordArray.length; i++) {\n if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) {\n keywordRegistry[wordArray[i]] = 0;\n }\n keywordRegistry[wordArray[i]] = keywordRegistry[wordArray[i]] + 1;\n}\n\n// now keywordRegistry will have, as properties, all of the \n// words in your word array with their respective counts \n\n// this will alert (choose something better than alert) all words and their counts\nfor(var keyword in keywordRegistry) {\n alert(\"The keyword '\" + keyword + \"' occurred \" + keywordRegistry[keyword] + \" times\");\n}\n</code></pre>\n\n<p>That should give you the basics of doing this part of the work.</p>\n" }, { "answer_id": 141369, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "<p>Cut, paste + execute demo:</p>\n\n<pre><code>var text = \"Text to be examined to determine which n words are used the most\";\n\n// Find 'em!\nvar wordRegExp = /\\w+(?:'\\w{1,2})?/g;\nvar words = {};\nvar matches;\nwhile ((matches = wordRegExp.exec(text)) != null)\n{\n var word = matches[0].toLowerCase();\n if (typeof words[word] == \"undefined\")\n {\n words[word] = 1;\n }\n else\n {\n words[word]++;\n }\n}\n\n// Sort 'em!\nvar wordList = [];\nfor (var word in words)\n{\n if (words.hasOwnProperty(word))\n {\n wordList.push([word, words[word]]);\n }\n}\nwordList.sort(function(a, b) { return b[1] - a[1]; });\n\n// Come back any time, straaanger!\nvar n = 10;\nvar message = [\"The top \" + n + \" words are:\"];\nfor (var i = 0; i &lt; n; i++)\n{\n message.push(wordList[i][0] + \" - \" + wordList[i][1] + \" occurance\" +\n (wordList[i][1] == 1 ? \"\" : \"s\"));\n}\nalert(message.join(\"\\n\"));\n</code></pre>\n\n<p>Reusable function:</p>\n\n<pre><code>function getTopNWords(text, n)\n{\n var wordRegExp = /\\w+(?:'\\w{1,2})?/g;\n var words = {};\n var matches;\n while ((matches = wordRegExp.exec(text)) != null)\n {\n var word = matches[0].toLowerCase();\n if (typeof words[word] == \"undefined\")\n {\n words[word] = 1;\n }\n else\n {\n words[word]++;\n }\n }\n\n var wordList = [];\n for (var word in words)\n {\n if (words.hasOwnProperty(word))\n {\n wordList.push([word, words[word]]);\n }\n }\n wordList.sort(function(a, b) { return b[1] - a[1]; });\n\n var topWords = [];\n for (var i = 0; i &lt; n; i++)\n {\n topWords.push(wordList[i][0]);\n }\n return topWords;\n}\n</code></pre>\n" }, { "answer_id": 141396, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": -1, "selected": false, "text": "<p>I would do exactly what you have mentioned above to isolate each word. I would then probably add each word as the index of an array with the number of occurrences as the value. </p>\n\n<p>For example:</p>\n\n<pre><code>var a = new Array;\na[word] = a[word]?a[word]+1:1;\n</code></pre>\n\n<p>Now you know how many unique words there are (a.length) and how many occurrences of each word existed (a[word]).</p>\n" }, { "answer_id": 141928, "author": "awatts", "author_id": 22847, "author_profile": "https://Stackoverflow.com/users/22847", "pm_score": 1, "selected": false, "text": "<p>This builds upon a previous answer by <em>insin</em> by only having one loop:</p>\n\n<pre><code>function top_words(text, n) {\n // Split text on non word characters\n var words = text.toLowerCase().split(/\\W+/)\n var positions = new Array()\n var word_counts = new Array()\n for (var i=0; i&lt;words.length; i++) {\n var word = words[i]\n if (!word) {\n continue\n }\n\n if (typeof positions[word] == 'undefined') {\n positions[word] = word_counts.length\n word_counts.push([word, 1])\n } else {\n word_counts[positions[word]][1]++\n }\n }\n // Put most frequent words at the beginning.\n word_counts.sort(function (a, b) {return b[1] - a[1]})\n // Return the first n items\n return word_counts.slice(0, n)\n}\n\n// Let's see if it works.\nvar text = \"Words in here are repeated. Are repeated, repeated!\"\nalert(top_words(text, 3))\n</code></pre>\n\n<p>The result of the example is: <code>[['repeated',3], ['are',2], ['words', 1]]</code></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.
Cut, paste + execute demo: ``` var text = "Text to be examined to determine which n words are used the most"; // Find 'em! var wordRegExp = /\w+(?:'\w{1,2})?/g; var words = {}; var matches; while ((matches = wordRegExp.exec(text)) != null) { var word = matches[0].toLowerCase(); if (typeof words[word] == "undefined") { words[word] = 1; } else { words[word]++; } } // Sort 'em! var wordList = []; for (var word in words) { if (words.hasOwnProperty(word)) { wordList.push([word, words[word]]); } } wordList.sort(function(a, b) { return b[1] - a[1]; }); // Come back any time, straaanger! var n = 10; var message = ["The top " + n + " words are:"]; for (var i = 0; i < n; i++) { message.push(wordList[i][0] + " - " + wordList[i][1] + " occurance" + (wordList[i][1] == 1 ? "" : "s")); } alert(message.join("\n")); ``` Reusable function: ``` function getTopNWords(text, n) { var wordRegExp = /\w+(?:'\w{1,2})?/g; var words = {}; var matches; while ((matches = wordRegExp.exec(text)) != null) { var word = matches[0].toLowerCase(); if (typeof words[word] == "undefined") { words[word] = 1; } else { words[word]++; } } var wordList = []; for (var word in words) { if (words.hasOwnProperty(word)) { wordList.push([word, words[word]]); } } wordList.sort(function(a, b) { return b[1] - a[1]; }); var topWords = []; for (var i = 0; i < n; i++) { topWords.push(wordList[i][0]); } return topWords; } ```
141,288
<p>Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect.</p> <p>If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?</p>
[ { "answer_id": 141488, "author": "Antti", "author_id": 6037, "author_profile": "https://Stackoverflow.com/users/6037", "pm_score": 0, "selected": false, "text": "<p>Yes, you just need to include the flex swc in your classpath. You can find flex.swc in the flex sdk in frameoworks/lib/flex.swc</p>\n\n<p>edit: One more thing: if you're using Flex Builder you can simply create a new ActionScript project, which will essentially do the same as above.</p>\n" }, { "answer_id": 141522, "author": "Borek Bernard", "author_id": 21728, "author_profile": "https://Stackoverflow.com/users/21728", "pm_score": 3, "selected": false, "text": "<p>This is a very simple app that does only the basic bootstrapping in MXML. This is the MXML:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"onCreationComplete()\"&gt;\n &lt;mx:Script source=\"Script.as\" /&gt;\n&lt;/mx:Application&gt;\n</code></pre>\n\n<p>This is the Script.as:</p>\n\n<pre><code>import mx.controls.Button;\nimport flash.events.MouseEvent;\nimport mx.controls.Alert;\nimport mx.core.Application;\n\nprivate function onCreationComplete() : void {\n var button : Button = new Button();\n button.label = \"Click me\";\n button.addEventListener(MouseEvent.CLICK, function(e : MouseEvent) : void {\n Alert.show(\"Clicked\");\n });\n\n Application.application.addChild(button);\n}\n</code></pre>\n" }, { "answer_id": 141827, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "<p>NOTE: The below answer will not actually work unless you initialize the Flex library first. There is a lot of code involved to do that. See the comments below, or other answers for more details.</p>\n\n<hr>\n\n<p>The main class doesn't even have to be in MXML, just create a class that inherits from <code>mx.core.Application</code> (which is what an MXML class with a <code>&lt;mx:Application&gt;</code> root node is compiled as anyway):</p>\n\n<pre><code>package {\n\n import mx.core.Application;\n\n\n public class MyFancyApplication extends Application {\n\n // do whatever you want here\n\n }\n\n}\n</code></pre>\n\n<p>Also, any ActionScript code compiled with the <code>mxmlc</code> compiler -- or even the Flash CS3 authoring tool -- can use the Flex classes, it's just a matter of making them available in the classpath (refering to the framework SWC when using <code>mxmlc</code> or pointing to a folder containing the source when using either). Unless the document class inherits from <code>mx.core.Application</code> you might run in to some trouble, though, since some things in the framework assume that this is the case.</p>\n" }, { "answer_id": 219571, "author": "jgormley", "author_id": 29738, "author_profile": "https://Stackoverflow.com/users/29738", "pm_score": 5, "selected": true, "text": "<p>I did a simple bootstrap similar to Borek (see below). I would love to get rid of the mxml file, but if I don't have it, I don't get any of the standard themes that come with Flex (haloclassic.swc, etc). Does anybody know how to do what Theo suggests and still have the standard themes applied?</p>\n\n<p>Here's my simplified bootstrapping method:</p>\n\n<p>main.mxml</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;custom:ApplicationClass xmlns:custom=\"components.*\"/&gt;\n</code></pre>\n\n<p>ApplicationClass.as</p>\n\n<pre><code>package components {\n import mx.core.Application;\n import mx.events.FlexEvent;\n import flash.events.MouseEvent;\n import mx.controls.Alert;\n import mx.controls.Button;\n\n public class ApplicationClass extends Application {\n public function ApplicationClass () {\n addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete);\n }\n private function handleComplete( event : FlexEvent ) : void {\n var button : Button = new Button();\n button.label = \"My favorite button\";\n button.styleName=\"halo\"\n button.addEventListener(MouseEvent.CLICK, handleClick);\n addChild( button );\n }\n private function handleClick(e:MouseEvent):void {\n Alert.show(\"You clicked on the button!\", \"Clickity\");\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Here are the necessary updates to use it with Flex 4:</p>\n\n<p>main.mxml</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;local:MyApplication xmlns:fx=\"http://ns.adobe.com/mxml/2009\" xmlns:local=\"components.*\" /&gt;\n</code></pre>\n\n<p>MyApplication.as</p>\n\n<pre><code>package components {\n import flash.events.MouseEvent;\n import mx.controls.Alert;\n import mx.events.FlexEvent;\n import spark.components.Application;\n import spark.components.Button;\n\n public class MyApplication extends Application {\n public function MyApplication() {\n addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler);\n }\n private function creationHandler(e:FlexEvent):void {\n var button : Button = new Button();\n button.label = \"My favorite button\";\n button.styleName=\"halo\"\n button.addEventListener(MouseEvent.CLICK, handleClick);\n addElement( button );\n }\n private function handleClick(e:MouseEvent):void {\n Alert.show(\"You clicked it!\", \"Clickity!\");\n }\n }\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect. If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?
I did a simple bootstrap similar to Borek (see below). I would love to get rid of the mxml file, but if I don't have it, I don't get any of the standard themes that come with Flex (haloclassic.swc, etc). Does anybody know how to do what Theo suggests and still have the standard themes applied? Here's my simplified bootstrapping method: main.mxml ``` <?xml version="1.0" encoding="utf-8"?> <custom:ApplicationClass xmlns:custom="components.*"/> ``` ApplicationClass.as ``` package components { import mx.core.Application; import mx.events.FlexEvent; import flash.events.MouseEvent; import mx.controls.Alert; import mx.controls.Button; public class ApplicationClass extends Application { public function ApplicationClass () { addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete); } private function handleComplete( event : FlexEvent ) : void { var button : Button = new Button(); button.label = "My favorite button"; button.styleName="halo" button.addEventListener(MouseEvent.CLICK, handleClick); addChild( button ); } private function handleClick(e:MouseEvent):void { Alert.show("You clicked on the button!", "Clickity"); } } } ``` --- Here are the necessary updates to use it with Flex 4: main.mxml ``` <?xml version="1.0" encoding="utf-8"?> <local:MyApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:local="components.*" /> ``` MyApplication.as ``` package components { import flash.events.MouseEvent; import mx.controls.Alert; import mx.events.FlexEvent; import spark.components.Application; import spark.components.Button; public class MyApplication extends Application { public function MyApplication() { addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler); } private function creationHandler(e:FlexEvent):void { var button : Button = new Button(); button.label = "My favorite button"; button.styleName="halo" button.addEventListener(MouseEvent.CLICK, handleClick); addElement( button ); } private function handleClick(e:MouseEvent):void { Alert.show("You clicked it!", "Clickity!"); } } } ```
141,291
<p>I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders.</p> <p>Let's see if an example helps. In the current directory we have:</p> <pre><code>&gt;&gt;&gt; os.listdir(os.getcwd()) ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe'] </code></pre> <p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p> <pre><code>&gt;&gt;&gt; for root, dirnames, filenames in os.walk('.'): ... print dirnames ... break ... ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools'] </code></pre> <p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
[ { "answer_id": 141313, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 4, "selected": false, "text": "<pre><code>directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]\n</code></pre>\n" }, { "answer_id": 141317, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": "<p>Like so?</p>\n\n<pre><code>&gt;&gt;&gt;&gt; [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]\n</code></pre>\n" }, { "answer_id": 141318, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 2, "selected": false, "text": "<pre><code>[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]\n</code></pre>\n" }, { "answer_id": 141327, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 8, "selected": true, "text": "<p>Filter the result using os.path.isdir() (and use os.path.join() to get the real path):</p>\n\n<pre><code>&gt;&gt;&gt; [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]\n['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']\n</code></pre>\n" }, { "answer_id": 141336, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 6, "selected": false, "text": "<p>Filter the list using os.path.isdir to detect directories.</p>\n\n<pre><code>filter(os.path.isdir, os.listdir(os.getcwd()))\n</code></pre>\n" }, { "answer_id": 142368, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "<p>Note that, instead of doing <code>os.listdir(os.getcwd())</code>, it's preferable to do <code>os.listdir(os.path.curdir)</code>. One less function call, and it's as portable.</p>\n\n<p>So, to complete the answer, to get a list of directories in a folder:</p>\n\n<pre><code>def listdirs(folder):\n return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]\n</code></pre>\n\n<p>If you prefer full pathnames, then use this function:</p>\n\n<pre><code>def listdirs(folder):\n return [\n d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))\n if os.path.isdir(d)\n ]\n</code></pre>\n" }, { "answer_id": 142535, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 8, "selected": false, "text": "<h2>os.walk</h2>\n\n<p>Use <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"noreferrer\"><code>os.walk</code></a> with <a href=\"https://docs.python.org/3/library/functions.html#next\" rel=\"noreferrer\"><code>next</code></a> item function:</p>\n\n<pre><code>next(os.walk('.'))[1]\n</code></pre>\n\n<p>For <em>Python &lt;=2.5</em> use:</p>\n\n<pre><code>os.walk('.').next()[1]\n</code></pre>\n\n<h3>How this works</h3>\n\n<p><code>os.walk</code> is a generator and calling <code>next</code> will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the <code>[1]</code> index returns only the <code>dirnames</code> from that tuple.</p>\n" }, { "answer_id": 4820270, "author": "antiplex", "author_id": 294930, "author_profile": "https://Stackoverflow.com/users/294930", "pm_score": 2, "selected": false, "text": "<p>being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of <a href=\"https://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python/142368#142368\">ΤΖΩΤΖΙΟΥ's answer</a> :</p>\n\n<blockquote>\n <p>If you prefer full pathnames, then use this function:</p>\n\n<pre><code>def listdirs(folder): \n return [\n d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))\n if os.path.isdir(d)\n]\n</code></pre>\n</blockquote>\n\n<p><strong>for those still on python &lt; 2.4</strong>: the inner construct needs to be a list instead of a tuple and therefore should read like this:</p>\n\n<pre><code>def listdirs(folder): \n return [\n d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]\n if os.path.isdir(d)\n ]\n</code></pre>\n\n<p>otherwise one gets a syntax error.</p>\n" }, { "answer_id": 14378583, "author": "foz", "author_id": 1671320, "author_profile": "https://Stackoverflow.com/users/1671320", "pm_score": 3, "selected": false, "text": "<p>Just to add that using os.listdir() does not <em>\"take a lot of processing vs very simple os.walk().next()[1]\"</em>. This is because os.walk() uses os.listdir() internally. In fact if you test them together:</p>\n\n<pre><code>&gt;&gt;&gt;&gt; import timeit\n&gt;&gt;&gt;&gt; timeit.timeit(\"os.walk('.').next()[1]\", \"import os\", number=10000)\n1.1215229034423828\n&gt;&gt;&gt;&gt; timeit.timeit(\"[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]\", \"import os\", number=10000)\n1.0592019557952881\n</code></pre>\n\n<p>The filtering of os.listdir() is very slightly faster.</p>\n" }, { "answer_id": 15521489, "author": "Malius Arth", "author_id": 2190476, "author_profile": "https://Stackoverflow.com/users/2190476", "pm_score": 1, "selected": false, "text": "<p>For a list of full path names I prefer this version to the other <a href=\"https://stackoverflow.com/a/142368/2190476\">solutions</a> here:</p>\n\n<pre><code>def listdirs(dir):\n return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir) \n if os.path.isdir(os.path.join(dir, x))]\n</code></pre>\n" }, { "answer_id": 26338900, "author": "manty", "author_id": 4085421, "author_profile": "https://Stackoverflow.com/users/4085421", "pm_score": 3, "selected": false, "text": "<p>A very much simpler and elegant way is to use this:</p>\n\n<pre><code> import os\n dir_list = os.walk('.').next()[1]\n print dir_list\n</code></pre>\n\n<p>Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).</p>\n" }, { "answer_id": 38216530, "author": "Travis", "author_id": 267157, "author_profile": "https://Stackoverflow.com/users/267157", "pm_score": 4, "selected": false, "text": "<p>This seems to work too (at least on linux):</p>\n\n<pre><code>import glob, os\nglob.glob('*' + os.path.sep)\n</code></pre>\n" }, { "answer_id": 45232249, "author": "Alexey Gavrilov", "author_id": 4323224, "author_profile": "https://Stackoverflow.com/users/4323224", "pm_score": 0, "selected": false, "text": "<p>A safer option that does not fail when there is no directory.</p>\n\n<pre><code>def listdirs(folder):\n if os.path.exists(folder):\n return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]\n else:\n return []\n</code></pre>\n" }, { "answer_id": 46283751, "author": "nvd", "author_id": 1943525, "author_profile": "https://Stackoverflow.com/users/1943525", "pm_score": 1, "selected": false, "text": "<pre><code>scanDir = \"abc\"\ndirectories = [d for d in os.listdir(scanDir) if os.path.isdir(os.path.join(os.path.abspath(scanDir), d))]\n</code></pre>\n" }, { "answer_id": 48998735, "author": "venkata maddineni", "author_id": 6318033, "author_profile": "https://Stackoverflow.com/users/6318033", "pm_score": -1, "selected": false, "text": "<pre><code>-- This will exclude files and traverse through 1 level of sub folders in the root\n\ndef list_files(dir):\n List = []\n filterstr = ' '\n for root, dirs, files in os.walk(dir, topdown = True):\n #r.append(root)\n if (root == dir):\n pass\n elif filterstr in root:\n #filterstr = ' '\n pass\n else:\n filterstr = root\n #print(root)\n for name in files:\n print(root)\n print(dirs)\n List.append(os.path.join(root,name))\n #print(os.path.join(root,name),\"\\n\")\n print(List,\"\\n\")\n\n return List\n</code></pre>\n" }, { "answer_id": 55605290, "author": "KBLee", "author_id": 9605162, "author_profile": "https://Stackoverflow.com/users/9605162", "pm_score": 4, "selected": false, "text": "<p>Using list comprehension,</p>\n\n<pre><code>[a for a in os.listdir() if os.path.isdir(a)]\n</code></pre>\n\n<p>I think It is the simplest way</p>\n" }, { "answer_id": 63001540, "author": "joelostblom", "author_id": 2166823, "author_profile": "https://Stackoverflow.com/users/2166823", "pm_score": 2, "selected": false, "text": "<p>Python 3.4 introduced <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">the <code>pathlib</code> module</a> into the standard library, which provides an object oriented approach to handle filesystem paths:</p>\n<pre><code>from pathlib import Path\n\np = Path('./')\n[f for f in p.iterdir() if f.is_dir()]\n</code></pre>\n" }, { "answer_id": 63715910, "author": "pandichef", "author_id": 10134077, "author_profile": "https://Stackoverflow.com/users/10134077", "pm_score": 1, "selected": false, "text": "<p>FWIW, the <code>os.walk</code> approach is almost 10x faster than the list comprehension and filter approaches:</p>\n<pre class=\"lang-py prettyprint-override\"><code>In [30]: %timeit [d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]\n1.23 ms ± 97.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nIn [31]: %timeit list(filter(os.path.isdir, os.listdir(os.getcwd())))\n1.13 ms ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nIn [32]: %timeit next(os.walk(os.getcwd()))[1]\n132 µs ± 9.34 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n" }, { "answer_id": 66170445, "author": "G M", "author_id": 2132157, "author_profile": "https://Stackoverflow.com/users/2132157", "pm_score": 2, "selected": false, "text": "<p>You could also use <a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\"><code>os.scandir</code></a>:</p>\n<pre><code>with os.scandir(os.getcwd()) as mydir:\n dirs = [i.name for i in mydir if i.is_dir()]\n</code></pre>\n<p>In case you want the full path you can use <code>i.path</code>.</p>\n<blockquote>\n<p>Using scandir() instead of listdir() can significantly increase the\nperformance of code that also needs file type or file attribute\ninformation, because os.DirEntry objects expose this information if\nthe operating system provides it when scanning a directory.</p>\n</blockquote>\n" }, { "answer_id": 69067814, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 2, "selected": false, "text": "<p>2021 answer using <a href=\"https://docs.python.org/3/library/glob.html\" rel=\"nofollow noreferrer\"><code>glob</code></a>:</p>\n<pre><code>import glob, os\n\np = &quot;/some/path/&quot;\nfor d in glob.glob(p + &quot;*&quot; + os.path.sep):\n print(d)\n</code></pre>\n" }, { "answer_id": 71596385, "author": "Darren Weber", "author_id": 1172685, "author_profile": "https://Stackoverflow.com/users/1172685", "pm_score": 1, "selected": false, "text": "<p>Using python 3.x with <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib.Path.iter_dir</a></p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ mkdir tmpdir\n$ mkdir -p tmpdir/a/b/c\n$ mkdir -p tmpdir/x/y/z\n\n$ touch tmpdir/a/b/c/abc.txt\n$ touch tmpdir/a/b/ab.txt\n$ touch tmpdir/a/a.txt\n\n$ python --version\nPython 3.7.12\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; from pathlib import Path\n&gt;&gt;&gt; tmpdir = Path(&quot;./tmpdir&quot;)\n&gt;&gt;&gt; [d for d in tmpdir.iterdir() if d.is_dir]\n[PosixPath('tmpdir/x'), PosixPath('tmpdir/a')]\n&gt;&gt;&gt; sorted(d for d in tmpdir.iterdir() if d.is_dir)\n[PosixPath('tmpdir/a'), PosixPath('tmpdir/x')]\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders. Let's see if an example helps. In the current directory we have: ``` >>> os.listdir(os.getcwd()) ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe'] ``` However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following: ``` >>> for root, dirnames, filenames in os.walk('.'): ... print dirnames ... break ... ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools'] ``` However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.
Filter the result using os.path.isdir() (and use os.path.join() to get the real path): ``` >>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ] ['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac'] ```
141,302
<p>Is there a way to check if a file has been opened by ReWrite in Delphi? </p> <p>Code would go something like this:</p> <pre><code>AssignFile(textfile, 'somefile.txt'); if not textFile.IsOpen then Rewrite(textFile); </code></pre>
[ { "answer_id": 141339, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 5, "selected": true, "text": "<p>You can get the filemode. (One moment, I'll create an example).</p>\n\n<p>TTextRec(txt).Mode gives you the mode:</p>\n\n<pre><code>55216 = closed\n55217 = open read\n55218 = open write\n\nfmClosed = $D7B0;\nfmInput = $D7B1;\nfmOutput = $D7B2;\nfmInOut = $D7B3;\n</code></pre>\n\n<p>Search TTextRec in the system unit for more information.</p>\n" }, { "answer_id": 141376, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>function IsFileInUse(fName: string) : boolean;\nvar\n HFileRes: HFILE;\nbegin\n Result := False;\n if not FileExists(fName) then begin\n Exit;\n end;\n\n HFileRes := CreateFile(PChar(fName)\n ,GENERIC_READ or GENERIC_WRITE\n ,0\n ,nil\n ,OPEN_EXISTING\n ,FILE_ATTRIBUTE_NORMAL\n ,0);\n\n Result := (HFileRes = INVALID_HANDLE_VALUE);\n\n if not(Result) then begin\n CloseHandle(HFileRes);\n end;\nend;\n</code></pre>\n" }, { "answer_id": 7730228, "author": "Mike Baran", "author_id": 990053, "author_profile": "https://Stackoverflow.com/users/990053", "pm_score": 1, "selected": false, "text": "<p>I found it easier to keep a boolean variable as a companion; example: <code>bFileIsOpen</code>. Wherever the file is opened, set <code>bFileIsOpen := true</code> then, whenever you need to know if the file is open, just test this variable; example: <code>if (bFileIsOpen) then Close(datafile);</code></p>\n" }, { "answer_id": 8166349, "author": "Ramon", "author_id": 1051656, "author_profile": "https://Stackoverflow.com/users/1051656", "pm_score": 3, "selected": false, "text": "<p>This works fine:</p>\n\n<pre><code>function IsOpen(const txt:TextFile):Boolean;\nconst\n fmTextOpenRead = 55217;\n fmTextOpenWrite = 55218;\nbegin\n Result := (TTextRec(txt).Mode = fmTextOpenRead) or (TTextRec(txt).Mode = fmTextOpenWrite)\nend;\n</code></pre>\n" }, { "answer_id": 27875732, "author": "Whitehairedgeezer", "author_id": 3074340, "author_profile": "https://Stackoverflow.com/users/3074340", "pm_score": -1, "selected": false, "text": "<p>Joseph's answer works perfectly - I called the function <code>filenotopen</code> and changed the line if </p>\n\n<pre><code>Result := (HFileRes = INVALID_HANDLE_VALUE);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Result := NOT (HFileRes = INVALID_HANDLE_VALUE);\n</code></pre>\n\n<p>I also removed the line 'if not(Result) then begin' (and the 'end') so that it ALWAYS closes the handle or subsequent assignments and reads give errors</p>\n\n<p>I now call it like this</p>\n\n<pre><code>if filenotopen(filename) then \n begin\n assignfile(f,filename);\n reset(f)\n etc;\n end\nelse\n message('file open by a different program')\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
Is there a way to check if a file has been opened by ReWrite in Delphi? Code would go something like this: ``` AssignFile(textfile, 'somefile.txt'); if not textFile.IsOpen then Rewrite(textFile); ```
You can get the filemode. (One moment, I'll create an example). TTextRec(txt).Mode gives you the mode: ``` 55216 = closed 55217 = open read 55218 = open write fmClosed = $D7B0; fmInput = $D7B1; fmOutput = $D7B2; fmInOut = $D7B3; ``` Search TTextRec in the system unit for more information.
141,315
<p>Is there a way to check to see if a date/time is valid you would think these would be easy to check:</p> <pre><code>$date = '0000-00-00'; $time = '00:00:00'; $dateTime = $date . ' ' . $time; if(strtotime($dateTime)) { // why is this valid? } </code></pre> <p>what really gets me is this:</p> <pre><code>echo date('Y-m-d', strtotime($date)); </code></pre> <p>results in: "1999-11-30",</p> <p>huh? i went from 0000-00-00 to 1999-11-30 ???</p> <p>I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?</p> <p>Edit: People are asking what i'm running: Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux</p>
[ { "answer_id": 141341, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>echo date('Y-m-d', strtotime($date));</p>\n \n <p>results in: \"1999-11-30\"</p>\n</blockquote>\n\n<p>The result of <code>strtotime</code> is 943920000 - this is the number of seconds, roughly, between the <a href=\"http://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow noreferrer\">Unix epoch</a> (base from which time is measured) to 1999-11-30. </p>\n\n<p>There is a <strong>documented <a href=\"http://bugs.php.net/bug.php?id=17123\" rel=\"nofollow noreferrer\">mysql bug</a></strong> on <code>mktime(), localtime(), strtotime()</code> all returning this odd value when you try a pre-epoch time (including \"0000-00-00 00:00:00\"). There's some debate on the linked thread as to whether this is actually a bug:</p>\n\n<blockquote>\n <p>Since the time stamp is started from 1970, I don't think it supposed to\n work in anyways.</p>\n</blockquote>\n\n<p>Below is a function that I use for converting dateTimes such as the above to a timestamp for comparisons, etc, which may be of some use to you, for dates beyond \"0000-00-00 00:00:00\"</p>\n\n<pre><code>/**\n * Converts strings of the format \"YYYY-MM-DD HH:MM:SS\" into php dates\n */\nfunction convert_date_string($date_string)\n{\n list($date, $time) = explode(\" \", $date_string);\n list($hours, $minutes, $seconds) = explode(\":\", $time);\n list($year, $month, $day) = explode(\"-\", $date);\n return mktime($hours, $minutes, $seconds, $month, $day, $year);\n}\n</code></pre>\n" }, { "answer_id": 141365, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 6, "selected": true, "text": "<p>From <a href=\"http://php.net/manual/en/function.checkdate.php#78362\" rel=\"noreferrer\">php.net</a></p>\n\n<pre><code>&lt;?php\nfunction isValidDateTime($dateTime)\n{\n if (preg_match(\"/^(\\d{4})-(\\d{2})-(\\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/\", $dateTime, $matches)) {\n if (checkdate($matches[2], $matches[3], $matches[1])) {\n return true;\n }\n }\n\n return false;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 148414, "author": "user22960", "author_id": 22960, "author_profile": "https://Stackoverflow.com/users/22960", "pm_score": 1, "selected": false, "text": "<p>Don't expect coherent results when you're out of range:</p>\n\n<p>cf <a href=\"http://us2.php.net/manual/en/function.strtotime.php\" rel=\"nofollow noreferrer\">strtotime</a></p>\n\n<p>cf <a href=\"http://www.gnu.org/software/tar/manual/html_node/Calendar-date-items.html#SEC116\" rel=\"nofollow noreferrer\">Gnu Calendar-date-items</a>.html</p>\n\n<blockquote>\n <p>\"For numeric months, the ISO 8601\n format ‘year-month-day’ is allowed,\n where year is any positive number,\n <strong>month is a number between 01\n and 12</strong>, and <strong>day is a\n number between 01 and 31</strong>. A\n leading zero must be present if a\n number is less than ten.\"</p>\n</blockquote>\n\n<p>So '0000-00-00' gives weird results, that's logical!</p>\n\n<hr>\n\n<blockquote>\n <p>\"Additionally, <strong>not all\n platforms support negative timestamps,\n therefore your date range may be\n limited to no earlier than the Unix\n epoch</strong>. This means that e.g.\n %e, %T, %R and %D (there might be\n more) and <strong>dates prior to Jan\n 1, 1970 will not work on Windows, some\n Linux distributions, and a few other\n operating systems</strong>.\"</p>\n</blockquote>\n\n<p>cf <a href=\"http://us2.php.net/manual/en/function.strftime.php\" rel=\"nofollow noreferrer\">strftime</a></p>\n\n<hr>\n\n<p>Use <a href=\"http://us2.php.net/manual/en/function.checkdate.php\" rel=\"nofollow noreferrer\">checkdate</a> function instead (more robust):</p>\n\n<blockquote>\n <p>month:\n The <strong>month is between 1 and 12 inclusive</strong>.</p>\n \n <p>day:\n The day is within the allowed number of days for the given\n month. Leap year s are taken\n into consideration.</p>\n \n <p>year:\n The <strong>year is between 1 and 32767 inclusive</strong>.</p>\n</blockquote>\n" }, { "answer_id": 2069817, "author": "dave", "author_id": 251324, "author_profile": "https://Stackoverflow.com/users/251324", "pm_score": 1, "selected": false, "text": "<p>If you just want to handle a date conversion without the time for a mysql date field, you can modify this great code as I did.\nOn my version of PHP without performing this function I get \"0000-00-00\" every time. Annoying. </p>\n\n<pre><code>function ConvertDateString ($DateString)\n{\n list($year, $month, $day) = explode(\"-\", $DateString);\n return date (\"Y-m-d, mktime (0, 0, 0, $month, $day, $year));\n}\n</code></pre>\n" }, { "answer_id": 4605939, "author": "asupynuk", "author_id": 564167, "author_profile": "https://Stackoverflow.com/users/564167", "pm_score": 1, "selected": false, "text": "<p>This version allows for the field to be empty, has dates in mm/dd/yy or mm/dd/yyyy format, allow for single digit hours, adds optional am/pm, and corrects some subtle flaws in the time match.</p>\n\n<p>Still allows some pathological times like '23:14 AM'.</p>\n\n<pre><code>function isValidDateTime($dateTime) {\n if (trim($dateTime) == '') {\n return true;\n }\n if (preg_match('/^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{2,4})(\\s+(([01]?[0-9])|(2[0-3]))(:[0-5][0-9]){0,2}(\\s+(am|pm))?)?$/i', $dateTime, $matches)) {\n list($all,$mm,$dd,$year) = $matches;\n if ($year &lt;= 99) {\n $year += 2000;\n }\n return checkdate($mm, $dd, $year);\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 7475555, "author": "martin", "author_id": 953300, "author_profile": "https://Stackoverflow.com/users/953300", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\n\nfunction is_date( $str ) {\n $stamp = strtotime( $str );\n\n if (!is_numeric($stamp)) {\n return FALSE;\n }\n $month = date( 'm', $stamp );\n $day = date( 'd', $stamp );\n $year = date( 'Y', $stamp );\n\n if (checkdate($month, $day, $year)) {\n return TRUE;\n }\n return FALSE;\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 8938609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have been just changing the martin answer above, which will validate any type of date and return in the format you like. </p>\n\n<p>Just change the format by editing below line of script\nstrftime(\"10-10-2012\", strtotime($dt));</p>\n\n<pre><code>&lt;?php\necho is_date(\"13/04/10\");\n\nfunction is_date( $str ) {\n $flag = strpos($str, '/');\n\n if(intval($flag)&lt;=0){\n $stamp = strtotime( $str );\n } else {\n list($d, $m, $y) = explode('/', $str); \n $stamp = strtotime(\"$d-$m-$y\");\n } \n //var_dump($stamp) ;\n\n if (!is_numeric($stamp)) {\n //echo \"ho\" ;\n return \"not a date\" ; \n }\n\n $month = date( 'n', $stamp ); // use n to get date in correct format\n $day = date( 'd', $stamp );\n $year = date( 'Y', $stamp );\n\n if (checkdate($month, $day, $year)) {\n $dt = \"$year-$month-$day\" ;\n return strftime(\"%d-%b-%Y\", strtotime($dt));\n //return TRUE;\n } else {\n return \"not a date\" ;\n }\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 9742388, "author": "Josue", "author_id": 1133003, "author_profile": "https://Stackoverflow.com/users/1133003", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\nfunction is_valid_date($user_date=false, $valid_date = \"1900-01-01\") {\n $user_date = date(\"Y-m-d H:i:s\",strtotime($user_date));\n return strtotime($user_date) &gt;= strtotime($valid_date) ? true : false;\n}\n\necho is_valid_date(\"00-00-00\") ? 1 : 0; // return 0\n\necho is_valid_date(\"3/5/2011\") ? 1 : 0; // return 1\n</code></pre>\n" }, { "answer_id": 9933557, "author": "Izkata", "author_id": 500202, "author_profile": "https://Stackoverflow.com/users/500202", "pm_score": 3, "selected": false, "text": "<p>As mentioned here: <a href=\"https://bugs.php.net/bug.php?id=45647\" rel=\"noreferrer\">https://bugs.php.net/bug.php?id=45647</a></p>\n\n<blockquote>\n <p>There is no bug here, 00-00-00 means 2000-00-00, which is 1999-12-00,\n which is 1999-11-30. No bug, perfectly normal.</p>\n</blockquote>\n\n<p>And as shown with a few tests, rolling backwards is expected behavior, if a little unsettling:</p>\n\n<pre><code>&gt;&gt; date('Y-m-d', strtotime('2012-03-00'))\nstring: '2012-02-29'\n&gt;&gt; date('Y-m-d', strtotime('2012-02-00'))\nstring: '2012-01-31'\n&gt;&gt; date('Y-m-d', strtotime('2012-01-00'))\nstring: '2011-12-31'\n&gt;&gt; date('Y-m-d', strtotime('2012-00-00'))\nstring: '2011-11-30'\n</code></pre>\n" }, { "answer_id": 10313431, "author": "eli", "author_id": 281924, "author_profile": "https://Stackoverflow.com/users/281924", "pm_score": 0, "selected": false, "text": "<p>I have used the following code to validate dates coming from ExtJS applications. </p>\n\n<pre><code>function check_sql_date_format($date) {\n $date = substr($date, 0, 10);\n list($year, $month, $day) = explode('-', $date);\n if (!is_numeric($year) || !is_numeric($month) || !is_numeric($day)) {\n return false;\n }\n return checkdate($month, $day, $year);\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
Is there a way to check to see if a date/time is valid you would think these would be easy to check: ``` $date = '0000-00-00'; $time = '00:00:00'; $dateTime = $date . ' ' . $time; if(strtotime($dateTime)) { // why is this valid? } ``` what really gets me is this: ``` echo date('Y-m-d', strtotime($date)); ``` results in: "1999-11-30", huh? i went from 0000-00-00 to 1999-11-30 ??? I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this? Edit: People are asking what i'm running: Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux
From [php.net](http://php.net/manual/en/function.checkdate.php#78362) ``` <?php function isValidDateTime($dateTime) { if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) { if (checkdate($matches[2], $matches[3], $matches[1])) { return true; } } return false; } ?> ```
141,332
<p>I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:</p> <pre><code>sub _read_from_client { my ($file_handle) = @_; while (my $line = &lt;$file_handle&gt;) { print STDOUT $line; } return; } </code></pre> <p>Importantly, the snippet needs to work in Win32 platform. There are many solutions for *nix platforms that I'm not interested in. I'm using ActivePerl 5.10.</p>
[ { "answer_id": 141770, "author": "xdg", "author_id": 11800, "author_profile": "https://Stackoverflow.com/users/11800", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://www.perlmonks.org/?node_id=529812\" rel=\"nofollow noreferrer\">This thread</a> on <a href=\"http://www.perlmonks.org\" rel=\"nofollow noreferrer\">Perlmonks</a> suggests you can make a socket nonblocking on Windows in Perl this way:</p>\n\n<pre><code>ioctl($socket, 0x8004667e, 1);\n</code></pre>\n\n<p>More details and resources in that thread</p>\n" }, { "answer_id": 143138, "author": "Corion", "author_id": 21731, "author_profile": "https://Stackoverflow.com/users/21731", "pm_score": 2, "selected": false, "text": "<p>If you don't want to go the low-level route, you will have to look at the other more frameworked solutions.</p>\n\n<p>You can use a <a href=\"http://search.cpan.org/perldoc?threads\" rel=\"nofollow noreferrer\">thread</a> to read from the input and have it stuff all data it reads into a <a href=\"http://search.cpan.org/perldoc?Thread::Queue\" rel=\"nofollow noreferrer\">Thread::Queue</a> which you then handle in your main thread.</p>\n\n<p>You can look at <a href=\"http://search.cpan.org/perldoc?POE\" rel=\"nofollow noreferrer\">POE</a> which implements an event based framework, especially <a href=\"http://search.cpan.org/perldoc?POE::Wheel::Run::Win32\" rel=\"nofollow noreferrer\">POE::Wheel::Run::Win32</a>. Potentially, you can also steal the code from it to implement the nonblocking reads yourself.</p>\n\n<p>You can look at [Coro], which implements a cooperative multitasking system using coroutines. This is mostly similar to threads except that you get userspace threads, not system threads.</p>\n\n<p>You haven't stated how far up you want to go, but your choice is between <code>sysread</code> and a framework, or writing said framework yourself. The easiest route to go is just to use threads or by going through the code of <code>Poe::Wheel::Run::Win32</code>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7045/" ]
I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this: ``` sub _read_from_client { my ($file_handle) = @_; while (my $line = <$file_handle>) { print STDOUT $line; } return; } ``` Importantly, the snippet needs to work in Win32 platform. There are many solutions for \*nix platforms that I'm not interested in. I'm using ActivePerl 5.10.
[This thread](http://www.perlmonks.org/?node_id=529812) on [Perlmonks](http://www.perlmonks.org) suggests you can make a socket nonblocking on Windows in Perl this way: ``` ioctl($socket, 0x8004667e, 1); ``` More details and resources in that thread
141,344
<p>How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.</p> <p>Is there a better way of doing this? Something like <a href="https://ss64.com/nt/find.html" rel="nofollow noreferrer">FIND</a> or <a href="https://ss64.com/nt/findstr.html" rel="nofollow noreferrer">FINDSTR</a> operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.</p> <pre><code>FOR /F &quot;delims=;&quot; %%P IN (&quot;%PATH%&quot;) DO ( @ECHO %%~P ) </code></pre>
[ { "answer_id": 141385, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 5, "selected": false, "text": "<p>This may work:</p>\n<pre><code>echo ;%PATH%; | find /C /I &quot;;&lt;string&gt;;&quot;\n</code></pre>\n<p>It should give you 0 if the string is not found and 1 or more if it is.</p>\n" }, { "answer_id": 142381, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "<p>If your question was \"why doesn't this cmd script fragment work?\" then the answer is that <code>for /f</code> iterates over lines. The <code>delims</code> split lines into fields, but you're only capturing the first field in <code>%%P</code>. There is no way to capture an arbitrary number of fields with a <code>for /f</code> loop.</p>\n" }, { "answer_id": 142395, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 1, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/questions/141344/how-to-check-if-a-directory-exists-in-path/141385#141385\">Randy's answer</a>, you have to make sure a substring of the target isn't found.</p>\n<pre><code>if a%X%==a%PATH% echo %X% is in PATH\necho %PATH% | find /c /i &quot;;%X%&quot;\nif errorlevel 1 echo %X% is in PATH\necho %PATH% | find /c /i &quot;%X%;&quot;\nif errorlevel 1 echo %X% is in PATH\n</code></pre>\n" }, { "answer_id": 142605, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 2, "selected": false, "text": "<p>I took your implementation using the <em>for</em> loop and extended it into something that iterates through all elements of the path. Each iteration of the for loop removes the first element of the path (%p) from the entire path (held in %q and %r).</p>\n\n<pre><code>@echo off\nSET MYPATHCOPY=%PATH%\n\n:search\nfor /f \"delims=; tokens=1,2*\" %%p in (\"%MYPATHCOPY%\") do (\n @echo %%~p\n SET MYPATHCOPY=%%~q;%%~r\n)\n\nif \"%MYPATHCOPY%\"==\";\" goto done;\ngoto search;\n\n:done\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>Z:\\&gt;path.bat\nC:\\Program Files\\Microsoft DirectX SDK (November 2007)\\Utilities\\Bin\\x86\nc:\\program files\\imagemagick-6.3.4-q16\nC:\\WINDOWS\\system32\nC:\\WINDOWS\nC:\\SFU\\common\\\nc:\\Program Files\\Debugging Tools for Windows\nC:\\Program Files\\Nmap\n</code></pre>\n" }, { "answer_id": 157653, "author": "ketorin", "author_id": 24094, "author_profile": "https://Stackoverflow.com/users/24094", "pm_score": 1, "selected": false, "text": "<p>You mention that you want to avoid adding the directory to search path if it already exists there. Is your intention to store the directory permanently to the path, or just temporarily for batch file's sake?</p>\n\n<p>If you wish to add (or remove) directories permanently to PATH, take a look at Path Manager (pathman.exe) utility in Windows Resource Kit Tools for administrative tasks, <a href=\"http://support.microsoft.com/kb/927229\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/927229</a>. With that you can add or remove components of both system and user paths, and it will handle anomalies such as duplicate entries.</p>\n\n<p>If you need to modify the path only temporarily for a batch file, I would just add the extra path in front of the path, with the risk of slight performance hit because of duplicate entry in the path.</p>\n" }, { "answer_id": 157744, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"http://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"nofollow noreferrer\"><code>for</code></a> and <a href=\"http://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"nofollow noreferrer\"><code>delims</code></a>, you cannot capture an arbitrary number of fields (as <a href=\"https://stackoverflow.com/questions/141344/how-to-check-if-directory-exists-in-path#142381\">Adam pointed out</a> as well) so you have to use a looping technique instead. The following command script will list each path in the <code>PATH</code> environment variable on a separate line:</p>\n\n<pre><code>@echo off \nsetlocal \nif \"%~1\"==\"\" (\n set PATHQ=%PATH%\n) else (\n set PATHQ=%~1 ) \n:WHILE\n if \"%PATHQ%\"==\"\" goto WEND\n for /F \"delims=;\" %%i in (\"%PATHQ%\") do echo %%i\n for /F \"delims=; tokens=1,*\" %%i in (\"%PATHQ%\") do set PATHQ=%%j\n goto WHILE \n:WEND\n</code></pre>\n\n<p>It simulates a classical <em>while</em>…<em>wend</em> construct found in many programming languages.\nWith this in place, you can use something like <a href=\"http://technet.microsoft.com/en-us/library/bb490907.aspx\" rel=\"nofollow noreferrer\"><code>findstr</code></a> to subsequently filter and look for a particular path. For example, if you saved the above script in a file called <code>tidypath.cmd</code> then here is how you could pipe to <code>findstr</code>, looking for paths under the standard programs directory (using a case-insensitive match):</p>\n\n<pre><code>&gt; tidypath | findstr /i \"%ProgramFiles%\"\n</code></pre>\n" }, { "answer_id": 2559366, "author": "bert bruynooghe", "author_id": 306730, "author_profile": "https://Stackoverflow.com/users/306730", "pm_score": 5, "selected": false, "text": "<p>Another way to check if something is in the path is to execute some innocent executable that is not going to fail if it's there, and check the result.</p>\n<p>As an example, the following code snippet checks if <a href=\"https://en.wikipedia.org/wiki/Apache_Maven\" rel=\"nofollow noreferrer\">Maven</a> is in the path:</p>\n<pre><code>mvn --help &gt; NUL 2&gt; NUL\nif errorlevel 1 goto mvnNotInPath\n</code></pre>\n<p>So I try to run <em>mvn --help</em>, ignore the output (I don't actually want to see the help if Maven is there) (<em>&gt; NUL</em>), and also don't display the error message if Maven was not found (<em>2&gt; NUL</em>).</p>\n" }, { "answer_id": 5296725, "author": "Noam Manos", "author_id": 658497, "author_profile": "https://Stackoverflow.com/users/658497", "pm_score": 1, "selected": false, "text": "<p>Add the directory to PATH if it does not already exist:</p>\n<pre><code>set myPath=c:\\mypath\nFor /F &quot;Delims=&quot; %%I In ('echo %PATH% ^| find /C /I &quot;%myPath%&quot;') Do set pathExists=%%I 2&gt;Nul\nIf %pathExists%==0 (set PATH=%myPath%;%PATH%)\n</code></pre>\n" }, { "answer_id": 5572997, "author": "mousio", "author_id": 653295, "author_profile": "https://Stackoverflow.com/users/653295", "pm_score": 2, "selected": false, "text": "<p>This will look for an exact but case-insensitive match, so mind any trailing backslashes etc.:</p>\n\n<pre><code>for %P in (\"%path:;=\";\"%\") do @if /i %P==\"PATH_TO_CHECK\" echo %P exists in PATH\n</code></pre>\n\n<p>or, in a batch file (e.g. checkpath.bat) which takes an argument:</p>\n\n<pre><code>@for %%P in (\"%path:;=\";\"%\") do @if /i %%P==\"%~1\" echo %%P exists in PATH\n</code></pre>\n\n<p>In the latter form, one could call e.g. <code>checkpath \"%ProgramFiles%\"</code> to see if the specified path already exists in PATH.</p>\n\n<p>Please note that this implementation assumes no semicolons or quotes are present inside a single path item.</p>\n" }, { "answer_id": 5573965, "author": "Andriy M", "author_id": 297408, "author_profile": "https://Stackoverflow.com/users/297408", "pm_score": 1, "selected": false, "text": "<p>Just as an alternative:</p>\n\n<ol>\n<li><p>In the folder you are going to search the <code>PATH</code> variable for, create a temporary file with such an unusual name that you would never ever expect any other file on your computer to have.</p></li>\n<li><p>Use the standard batch scripting construct that lets you perform the search for a file by looking up a directory list defined by some environment variable (typically <code>PATH</code>).</p></li>\n<li><p>Check if the result of the search matches the path in question, and display the outcome.</p></li>\n<li><p>Delete the temporary file.</p></li>\n</ol>\n\n<p>This might look like this:</p>\n\n<pre><code>@ECHO OFF\nSET \"mypath=D:\\the\\searched-for\\path\"\nSET unusualname=nowthisissupposedtobesomeveryunusualfilename\nECHO.&gt;\"%mypath%\\%unusualname%\"\nFOR %%f IN (%unusualname%) DO SET \"foundpath=%%~dp$PATH:f\"\nERASE \"%mypath%\\%unusualname%\"\nIF \"%mypath%\" == \"%foundpath%\" (\n ECHO The dir exists in PATH\n) ELSE (\n ECHO The dir DOES NOT exist in PATH\n)\n</code></pre>\n\n<p>Known issues:</p>\n\n<ol>\n<li><p>The method can work only if the directory exists (which isn't always the case).</p></li>\n<li><p>Creating / deleting files in a directory affects its 'modified date/time' attribute (which may be an undesirable effect sometimes).</p></li>\n<li><p>Making up a globally unique file name in one's mind cannot be considered very reliable. Generating such a name is itself not a trivial task.</p></li>\n</ol>\n" }, { "answer_id": 6802486, "author": "Kevin Edwards", "author_id": 244173, "author_profile": "https://Stackoverflow.com/users/244173", "pm_score": 2, "selected": false, "text": "<p>You can also use substring replacement to test for the presence of a substring. Here I remove quotes to create PATH_NQ, then I remove \"c:\\mydir\" from the PATH_NQ and compare it to the original to see if anything changed:</p>\n\n<pre><code>set PATH_NQ=%PATH:\"=%\nif not \"%PATH_NQ%\"==\"%PATH_NQ:c:\\mydir=%\" goto already_in_path\nset PATH=%PATH%;c:\\mydir\n:already_in_path\n</code></pre>\n" }, { "answer_id": 7685205, "author": "Chris Degnen", "author_id": 879601, "author_profile": "https://Stackoverflow.com/users/879601", "pm_score": 1, "selected": false, "text": "<p>This version works fairly well. It simply checks whether executable <em>vim71</em> (<a href=\"https://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"nofollow noreferrer\">Vim</a> 7.1) is in the path, and prepends it if not.</p>\n<pre><code>@echo off\necho %PATH% | find /c /i &quot;vim71&quot; &gt; nul\nif not errorlevel 1 goto jump\nPATH = C:\\Program Files\\Vim\\vim71\\;%PATH%\n:jump\n</code></pre>\n<p>This demo is to illustrate the <em>errorlevel</em> logic:</p>\n<pre><code>@echo on\necho %PATH% | find /c /i &quot;Windows&quot;\nif &quot;%errorlevel%&quot;==&quot;0&quot; echo Found Windows\necho %PATH% | find /c /i &quot;Nonesuch&quot;\nif &quot;%errorlevel%&quot;==&quot;0&quot; echo Found Nonesuch\n</code></pre>\n<p>The logic is reversed in the <em>vim71</em> code since <em>errorlevel</em> 1 is equivalent to <em>errorlevel</em> &gt;= 1. It follows that <em>errorlevel</em> 0 would always evaluate true, so &quot;<code>not errorlevel 1</code>&quot; is used.</p>\n<p><strong>Postscript</strong>: Checking may not be necessary if you use <a href=\"https://ss64.com/nt/setlocal.html\" rel=\"nofollow noreferrer\">SETLOCAL</a> and <a href=\"https://ss64.com/nt/endlocal.html\" rel=\"nofollow noreferrer\">ENDLOCAL</a> to localise your environment settings, e.g.,</p>\n<pre><code>@echo off\nsetlocal\nPATH = C:\\Program Files\\Vim\\vim71\\;%PATH%\nrem your code here\nendlocal\n</code></pre>\n<p>After ENDLOCAL you are back with your original path.</p>\n" }, { "answer_id": 7731616, "author": "Redsplinter", "author_id": 990204, "author_profile": "https://Stackoverflow.com/users/990204", "pm_score": 2, "selected": false, "text": "<p>I've combined some of the above answers to come up with this to ensure that a given path entry exists <em>exactly as given</em> with as much brevity as possible and no junk echos on the command line.</p>\n\n<pre><code>set myPath=&lt;pathToEnsure | %1&gt;\necho ;%PATH%; | find /C /I \";%myPath%;\" &gt;nul\nif %ERRORLEVEL% NEQ 0 set PATH=%PATH%;%myPath%\n</code></pre>\n" }, { "answer_id": 8046515, "author": "dbenham", "author_id": 1012053, "author_profile": "https://Stackoverflow.com/users/1012053", "pm_score": 7, "selected": false, "text": "<p>First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.</p>\n\n<p>For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.</p>\n\n<p>From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:</p>\n\n<ol>\n<li><p><strong>The trailing <code>\\</code> is optional in a path</strong><br>\nMost paths work equally well both with and without the trailing <code>\\</code>. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing <code>\\</code>. This is probably the most common practical issue when searching a PATH for a match.</p>\n\n<ul>\n<li>There is one exception: The relative path <code>C:</code> (meaning the current working directory of drive C) is very different than <code>C:\\</code> (meaning the root directory of drive C)\n<br/><br/></li>\n</ul></li>\n<li><p><strong>Some paths have alternate short names</strong><br>\nAny path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.</p></li>\n<li><p><strong>Windows accepts both <code>/</code> and <code>\\</code> as folder separators within a path.</strong><br>\nThis is not seen very often, but a path can be specified using <code>/</code> instead of <code>\\</code> and it will function just fine within PATH (as well as in many other Windows contexts)</p></li>\n<li><p><strong>Windows treats consecutive folder separators as one logical separator.</strong><br>\nC:\\FOLDER\\\\ and C:\\FOLDER\\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append <code>\\</code> to a path without bothering to check if the trailing <code>\\</code> already exists. But this obviously can cause problems if trying to perform an exact string match.</p>\n\n<ul>\n<li>Exceptions: Not only is <code>C:</code>, different than <code>C:\\</code>, but <code>C:\\</code> (a valid path), is different than <code>C:\\\\</code> (an invalid path).\n<br/><br/></li>\n</ul></li>\n<li><p><strong>Windows trims trailing dots and spaces from file and directory names.</strong><br>\n<code>\"C:\\test. \"</code> is equivalent to <code>\"C:\\test\"</code>.</p></li>\n<li><p><strong>The current <code>.\\</code> and parent <code>..\\</code> folder specifiers may appear within a path</strong><br>\nUnlikely to be seen in real life, but something like <code>C:\\.\\parent\\child\\..\\.\\child\\</code> is equivalent to <code>C:\\parent\\child</code></p></li>\n<li><p><strong>A path can optionally be enclosed within double quotes.</strong><br>\nA path is often enclosed in quotes to protect against special characters like <code>&lt;space&gt;</code> <code>,</code> <code>;</code> <code>^</code> <code>&amp;</code> <code>=</code>. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a <code>;</code>, but the quotes may be present never-the-less.</p></li>\n<li><p><strong>A path may be fully qualified or relative.</strong><br>\nA fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths: </p>\n\n<ul>\n<li><strong><code>D:</code></strong> is relative to the current working directory of volume D:</li>\n<li><strong><code>\\myPath</code></strong> is relative to the current working volume (could be C:, D: etc.)</li>\n<li><strong><code>myPath</code></strong> is relative to the current working volume and directory </li>\n</ul>\n\n<p>It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain <code>.\\</code>. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.</p></li>\n</ol>\n\n<p>So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The <code>~s</code> modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The <code>~s</code> modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the <code>~s</code> modifier will not append the <code>\\</code> to the path, nor will it convert the path into a valid 8.3 format.</p>\n\n<p>The problem with <code>~s</code> is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with <code>&lt;letter&gt;:&lt;separator&gt;</code> but not <code>&lt;letter&gt;:&lt;separator&gt;&lt;separator&gt;</code>, where &lt;separator> is either <code>\\</code> or <code>/</code>. UNC paths are always fully qualified and must start with <code>\\\\</code>. When comparing fully qualified paths we use the <code>~s</code> modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.</p>\n\n<p>There are some additional issues that complicate this problem:</p>\n\n<p>9) <strong>Normal expansion is not reliable when dealing with a PATH that contains special characters.</strong><br>\n Special characters do not need to be quoted within PATH, but they could be. So a PATH like\n<code>C:\\THIS &amp; THAT;\"C:\\&amp; THE OTHER THING\"</code> is perfectly valid, but it cannot be expanded safely using simple expansion because both <code>\"%PATH%\"</code> and <code>%PATH%</code> will fail.</p>\n\n<p>10) <strong>The path delimiter is also valid within a path name</strong><br>\nA <code>;</code> is used to delimit paths within PATH, but <code>;</code> can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.</p>\n\n<p>jeb solved both issues 9 and 10 at <a href=\"https://stackoverflow.com/questions/5471556/pretty-print-windows-path-variable-how-to-split-on-in-cmd-shell/5472168#5472168\">&#39;Pretty print&#39; windows %PATH% variable - how to split on &#39;;&#39; in CMD shell</a> </p>\n\n<p>So we can combine the <code>~s</code> modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.</p>\n\n<pre><code>@echo off\n:inPath pathVar\n::\n:: Tests if the path stored within variable pathVar exists within PATH.\n::\n:: The result is returned as the ERRORLEVEL:\n:: 0 if the pathVar path is found in PATH.\n:: 1 if the pathVar path is not found in PATH.\n:: 2 if pathVar is missing or undefined or if PATH is undefined.\n::\n:: If the pathVar path is fully qualified, then it is logically compared\n:: to each fully qualified path within PATH. The path strings don't have\n:: to match exactly, they just need to be logically equivalent.\n::\n:: If the pathVar path is relative, then it is strictly compared to each\n:: relative path within PATH. Case differences and double quotes are\n:: ignored, but otherwise the path strings must match exactly.\n::\n::------------------------------------------------------------------------\n::\n:: Error checking\nif \"%~1\"==\"\" exit /b 2\nif not defined %~1 exit /b 2\nif not defined path exit /b 2\n::\n:: Prepare to safely parse PATH into individual paths\nsetlocal DisableDelayedExpansion\nset \"var=%path:\"=\"\"%\"\nset \"var=%var:^=^^%\"\nset \"var=%var:&amp;=^&amp;%\"\nset \"var=%var:|=^|%\"\nset \"var=%var:&lt;=^&lt;%\"\nset \"var=%var:&gt;=^&gt;%\"\nset \"var=%var:;=^;^;%\"\nset var=%var:\"\"=\"%\nset \"var=%var:\"=\"\"Q%\"\nset \"var=%var:;;=\"S\"S%\"\nset \"var=%var:^;^;=;%\"\nset \"var=%var:\"\"=\"%\"\nsetlocal EnableDelayedExpansion\nset \"var=!var:\"Q=!\"\nset \"var=!var:\"S\"S=\";\"!\"\n::\n:: Remove quotes from pathVar and abort if it becomes empty\nset \"new=!%~1:\"=!\"\nif not defined new exit /b 2\n::\n:: Determine if pathVar is fully qualified\necho(\"!new!\"|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" &gt;nul ^\n &amp;&amp; set \"abs=1\" || set \"abs=0\"\n::\n:: For each path in PATH, check if path is fully qualified and then do\n:: proper comparison with pathVar.\n:: Exit with ERRORLEVEL 0 if a match is found.\n:: Delayed expansion must be disabled when expanding FOR variables\n:: just in case the value contains !\nfor %%A in (\"!new!\\\") do for %%B in (\"!var!\") do (\n if \"!!\"==\"\" endlocal\n for %%C in (\"%%~B\\\") do (\n echo(%%B|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" &gt;nul ^\n &amp;&amp; (if %abs%==1 if /i \"%%~sA\"==\"%%~sC\" exit /b 0) ^\n || (if %abs%==0 if /i \"%%~A\"==\"%%~C\" exit /b 0)\n )\n)\n:: No match was found so exit with ERRORLEVEL 1\nexit /b 1\n</code></pre>\n\n<p>The function can be used like so (assuming the batch file is named inPath.bat):</p>\n\n<pre><code>set test=c:\\mypath\ncall inPath test &amp;&amp; (echo found) || (echo not found)\n</code></pre>\n\n<p><br/>\n<hr/>\nTypically the reason for checking if a path exists within PATH is because you want to append the path if it isn't there. This is normally done simply by using something like <code>path %path%;%newPath%</code>. But Issue 9 demonstrates how this is not reliable.</p>\n\n<p>Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped <code>!</code> will corrupt the value if delayed expansion is enabled.</p>\n\n<p>These problems are resolved using an amazing safe return technique that jeb invented here: <a href=\"http://www.dostips.com/forum/viewtopic.php?p=6930#p6930\" rel=\"noreferrer\">http://www.dostips.com/forum/viewtopic.php?p=6930#p6930</a></p>\n\n<pre><code>@echo off\n:addPath pathVar /B\n::\n:: Safely appends the path contained within variable pathVar to the end\n:: of PATH if and only if the path does not already exist within PATH.\n::\n:: If the case insensitive /B option is specified, then the path is\n:: inserted into the front (Beginning) of PATH instead.\n::\n:: If the pathVar path is fully qualified, then it is logically compared\n:: to each fully qualified path within PATH. The path strings are\n:: considered a match if they are logically equivalent.\n::\n:: If the pathVar path is relative, then it is strictly compared to each\n:: relative path within PATH. Case differences and double quotes are\n:: ignored, but otherwise the path strings must match exactly.\n::\n:: Before appending the pathVar path, all double quotes are stripped, and\n:: then the path is enclosed in double quotes if and only if the path\n:: contains at least one semicolon.\n::\n:: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined\n:: or if PATH is undefined.\n::\n::------------------------------------------------------------------------\n::\n:: Error checking\nif \"%~1\"==\"\" exit /b 2\nif not defined %~1 exit /b 2\nif not defined path exit /b 2\n::\n:: Determine if function was called while delayed expansion was enabled\nsetlocal\nset \"NotDelayed=!\"\n::\n:: Prepare to safely parse PATH into individual paths\nsetlocal DisableDelayedExpansion\nset \"var=%path:\"=\"\"%\"\nset \"var=%var:^=^^%\"\nset \"var=%var:&amp;=^&amp;%\"\nset \"var=%var:|=^|%\"\nset \"var=%var:&lt;=^&lt;%\"\nset \"var=%var:&gt;=^&gt;%\"\nset \"var=%var:;=^;^;%\"\nset var=%var:\"\"=\"%\nset \"var=%var:\"=\"\"Q%\"\nset \"var=%var:;;=\"S\"S%\"\nset \"var=%var:^;^;=;%\"\nset \"var=%var:\"\"=\"%\"\nsetlocal EnableDelayedExpansion\nset \"var=!var:\"Q=!\"\nset \"var=!var:\"S\"S=\";\"!\"\n::\n:: Remove quotes from pathVar and abort if it becomes empty\nset \"new=!%~1:\"^=!\"\nif not defined new exit /b 2\n::\n:: Determine if pathVar is fully qualified\necho(\"!new!\"|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" &gt;nul ^\n &amp;&amp; set \"abs=1\" || set \"abs=0\"\n::\n:: For each path in PATH, check if path is fully qualified and then\n:: do proper comparison with pathVar. Exit if a match is found.\n:: Delayed expansion must be disabled when expanding FOR variables\n:: just in case the value contains !\nfor %%A in (\"!new!\\\") do for %%B in (\"!var!\") do (\n if \"!!\"==\"\" setlocal disableDelayedExpansion\n for %%C in (\"%%~B\\\") do (\n echo(%%B|findstr /i /r /c:^\"^^\\\"[a-zA-Z]:[\\\\/][^\\\\/]\" ^\n /c:^\"^^\\\"[\\\\][\\\\]\" &gt;nul ^\n &amp;&amp; (if %abs%==1 if /i \"%%~sA\"==\"%%~sC\" exit /b 0) ^\n || (if %abs%==0 if /i %%A==%%C exit /b 0)\n )\n)\n::\n:: Build the modified PATH, enclosing the added path in quotes\n:: only if it contains ;\nsetlocal enableDelayedExpansion\nif \"!new:;=!\" neq \"!new!\" set new=\"!new!\"\nif /i \"%~2\"==\"/B\" (set \"rtn=!new!;!path!\") else set \"rtn=!path!;!new!\"\n::\n:: rtn now contains the modified PATH. We need to safely pass the\n:: value accross the ENDLOCAL barrier\n::\n:: Make rtn safe for assignment using normal expansion by replacing\n:: % and \" with not yet defined FOR variables\nset \"rtn=!rtn:%%=%%A!\"\nset \"rtn=!rtn:\"=%%B!\"\n::\n:: Escape ^ and ! if function was called while delayed expansion was enabled.\n:: The trailing ! in the second assignment is critical and must not be removed.\nif not defined NotDelayed set \"rtn=!rtn:^=^^^^!\"\nif not defined NotDelayed set \"rtn=%rtn:!=^^^!%\" !\n::\n:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to\n:: restore the % and \" characters. Again the trailing ! is critical.\nfor /f \"usebackq tokens=1,2\" %%A in ('%%^ ^\"') do (\n endlocal &amp; endlocal &amp; endlocal &amp; endlocal &amp; endlocal\n set \"path=%rtn%\" !\n)\nexit /b 0\n</code></pre>\n" }, { "answer_id": 11018458, "author": "user1454091", "author_id": 1454091, "author_profile": "https://Stackoverflow.com/users/1454091", "pm_score": 1, "selected": false, "text": "<p>In general, this is to add an EXE or DLL file on the path. As long as this file won’t appear anywhere else:</p>\n<pre><code>@echo off\nwhere /q &lt;put filename here&gt;\nif %errorlevel% == 1 (\n setx PATH &quot;%PATH%;&lt;additional path stuff&gt;&quot;\n) else (\n echo &quot;already set path&quot;\n)\n</code></pre>\n" }, { "answer_id": 12884517, "author": "carlsomo", "author_id": 1745223, "author_profile": "https://Stackoverflow.com/users/1745223", "pm_score": 0, "selected": false, "text": "<p>This routine will search for a path\\ or file.ext in the path variable.\nIt returns 0 if found. Path\\ or file may contain spaces if quoted.\nIf a variable is passed as the last argument, it will be set to <code>d:\\path\\file</code>.</p>\n<pre><code>@echo off&amp;goto :PathCheck\n:PathCheck.CMD\necho.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable\necho.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]\necho.Checkpath must have a trailing \\ but checkfile must not\necho.If Checkpath contains spaces use quotes ie. &quot;C:\\Check path\\&quot;\necho.Checkfile must not include a path, just the filename.ext\necho.If Checkfile contains spaces use quotes ie. &quot;Check File.ext&quot;\necho.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all\necho.If PathVar is not in command line it will be echoed with surrounding quotes\necho.If PathVar is passed it will be set to d:\\path\\checkfile with no trailing \\\necho.Then %%PathVar%% will be set to the fully qualified path to Checkfile\necho.Note: %%PathVar%% variable set will not be surrounded with quotes\necho.To view the path listing line by line use: PathCheck.CMD /L\nexit/b 1\n\n:PathCheck\nif &quot;%~1&quot;==&quot;&quot; goto :PathCheck.CMD\nsetlocal EnableDelayedExpansion\nset &quot;PathVar=%~2&quot;\nset &quot;pth=&quot;\nset &quot;pcheck=%~1&quot;\nif &quot;%pcheck:~-1%&quot; equ &quot;\\&quot; (\n if not exist %pcheck% endlocal&amp;exit/b -1\n set/a pth=1\n)\nfor %%G in (&quot;%path:;=&quot; &quot;%&quot;) do (\n set &quot;Pathfd=%%~G\\&quot;\n set &quot;Pathfd=!Pathfd:\\\\=\\!&quot;\n if /i &quot;%pcheck%&quot; equ &quot;/L&quot; echo.!Pathfd!\n if defined pth (\n if /i &quot;%pcheck%&quot; equ &quot;!Pathfd!&quot; endlocal&amp;exit/b 0\n ) else (\n if exist &quot;!Pathfd!%pcheck%&quot; goto :CheckfileFound\n )\n)\nendlocal&amp;exit/b 1\n\n:CheckfileFound\nendlocal&amp;(\n if not &quot;%PathVar%&quot;==&quot;&quot; (\n call set &quot;%~2=%Pathfd%%pcheck%&quot;\n ) else (echo.&quot;%Pathfd%%pcheck%&quot;)\n exit/b 0\n)\n</code></pre>\n" }, { "answer_id": 19643064, "author": "Aacini", "author_id": 778560, "author_profile": "https://Stackoverflow.com/users/778560", "pm_score": 4, "selected": false, "text": "<p>After reading the answers here I think I can provide a new point of view: if the purpose of this question is to know <em>if the path to a certain executable file</em> exists in <code>%PATH%</code> and if not, insert it (and <strong>this is the only reason</strong> to do that, I think), then it may solved in a slightly different way: \"How to check if the directory of a certain executable program exist in %PATH%\"? This question may be easily solved this way:</p>\n\n<pre><code>for %%p in (programname.exe) do set \"progpath=%%~$PATH:p\"\nif not defined progpath (\n rem The path to programname.exe don't exist in PATH variable, insert it:\n set \"PATH=%PATH%;C:\\path\\to\\progranname\"\n)\n</code></pre>\n\n<p>If you don't know the extension of the executable file, just review all of them:</p>\n\n<pre><code>set \"progpath=\"\nfor %%e in (%PATHEXT%) do (\n if not defined progpath (\n for %%p in (programname.%%e) do set \"progpath=%%~$PATH:p\"\n )\n)\n</code></pre>\n" }, { "answer_id": 23353210, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "<p>This is a variation of <a href=\"https://stackoverflow.com/questions/141344/how-to-check-if-a-directory-exists-in-path/6802486#6802486\">Kevin Edwards's answer</a> using string replacement.</p>\n<p>The basic pattern is:</p>\n<pre><code>IF &quot;%PATH:new_path=%&quot; == &quot;%PATH%&quot; PATH=%PATH%;new_path\n</code></pre>\n<p>For example:</p>\n<pre><code>IF &quot;%PATH:C:\\Scripts=%&quot; == &quot;%PATH%&quot; PATH=%PATH%;C:\\Scripts\n</code></pre>\n<p>In a nutshell, we make a conditional test where we attempt to remove/replace <code>new_path</code> from our <code>PATH</code> environment variable. If <code>new_path</code> doesn't exist, the condition succeeds and the <code>new_path</code> will be appended to <code>PATH</code> for the first time. If <code>new_path</code> already exists then the condition fails and we will not add <code>new_path</code> a second time.</p>\n" }, { "answer_id": 30711326, "author": "Heyvoon", "author_id": 1824347, "author_profile": "https://Stackoverflow.com/users/1824347", "pm_score": 1, "selected": false, "text": "<p>You can accomplish this using PowerShell;</p>\n<pre><code>Test-Path $ENV:SystemRoot\\YourDirectory\nTest-Path C:\\Windows\\YourDirectory\n</code></pre>\n<p>This returns <code>TRUE</code> or <code>FALSE</code></p>\n<p>Short, simple and easy!</p>\n" }, { "answer_id": 43815216, "author": "Albert", "author_id": 2211788, "author_profile": "https://Stackoverflow.com/users/2211788", "pm_score": 2, "selected": false, "text": "<p>Just to elaborate on <a href=\"https://stackoverflow.com/a/30711326/2211788\">Heyvoon's response</a> (2015-06-08) using PowerShell, this simple PowerShell script should give you detail on %path%:</p>\n<pre><code>$env:Path -split &quot;;&quot; | % {&quot;$(test-path $_); $_&quot;}\n</code></pre>\n<p>It is generating this kind of output which you can independently verify:</p>\n<pre><code>True;C:\\WINDOWS\nTrue;C:\\WINDOWS\\system32\nTrue;C:\\WINDOWS\\System32\\Wbem\nFalse;C:windows\\System32\\windowsPowerShell\\v1.0\\\nFalse;C:\\Program Files (x86)\\Java\\jre7\\bin\n</code></pre>\n<p>To reassemble for updating Path:</p>\n<pre><code>$x = $null; foreach ($t in ($env:Path -split &quot;;&quot;) ) {if (test-path $t) {$x += $t + &quot;;&quot;}}; $x\n</code></pre>\n" }, { "answer_id": 56883320, "author": "Günter Zöchbauer", "author_id": 217408, "author_profile": "https://Stackoverflow.com/users/217408", "pm_score": 0, "selected": false, "text": "<p><code>-contains</code> worked for me</p>\n<pre class=\"lang-none prettyprint-override\"><code>$pathToCheck = &quot;c:\\some path\\to\\a\\file.txt&quot;\n\n$env:Path - split ';' -contains $pathToCheck\n</code></pre>\n<p>To add the path when it does not exist yet I use</p>\n<pre class=\"lang-none prettyprint-override\"><code>$pathToCheck = &quot;c:\\some path\\to\\a\\file.txt&quot;\n\nif(!($env:Path -split ';' -contains $vboxPath)) {\n $documentsDir = [Environment]::GetFolderPath(&quot;MyDocuments&quot;)\n $profileFilePath = Join-Path $documentsDir &quot;WindowsPowerShell/profile.ps1&quot;\n Out-File -FilePath $profileFilePath -Append -Force -Encoding ascii -InputObject &quot;`$env:Path += `&quot;;$pathToCheck`&quot;&quot;\n Invoke-Expression -command $profileFilePath\n}\n</code></pre>\n" }, { "answer_id": 70617492, "author": "Jerry T", "author_id": 2292993, "author_profile": "https://Stackoverflow.com/users/2292993", "pm_score": 0, "selected": false, "text": "<pre><code>rem https://stackoverflow.com/a/59571160/2292993\nrem Don't get mess with %PATH%, it is a concatenation of USER+SYSTEM, and will cause a lot of duplication in the result. \nfor /f &quot;usebackq tokens=2,*&quot; %%A in (`reg query HKCU\\Environment /v PATH`) do set userPATH=%%B\nrem userPATH should be %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps\n\nrem https://stackoverflow.com/questions/141344\nfor /f &quot;delims=&quot; %%A in ('echo &quot;;%userPATH%;&quot; ^| find /C /I &quot;;%WINAPPS%;&quot;') do set pathExists=%%A\nIf %pathExists%==0 (\n echo Inserting user path...\n setx PATH &quot;%WINAPPS%; %userPATH%&quot;\n)\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one. Is there a better way of doing this? Something like [FIND](https://ss64.com/nt/find.html) or [FINDSTR](https://ss64.com/nt/findstr.html) operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there. ``` FOR /F "delims=;" %%P IN ("%PATH%") DO ( @ECHO %%~P ) ```
First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with. For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable. From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because: 1. **The trailing `\` is optional in a path** Most paths work equally well both with and without the trailing `\`. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing `\`. This is probably the most common practical issue when searching a PATH for a match. * There is one exception: The relative path `C:` (meaning the current working directory of drive C) is very different than `C:\` (meaning the root directory of drive C) 2. **Some paths have alternate short names** Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings. 3. **Windows accepts both `/` and `\` as folder separators within a path.** This is not seen very often, but a path can be specified using `/` instead of `\` and it will function just fine within PATH (as well as in many other Windows contexts) 4. **Windows treats consecutive folder separators as one logical separator.** C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append `\` to a path without bothering to check if the trailing `\` already exists. But this obviously can cause problems if trying to perform an exact string match. * Exceptions: Not only is `C:`, different than `C:\`, but `C:\` (a valid path), is different than `C:\\` (an invalid path). 5. **Windows trims trailing dots and spaces from file and directory names.** `"C:\test. "` is equivalent to `"C:\test"`. 6. **The current `.\` and parent `..\` folder specifiers may appear within a path** Unlikely to be seen in real life, but something like `C:\.\parent\child\..\.\child\` is equivalent to `C:\parent\child` 7. **A path can optionally be enclosed within double quotes.** A path is often enclosed in quotes to protect against special characters like `<space>` `,` `;` `^` `&` `=`. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a `;`, but the quotes may be present never-the-less. 8. **A path may be fully qualified or relative.** A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths: * **`D:`** is relative to the current working directory of volume D: * **`\myPath`** is relative to the current working volume (could be C:, D: etc.) * **`myPath`** is relative to the current working volume and directoryIt is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain `.\`. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH. So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The `~s` modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The `~s` modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the `~s` modifier will not append the `\` to the path, nor will it convert the path into a valid 8.3 format. The problem with `~s` is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with `<letter>:<separator>` but not `<letter>:<separator><separator>`, where <separator> is either `\` or `/`. UNC paths are always fully qualified and must start with `\\`. When comparing fully qualified paths we use the `~s` modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH. There are some additional issues that complicate this problem: 9) **Normal expansion is not reliable when dealing with a PATH that contains special characters.** Special characters do not need to be quoted within PATH, but they could be. So a PATH like `C:\THIS & THAT;"C:\& THE OTHER THING"` is perfectly valid, but it cannot be expanded safely using simple expansion because both `"%PATH%"` and `%PATH%` will fail. 10) **The path delimiter is also valid within a path name** A `;` is used to delimit paths within PATH, but `;` can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue. jeb solved both issues 9 and 10 at ['Pretty print' windows %PATH% variable - how to split on ';' in CMD shell](https://stackoverflow.com/questions/5471556/pretty-print-windows-path-variable-how-to-split-on-in-cmd-shell/5472168#5472168) So we can combine the `~s` modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments. ``` @echo off :inPath pathVar :: :: Tests if the path stored within variable pathVar exists within PATH. :: :: The result is returned as the ERRORLEVEL: :: 0 if the pathVar path is found in PATH. :: 1 if the pathVar path is not found in PATH. :: 2 if pathVar is missing or undefined or if PATH is undefined. :: :: If the pathVar path is fully qualified, then it is logically compared :: to each fully qualified path within PATH. The path strings don't have :: to match exactly, they just need to be logically equivalent. :: :: If the pathVar path is relative, then it is strictly compared to each :: relative path within PATH. Case differences and double quotes are :: ignored, but otherwise the path strings must match exactly. :: ::------------------------------------------------------------------------ :: :: Error checking if "%~1"=="" exit /b 2 if not defined %~1 exit /b 2 if not defined path exit /b 2 :: :: Prepare to safely parse PATH into individual paths setlocal DisableDelayedExpansion set "var=%path:"=""%" set "var=%var:^=^^%" set "var=%var:&=^&%" set "var=%var:|=^|%" set "var=%var:<=^<%" set "var=%var:>=^>%" set "var=%var:;=^;^;%" set var=%var:""="% set "var=%var:"=""Q%" set "var=%var:;;="S"S%" set "var=%var:^;^;=;%" set "var=%var:""="%" setlocal EnableDelayedExpansion set "var=!var:"Q=!" set "var=!var:"S"S=";"!" :: :: Remove quotes from pathVar and abort if it becomes empty set "new=!%~1:"=!" if not defined new exit /b 2 :: :: Determine if pathVar is fully qualified echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && set "abs=1" || set "abs=0" :: :: For each path in PATH, check if path is fully qualified and then do :: proper comparison with pathVar. :: Exit with ERRORLEVEL 0 if a match is found. :: Delayed expansion must be disabled when expanding FOR variables :: just in case the value contains ! for %%A in ("!new!\") do for %%B in ("!var!") do ( if "!!"=="" endlocal for %%C in ("%%~B\") do ( echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^ || (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0) ) ) :: No match was found so exit with ERRORLEVEL 1 exit /b 1 ``` The function can be used like so (assuming the batch file is named inPath.bat): ``` set test=c:\mypath call inPath test && (echo found) || (echo not found) ``` Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped `!` will corrupt the value if delayed expansion is enabled. These problems are resolved using an amazing safe return technique that jeb invented here: <http://www.dostips.com/forum/viewtopic.php?p=6930#p6930> ``` @echo off :addPath pathVar /B :: :: Safely appends the path contained within variable pathVar to the end :: of PATH if and only if the path does not already exist within PATH. :: :: If the case insensitive /B option is specified, then the path is :: inserted into the front (Beginning) of PATH instead. :: :: If the pathVar path is fully qualified, then it is logically compared :: to each fully qualified path within PATH. The path strings are :: considered a match if they are logically equivalent. :: :: If the pathVar path is relative, then it is strictly compared to each :: relative path within PATH. Case differences and double quotes are :: ignored, but otherwise the path strings must match exactly. :: :: Before appending the pathVar path, all double quotes are stripped, and :: then the path is enclosed in double quotes if and only if the path :: contains at least one semicolon. :: :: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined :: or if PATH is undefined. :: ::------------------------------------------------------------------------ :: :: Error checking if "%~1"=="" exit /b 2 if not defined %~1 exit /b 2 if not defined path exit /b 2 :: :: Determine if function was called while delayed expansion was enabled setlocal set "NotDelayed=!" :: :: Prepare to safely parse PATH into individual paths setlocal DisableDelayedExpansion set "var=%path:"=""%" set "var=%var:^=^^%" set "var=%var:&=^&%" set "var=%var:|=^|%" set "var=%var:<=^<%" set "var=%var:>=^>%" set "var=%var:;=^;^;%" set var=%var:""="% set "var=%var:"=""Q%" set "var=%var:;;="S"S%" set "var=%var:^;^;=;%" set "var=%var:""="%" setlocal EnableDelayedExpansion set "var=!var:"Q=!" set "var=!var:"S"S=";"!" :: :: Remove quotes from pathVar and abort if it becomes empty set "new=!%~1:"^=!" if not defined new exit /b 2 :: :: Determine if pathVar is fully qualified echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && set "abs=1" || set "abs=0" :: :: For each path in PATH, check if path is fully qualified and then :: do proper comparison with pathVar. Exit if a match is found. :: Delayed expansion must be disabled when expanding FOR variables :: just in case the value contains ! for %%A in ("!new!\") do for %%B in ("!var!") do ( if "!!"=="" setlocal disableDelayedExpansion for %%C in ("%%~B\") do ( echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^ /c:^"^^\"[\\][\\]" >nul ^ && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^ || (if %abs%==0 if /i %%A==%%C exit /b 0) ) ) :: :: Build the modified PATH, enclosing the added path in quotes :: only if it contains ; setlocal enableDelayedExpansion if "!new:;=!" neq "!new!" set new="!new!" if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!" :: :: rtn now contains the modified PATH. We need to safely pass the :: value accross the ENDLOCAL barrier :: :: Make rtn safe for assignment using normal expansion by replacing :: % and " with not yet defined FOR variables set "rtn=!rtn:%%=%%A!" set "rtn=!rtn:"=%%B!" :: :: Escape ^ and ! if function was called while delayed expansion was enabled. :: The trailing ! in the second assignment is critical and must not be removed. if not defined NotDelayed set "rtn=!rtn:^=^^^^!" if not defined NotDelayed set "rtn=%rtn:!=^^^!%" ! :: :: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to :: restore the % and " characters. Again the trailing ! is critical. for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do ( endlocal & endlocal & endlocal & endlocal & endlocal set "path=%rtn%" ! ) exit /b 0 ```
141,345
<p>I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.</p> <pre><code>&lt;xsl:template match="one"&gt; &lt;xsl:variable name="varOne" select="@count" /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="two"&gt; &lt;xsl:if test="$varOne = 'Y'"&gt; &lt;xsl:value-of select="varTwo"/&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre> <p>This has been simplified for here.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 141364, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "<p>I'm fairly certain that variables are scoped and therefore you can't declare a variable in one and then use it in the other. You're going to have to move your variable declaration out of the template so that it's in a higher scope than both of them.</p>\n" }, { "answer_id": 141403, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 3, "selected": true, "text": "<p>Remembering that xsl variables are immutable...</p>\n\n<pre><code>&lt;!-- You may want to use absolute path --&gt;\n&lt;xsl:variable name=\"varOne\" select=\"one/@count\" /&gt;\n\n&lt;xsl:template match=\"one\"&gt;\n&lt;!-- // do something --&gt; \n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"two\"&gt;\n &lt;xsl:if test=\"$varOne = 'Y'\"&gt;\n &lt;xsl:value-of select=\"varTwo\"/&gt;\n &lt;/xsl:if&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 141463, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<p>You may also solve some scoping issues by passing parameters...</p>\n\n<pre><code>&lt;xsl:apply-templates select=\"two\"&gt;\n &lt;xsl:with-param name=\"varOne\"&gt;\n &lt;xsl:value-of select=\"one/@count\"/&gt;\n &lt;/xsl:with-param&gt;\n&lt;/xsl:apply-templates&gt;\n\n&lt;xsl:template match=\"two\"&gt;\n &lt;xsl:param name=\"varOne\"/&gt;\n &lt;xsl:if test=\"$varOne = 'Y'\"&gt;\n &lt;xsl:value-of select=\"varTwo\"/&gt;\n &lt;/xsl:if&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 142758, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>The scope of a variable in XSLT is its enclosing element. To make a variable visible to multiple elements, its declaration has to be at the same level or higher than those elements.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16354/" ]
I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong. ``` <xsl:template match="one"> <xsl:variable name="varOne" select="@count" /> </xsl:template> <xsl:template match="two"> <xsl:if test="$varOne = 'Y'"> <xsl:value-of select="varTwo"/> </xsl:if> </xsl:template> ``` This has been simplified for here. Any help is appreciated.
Remembering that xsl variables are immutable... ``` <!-- You may want to use absolute path --> <xsl:variable name="varOne" select="one/@count" /> <xsl:template match="one"> <!-- // do something --> </xsl:template> <xsl:template match="two"> <xsl:if test="$varOne = 'Y'"> <xsl:value-of select="varTwo"/> </xsl:if> </xsl:template> ```
141,348
<p>I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript <code>Date()</code> object so I can easily perform comparisons and other things on it.</p> <p>I tried the <code>parse()</code> method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same <code>Date()</code> object:</p> <ul> <li>1:00 pm</li> <li>1:00 p.m.</li> <li>1:00 p</li> <li>1:00pm</li> <li>1:00p.m.</li> <li>1:00p</li> <li>1 pm</li> <li>1 p.m.</li> <li>1 p</li> <li>1pm</li> <li>1p.m.</li> <li>1p</li> <li>13:00</li> <li>13</li> </ul> <p>I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my <code>Date()</code> object. What is the best way to do this?</p>
[ { "answer_id": 141383, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": false, "text": "<p>Don't bother doing it yourself, just use <a href=\"http://www.datejs.com/\" rel=\"noreferrer\">datejs</a>.</p>\n" }, { "answer_id": 141486, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>Why not use validation to narrow down what a user can put in and simplify the list to only include formats that can be parsed (or parsed after some tweaking).</p>\n\n<p>I don't think it's asking too much to require a user to put a time in a supported format.</p>\n\n<p>dd:dd A(m)/P(m)</p>\n\n<p>dd A(m)/P(m)</p>\n\n<p>dd</p>\n" }, { "answer_id": 141504, "author": "John Resig", "author_id": 6524, "author_profile": "https://Stackoverflow.com/users/6524", "pm_score": 7, "selected": true, "text": "<p>A quick solution which works on the input that you've specified:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime( t ) {\r\n var d = new Date();\r\n var time = t.match( /(\\d+)(?::(\\d\\d))?\\s*(p?)/ );\r\n d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );\r\n d.setMinutes( parseInt( time[2]) || 0 );\r\n return d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example). </p>\n\n<blockquote>\n <p>Warning: The code doe not work with 12:00 AM, etc.</p>\n</blockquote>\n" }, { "answer_id": 253680, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 2, "selected": false, "text": "<p>I came across a couple of kinks in implementing John Resig's solution. Here is the modified function that I have been using based on his answer:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(timeString)\r\n{\r\n if (timeString == '') return null;\r\n var d = new Date();\r\n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/);\r\n d.setHours( parseInt(time[1]) + ( ( parseInt(time[1]) &lt; 12 &amp;&amp; time[4] ) ? 12 : 0) );\r\n d.setMinutes( parseInt(time[3]) || 0 );\r\n d.setSeconds(0, 0);\r\n return d;\r\n} // parseTime()\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 338439, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 4, "selected": false, "text": "<p>Here's an improvement on <a href=\"http://#253680\" rel=\"nofollow noreferrer\">Joe's version</a>. Feel free to edit it further.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(timeString)\r\n{\r\n if (timeString == '') return null;\r\n var d = new Date();\r\n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/i);\r\n d.setHours( parseInt(time[1],10) + ( ( parseInt(time[1],10) &lt; 12 &amp;&amp; time[4] ) ? 12 : 0) );\r\n d.setMinutes( parseInt(time[3],10) || 0 );\r\n d.setSeconds(0, 0);\r\n return d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Changes:</p>\n\n<ul>\n<li>Added radix parameter to the parseInt() calls (so jslint won't complain). </li>\n<li>Made the regex case-insenstive so \"2:23 PM\" works like \"2:23 pm\"</li>\n</ul>\n" }, { "answer_id": 432785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>/(\\d+)(?::(\\d\\d))(?::(\\d\\d))?\\s*([pP]?)/ \n\n// added test for p or P\n// added seconds\n\nd.setHours( parseInt(time[1]) + (time[4] ? 12 : 0) ); // care with new indexes\nd.setMinutes( parseInt(time[2]) || 0 );\nd.setSeconds( parseInt(time[3]) || 0 );\n</code></pre>\n\n<p>thanks</p>\n" }, { "answer_id": 2188651, "author": "Nathan Villaescusa", "author_id": 264837, "author_profile": "https://Stackoverflow.com/users/264837", "pm_score": 6, "selected": false, "text": "<p>All of the examples provided fail to work for times from 12:00 am to 12:59 am. They also throw an error if the regex does not match a time. The following handles this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(timeString) { \r\n if (timeString == '') return null;\r\n \r\n var time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*(p?)/i); \r\n if (time == null) return null;\r\n \r\n var hours = parseInt(time[1],10); \r\n if (hours == 12 &amp;&amp; !time[4]) {\r\n hours = 0;\r\n }\r\n else {\r\n hours += (hours &lt; 12 &amp;&amp; time[4])? 12 : 0;\r\n } \r\n var d = new Date(); \r\n d.setHours(hours);\r\n d.setMinutes(parseInt(time[3],10) || 0);\r\n d.setSeconds(0, 0); \r\n return d;\r\n}\r\n\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This will work for strings which contain a time anywhere inside them. So \"abcde12:00pmdef\" would be parsed and return 12 pm. If the desired outcome is that it only returns a time when the string only contains a time in them the following regular expression can be used provided you replace \"time[4]\" with \"time[6]\".</p>\n\n<pre><code>/^(\\d+)(:(\\d\\d))?\\s*((a|(p))m?)?$/i\n</code></pre>\n" }, { "answer_id": 2307344, "author": "Pieter de Zwart", "author_id": 278277, "author_profile": "https://Stackoverflow.com/users/278277", "pm_score": 2, "selected": false, "text": "<p>This is a more rugged approach that takes into account how users intend to use this type of input. For example, if a user entered \"12\", they would expect it to be 12pm (noon), and not 12am. The below function handles all of this. It is also available here: <a href=\"http://blog.de-zwart.net/2010-02/javascript-parse-time/\" rel=\"nofollow noreferrer\">http://blog.de-zwart.net/2010-02/javascript-parse-time/</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\r\n * Parse a string that looks like time and return a date object.\r\n * @return Date object on success, false on error.\r\n */\r\nString.prototype.parseTime = function() {\r\n // trim it and reverse it so that the minutes will always be greedy first:\r\n var value = this.trim().reverse();\r\n\r\n // We need to reverse the string to match the minutes in greedy first, then hours\r\n var timeParts = value.match(/(a|p)?\\s*((\\d{2})?:?)(\\d{1,2})/i);\r\n\r\n // This didnt match something we know\r\n if (!timeParts) {\r\n return false;\r\n }\r\n\r\n // reverse it:\r\n timeParts = timeParts.reverse();\r\n\r\n // Reverse the internal parts:\r\n for( var i = 0; i &lt; timeParts.length; i++ ) {\r\n timeParts[i] = timeParts[i] === undefined ? '' : timeParts[i].reverse();\r\n }\r\n\r\n // Parse out the sections:\r\n var minutes = parseInt(timeParts[1], 10) || 0;\r\n var hours = parseInt(timeParts[0], 10);\r\n var afternoon = timeParts[3].toLowerCase() == 'p' ? true : false;\r\n\r\n // If meridian not set, and hours is 12, then assume afternoon.\r\n afternoon = !timeParts[3] &amp;&amp; hours == 12 ? true : afternoon;\r\n // Anytime the hours are greater than 12, they mean afternoon\r\n afternoon = hours &gt; 12 ? true : afternoon;\r\n // Make hours be between 0 and 12:\r\n hours -= hours &gt; 12 ? 12 : 0;\r\n // Add 12 if its PM but not noon\r\n hours += afternoon &amp;&amp; hours != 12 ? 12 : 0;\r\n // Remove 12 for midnight:\r\n hours -= !afternoon &amp;&amp; hours == 12 ? 12 : 0;\r\n\r\n // Check number sanity:\r\n if( minutes &gt;= 60 || hours &gt;= 24 ) {\r\n return false;\r\n }\r\n\r\n // Return a date object with these values set.\r\n var d = new Date();\r\n d.setHours(hours);\r\n d.setMinutes(minutes);\r\n return d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + tests[i].parseTime() );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This is a string prototype, so you can use it like so:</p>\n\n<pre><code>var str = '12am';\nvar date = str.parseTime();\n</code></pre>\n" }, { "answer_id": 2476181, "author": "Andrew M. Andrews III", "author_id": 210158, "author_profile": "https://Stackoverflow.com/users/210158", "pm_score": 1, "selected": false, "text": "<p>AnyTime.Converter can parse dates/times in many different formats:</p>\n\n<p><a href=\"http://www.ama3.com/anytime/\" rel=\"nofollow noreferrer\">http://www.ama3.com/anytime/</a></p>\n" }, { "answer_id": 3998001, "author": "Brad", "author_id": 188547, "author_profile": "https://Stackoverflow.com/users/188547", "pm_score": 0, "selected": false, "text": "<p>An improvement to Patrick McElhaney's solution (his does not handle 12am correctly)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime( timeString ) {\r\nvar d = new Date();\r\nvar time = timeString.match(/(\\d+)(:(\\d\\d))?\\s*([pP]?)/i);\r\nvar h = parseInt(time[1], 10);\r\nif (time[4])\r\n{\r\n if (h &lt; 12)\r\n h += 12;\r\n}\r\nelse if (h == 12)\r\n h = 0;\r\nd.setHours(h);\r\nd.setMinutes(parseInt(time[3], 10) || 0);\r\nd.setSeconds(0, 0);\r\nreturn d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 3998370, "author": "Stefan Haberl", "author_id": 287138, "author_profile": "https://Stackoverflow.com/users/287138", "pm_score": 2, "selected": false, "text": "<p>Here's a solution more for all of those who are using a 24h clock that supports:</p>\n\n<ul>\n<li>0820 -> 08:20</li>\n<li>32 -> 03:02</li>\n<li>124 -> 12:04</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(text) {\r\n var time = text.match(/(\\d?\\d):?(\\d?\\d?)/);\r\n var h = parseInt(time[1], 10);\r\n var m = parseInt(time[2], 10) || 0;\r\n \r\n if (h &gt; 24) {\r\n // try a different format\r\n time = text.match(/(\\d)(\\d?\\d?)/);\r\n h = parseInt(time[1], 10);\r\n m = parseInt(time[2], 10) || 0;\r\n } \r\n \r\n var d = new Date();\r\n d.setHours(h);\r\n d.setMinutes(m);\r\n return d; \r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 8395948, "author": "Andrew Cetinic", "author_id": 151447, "author_profile": "https://Stackoverflow.com/users/151447", "pm_score": 1, "selected": false, "text": "<p>I have made some modifications to the function above to support a few more formats.</p>\n\n<ul>\n<li>1400 -> 2:00 PM</li>\n<li>1.30 -> 1:30 PM</li>\n<li>1:30a -> 1:30 AM</li>\n<li>100 -> 1:00 AM</li>\n</ul>\n\n<p>Ain't cleaned it up yet but works for everything I can think of.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(timeString) {\r\n if (timeString == '') return null;\r\n\r\n var time = timeString.match(/^(\\d+)([:\\.](\\d\\d))?\\s*((a|(p))m?)?$/i);\r\n\r\n if (time == null) return null;\r\n\r\n var m = parseInt(time[3], 10) || 0;\r\n var hours = parseInt(time[1], 10);\r\n\r\n if (time[4]) time[4] = time[4].toLowerCase();\r\n\r\n // 12 hour time\r\n if (hours == 12 &amp;&amp; !time[4]) {\r\n hours = 12;\r\n }\r\n else if (hours == 12 &amp;&amp; (time[4] == \"am\" || time[4] == \"a\")) {\r\n hours += 12;\r\n }\r\n else if (hours &lt; 12 &amp;&amp; (time[4] != \"am\" &amp;&amp; time[4] != \"a\")) {\r\n hours += 12;\r\n }\r\n // 24 hour time\r\n else if(hours &gt; 24 &amp;&amp; hours.toString().length &gt;= 3) {\r\n if(hours.toString().length == 3) {\r\n m = parseInt(hours.toString().substring(1,3), 10);\r\n hours = parseInt(hours.toString().charAt(0), 10);\r\n }\r\n else if(hours.toString().length == 4) {\r\n m = parseInt(hours.toString().substring(2,4), 10);\r\n hours = parseInt(hours.toString().substring(0,2), 10);\r\n }\r\n }\r\n\r\n var d = new Date();\r\n d.setHours(hours);\r\n d.setMinutes(m);\r\n d.setSeconds(0, 0);\r\n return d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 14787410, "author": "claviska", "author_id": 567486, "author_profile": "https://Stackoverflow.com/users/567486", "pm_score": 4, "selected": false, "text": "<p>Most of the regex solutions here throw errors when the string can't be parsed, and not many of them account for strings like <code>1330</code> or <code>130pm</code>. Even though these formats weren't specified by the OP, I find them critical for parsing dates input by humans.</p>\n\n<p>All of this got me to thinking that using a regular expression might not be the best approach for this.</p>\n\n<p>My solution is a function that not only parses the time, but also allows you to specify an output format and a step (interval) at which to round minutes to. At about 70 lines, it's still lightweight and parses all of the aforementioned formats as well as ones without colons.</p>\n\n<ul>\n<li>Demo: <a href=\"http://jsfiddle.net/HwwzS/1/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/HwwzS/1/</a></li>\n<li>Code: <a href=\"https://gist.github.com/claviska/4744736\" rel=\"nofollow noreferrer\">https://gist.github.com/claviska/4744736</a></li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTime(time, format, step) {\r\n \r\n var hour, minute, stepMinute,\r\n defaultFormat = 'g:ia',\r\n pm = time.match(/p/i) !== null,\r\n num = time.replace(/[^0-9]/g, '');\r\n \r\n // Parse for hour and minute\r\n switch(num.length) {\r\n case 4:\r\n hour = parseInt(num[0] + num[1], 10);\r\n minute = parseInt(num[2] + num[3], 10);\r\n break;\r\n case 3:\r\n hour = parseInt(num[0], 10);\r\n minute = parseInt(num[1] + num[2], 10);\r\n break;\r\n case 2:\r\n case 1:\r\n hour = parseInt(num[0] + (num[1] || ''), 10);\r\n minute = 0;\r\n break;\r\n default:\r\n return '';\r\n }\r\n \r\n // Make sure hour is in 24 hour format\r\n if( pm === true &amp;&amp; hour &gt; 0 &amp;&amp; hour &lt; 12 ) hour += 12;\r\n \r\n // Force pm for hours between 13:00 and 23:00\r\n if( hour &gt;= 13 &amp;&amp; hour &lt;= 23 ) pm = true;\r\n \r\n // Handle step\r\n if( step ) {\r\n // Step to the nearest hour requires 60, not 0\r\n if( step === 0 ) step = 60;\r\n // Round to nearest step\r\n stepMinute = (Math.round(minute / step) * step) % 60;\r\n // Do we need to round the hour up?\r\n if( stepMinute === 0 &amp;&amp; minute &gt;= 30 ) {\r\n hour++;\r\n // Do we need to switch am/pm?\r\n if( hour === 12 || hour === 24 ) pm = !pm;\r\n }\r\n minute = stepMinute;\r\n }\r\n \r\n // Keep within range\r\n if( hour &lt;= 0 || hour &gt;= 24 ) hour = 0;\r\n if( minute &lt; 0 || minute &gt; 59 ) minute = 0;\r\n\r\n // Format output\r\n return (format || defaultFormat)\r\n // 12 hour without leading 0\r\n .replace(/g/g, hour === 0 ? '12' : 'g')\r\n .replace(/g/g, hour &gt; 12 ? hour - 12 : hour)\r\n // 24 hour without leading 0\r\n .replace(/G/g, hour)\r\n // 12 hour with leading 0\r\n .replace(/h/g, hour.toString().length &gt; 1 ? (hour &gt; 12 ? hour - 12 : hour) : '0' + (hour &gt; 12 ? hour - 12 : hour))\r\n // 24 hour with leading 0\r\n .replace(/H/g, hour.toString().length &gt; 1 ? hour : '0' + hour)\r\n // minutes with leading zero\r\n .replace(/i/g, minute.toString().length &gt; 1 ? minute : '0' + minute)\r\n // simulate seconds\r\n .replace(/s/g, '00')\r\n // lowercase am/pm\r\n .replace(/a/g, pm ? 'pm' : 'am')\r\n // lowercase am/pm\r\n .replace(/A/g, pm ? 'PM' : 'AM');\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 27778902, "author": "RobG", "author_id": 257182, "author_profile": "https://Stackoverflow.com/users/257182", "pm_score": 2, "selected": false, "text": "<p>Lots of answers so one more won't hurt. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\r\n * Parse a time in nearly any format\r\n * @param {string} time - Anything like 1 p, 13, 1:05 p.m., etc.\r\n * @returns {Date} - Date object for the current date and time set to parsed time\r\n*/\r\nfunction parseTime(time) {\r\n var b = time.match(/\\d+/g);\r\n \r\n // return undefined if no matches\r\n if (!b) return;\r\n \r\n var d = new Date();\r\n d.setHours(b[0]&gt;12? b[0] : b[0]%12 + (/p/i.test(time)? 12 : 0), // hours\r\n /\\d/.test(b[1])? b[1] : 0, // minutes\r\n /\\d/.test(b[2])? b[2] : 0); // seconds\r\n return d;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>To be properly robust, it should check that each value is within range of allowed values, e.g if am/pm hours must be 1 to 12 inclusive, otherwise 0 to 24 inclusive, etc.</p>\n" }, { "answer_id": 42590912, "author": "Sgnl", "author_id": 2612640, "author_profile": "https://Stackoverflow.com/users/2612640", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://github.com/zackdever/time\" rel=\"nofollow noreferrer\">time</a> package is 0.9kbs in size. Available with NPM and bower package managers.</p>\n\n<p>Here's an example straight from the <code>README.md</code>:</p>\n\n<pre><code>var t = Time('2p');\nt.hours(); // 2\nt.minutes(); // 0\nt.period(); // 'pm'\nt.toString(); // '2:00 pm'\nt.nextDate(); // Sep 10 2:00 (assuming it is 1 o'clock Sep 10)\nt.format('hh:mm AM') // '02:00 PM'\nt.isValid(); // true\nTime.isValid('99:12'); // false\n</code></pre>\n" }, { "answer_id": 49185071, "author": "Dave Jarvis", "author_id": 59087, "author_profile": "https://Stackoverflow.com/users/59087", "pm_score": 1, "selected": false, "text": "<p>Here's another approach that covers the original answer, any reasonable number of digits, data entry by cats, and logical fallacies. The algorithm follows:</p>\n\n<ol>\n<li>Determine whether meridian is <a href=\"https://en.wikipedia.org/wiki/12-hour_clock\" rel=\"nofollow noreferrer\">post meridiem</a>.</li>\n<li>Convert input digits to an integer value.</li>\n<li>Time between 0 and 24: hour is the o'clock, no minutes (hours 12 is PM).</li>\n<li>Time between 100 and 2359: hours div 100 is the o'clock, minutes mod 100 remainder.</li>\n<li>Time from 2400 on: hours is midnight, with minutes remainder.</li>\n<li>When hours exceeds 12, subtract 12 and force post meridiem true.</li>\n<li>When minutes exceeds 59, force to 59.</li>\n</ol>\n\n<p>Converting the hours, minutes, and post meridiem to a Date object is an exercise for the reader (numerous other answers show how to do this).</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\r\n\r\nString.prototype.toTime = function () {\r\n var time = this;\r\n var post_meridiem = false;\r\n var ante_meridiem = false;\r\n var hours = 0;\r\n var minutes = 0;\r\n\r\n if( time != null ) {\r\n post_meridiem = time.match( /p/i ) !== null;\r\n ante_meridiem = time.match( /a/i ) !== null;\r\n\r\n // Preserve 2400h time by changing leading zeros to 24.\r\n time = time.replace( /^00/, '24' );\r\n\r\n // Strip the string down to digits and convert to a number.\r\n time = parseInt( time.replace( /\\D/g, '' ) );\r\n }\r\n else {\r\n time = 0;\r\n }\r\n\r\n if( time &gt; 0 &amp;&amp; time &lt; 24 ) {\r\n // 1 through 23 become hours, no minutes.\r\n hours = time;\r\n }\r\n else if( time &gt;= 100 &amp;&amp; time &lt;= 2359 ) {\r\n // 100 through 2359 become hours and two-digit minutes.\r\n hours = ~~(time / 100);\r\n minutes = time % 100;\r\n }\r\n else if( time &gt;= 2400 ) {\r\n // After 2400, it's midnight again.\r\n minutes = (time % 100);\r\n post_meridiem = false;\r\n }\r\n\r\n if( hours == 12 &amp;&amp; ante_meridiem === false ) {\r\n post_meridiem = true;\r\n }\r\n\r\n if( hours &gt; 12 ) {\r\n post_meridiem = true;\r\n hours -= 12;\r\n }\r\n\r\n if( minutes &gt; 59 ) {\r\n minutes = 59;\r\n }\r\n\r\n var result =\r\n (\"\"+hours).padStart( 2, \"0\" ) + \":\" + (\"\"+minutes).padStart( 2, \"0\" ) +\r\n (post_meridiem ? \"PM\" : \"AM\");\r\n\r\n return result;\r\n};\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + tests[i].toTime() );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>With jQuery, the newly defined String prototype is used as follows:</p>\n\n<pre><code> &lt;input type=\"text\" class=\"time\" /&gt;\n</code></pre>\n\n<pre><code> $(\".time\").change( function() {\n var $this = $(this);\n $(this).val( time.toTime() );\n });\n</code></pre>\n" }, { "answer_id": 50769298, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 1, "selected": false, "text": "<p>I wasn't happy with the other answers so I made yet another one. This version:</p>\n\n<ul>\n<li>Recognizes seconds and milliseconds</li>\n<li>Returns <code>undefined</code> on invalid input such as \"13:00pm\" or \"11:65\"</li>\n<li>Returns a local time if you provide a <code>localDate</code> parameter, otherwise returns a UTC time on the Unix epoch (Jan 1, 1970).</li>\n<li>Supports military time like <code>1330</code> (to disable, make the first ':' required in the regex)</li>\n<li>Allows an hour by itself, with 24-hour time (i.e. \"7\" means 7am).</li>\n<li>Allows hour 24 as a synonym for hour 0, but hour 25 is not allowed.</li>\n<li>Requires the time to be at the beginning of the string (to disable, remove <code>^\\s*</code> in the regex)</li>\n<li>Has test code that actually detects when the output is incorrect.</li>\n</ul>\n\n<p>Edit: it's now a <a href=\"https://www.npmjs.com/package/simplertime\" rel=\"nofollow noreferrer\">package</a> including a <code>timeToString</code> formatter: <code>npm i simplertime</code></p>\n\n<hr>\n\n<pre><code>/**\n * Parses a string into a Date. Supports several formats: \"12\", \"1234\",\n * \"12:34\", \"12:34pm\", \"12:34 PM\", \"12:34:56 pm\", and \"12:34:56.789\".\n * The time must be at the beginning of the string but can have leading spaces.\n * Anything is allowed after the time as long as the time itself appears to\n * be valid, e.g. \"12:34*Z\" is OK but \"12345\" is not.\n * @param {string} t Time string, e.g. \"1435\" or \"2:35 PM\" or \"14:35:00.0\"\n * @param {Date|undefined} localDate If this parameter is provided, setHours\n * is called on it. Otherwise, setUTCHours is called on 1970/1/1.\n * @returns {Date|undefined} The parsed date, if parsing succeeded.\n */\nfunction parseTime(t, localDate) {\n // ?: means non-capturing group and ?! is zero-width negative lookahead\n var time = t.match(/^\\s*(\\d\\d?)(?::?(\\d\\d))?(?::(\\d\\d))?(?!\\d)(\\.\\d+)?\\s*(pm?|am?)?/i);\n if (time) {\n var hour = parseInt(time[1]), pm = (time[5] || ' ')[0].toUpperCase();\n var min = time[2] ? parseInt(time[2]) : 0;\n var sec = time[3] ? parseInt(time[3]) : 0;\n var ms = (time[4] ? parseFloat(time[4]) * 1000 : 0);\n if (pm !== ' ' &amp;&amp; (hour == 0 || hour &gt; 12) || hour &gt; 24 || min &gt;= 60 || sec &gt;= 60)\n return undefined;\n if (pm === 'A' &amp;&amp; hour === 12) hour = 0;\n if (pm === 'P' &amp;&amp; hour !== 12) hour += 12;\n if (hour === 24) hour = 0;\n var date = new Date(localDate!==undefined ? localDate.valueOf() : 0);\n var set = (localDate!==undefined ? date.setHours : date.setUTCHours);\n set.call(date, hour, min, sec, ms);\n return date;\n }\n return undefined;\n}\n\nvar testSuite = {\n '1300': ['1:00 pm','1:00 P.M.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1:00:00PM', '1300', '13'],\n '1100': ['11:00am', '11:00 AM', '11:00', '11:00:00', '1100'],\n '1359': ['1:59 PM', '13:59', '13:59:00', '1359', '1359:00', '0159pm'],\n '100': ['1:00am', '1:00 am', '0100', '1', '1a', '1 am'],\n '0': ['00:00', '24:00', '12:00am', '12am', '12:00:00 AM', '0000', '1200 AM'],\n '30': ['0:30', '00:30', '24:30', '00:30:00', '12:30:00 am', '0030', '1230am'],\n '1435': [\"2:35 PM\", \"14:35:00.0\", \"1435\"],\n '715.5': [\"7:15:30\", \"7:15:30am\"],\n '109': ['109'], // Three-digit numbers work (I wasn't sure if they would)\n '': ['12:60', '11:59:99', '-12:00', 'foo', '0660', '12345', '25:00'],\n};\n\nvar passed = 0;\nfor (var key in testSuite) {\n let num = parseFloat(key), h = num / 100 | 0;\n let m = num % 100 | 0, s = (num % 1) * 60;\n let expected = Date.UTC(1970, 0, 1, h, m, s); // Month is zero-based\n let strings = testSuite[key];\n for (let i = 0; i &lt; strings.length; i++) {\n var result = parseTime(strings[i]);\n if (result === undefined ? key !== '' : key === '' || expected !== result.valueOf()) {\n console.log(`Test failed at ${key}:\"${strings[i]}\" with result ${result ? result.toUTCString() : 'undefined'}`);\n } else {\n passed++;\n }\n }\n}\nconsole.log(passed + ' tests passed.');\n</code></pre>\n" }, { "answer_id": 51969817, "author": "Souradeep Nanda", "author_id": 1217998, "author_profile": "https://Stackoverflow.com/users/1217998", "pm_score": 0, "selected": false, "text": "<p>If you only want seconds here is a one liner</p>\n\n<pre><code>const toSeconds = s =&gt; s.split(':').map(v =&gt; parseInt(v)).reverse().reduce((acc,e,i) =&gt; acc + e * Math.pow(60,i))\n</code></pre>\n" }, { "answer_id": 53738137, "author": "V. Rubinetti", "author_id": 2180570, "author_profile": "https://Stackoverflow.com/users/2180570", "pm_score": 2, "selected": false, "text": "<p><strong>Compilation table of other answers</strong></p>\n\n<p>First of all, I <em>can't believe</em> that there is not a built-in functionality or even a robust third-party library that can handle this. Actually, it's web development so I can believe it.</p>\n\n<p>Trying to test all edge cases with all these different algorithms was making my head spin, so I took the liberty of compiling all the answers and tests in this thread into a handy table.</p>\n\n<p>The code (and resulting table) is pointlessly large to include inline, so I've made a JSFiddle:</p>\n\n<p><a href=\"http://jsfiddle.net/jLv16ydb/4/show\" rel=\"nofollow noreferrer\">http://jsfiddle.net/jLv16ydb/4/show</a></p>\n\n<pre><code>// heres some filler code of the functions I included in the test,\n// because StackOverfleaux wont let me have a jsfiddle link without code\nFunctions = [\n JohnResig,\n Qwertie,\n PatrickMcElhaney,\n Brad,\n NathanVillaescusa,\n DaveJarvis,\n AndrewCetinic,\n StefanHaberl,\n PieterDeZwart,\n JoeLencioni,\n Claviska,\n RobG,\n DateJS,\n MomentJS\n];\n// I didn't include `date-fns`, because it seems to have even more\n// limited parsing than MomentJS or DateJS\n</code></pre>\n\n<p><em>Please feel free to fork my fiddle and add more algorithms and test cases</em></p>\n\n<p>I didn't add any comparisons between the result and the \"expected\" output, because there are cases where the \"expected\" output could be debated (eg, should <code>12</code> be interpreted as <code>12:00am</code> or <code>12:00pm</code>?). You will have to go through the table and see which algorithm makes the most sense for you.</p>\n\n<p><strong>Note:</strong> The colors do not necessarily indicate quality or \"expectedness\" of output, they only indicate the type of output:</p>\n\n<ul>\n<li><p><code>red</code> = js error thrown</p></li>\n<li><p><code>yellow</code> = \"falsy\" value (<code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>\"\"</code>, <code>\"invalid date\"</code>)</p></li>\n<li><p><code>green</code> = js <code>Date()</code> object</p></li>\n<li><p><code>light green</code> = everything else</p></li>\n</ul>\n\n<p>Where a <code>Date()</code> object is the output, I convert it to 24 hr <code>HH:mm</code> format for ease of comparison.</p>\n" }, { "answer_id": 53752557, "author": "V. Rubinetti", "author_id": 2180570, "author_profile": "https://Stackoverflow.com/users/2180570", "pm_score": 0, "selected": false, "text": "<p>After thoroughly testing and investigating through <a href=\"https://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas/53738137#53738137\">my other compilation answer</a>, I concluded that @Dave Jarvis's solution was the closest to what I felt were reasonable outputs and edge-case-handling. For reference, I looked at what Google Calendar's time inputs reformatted the time to after exiting the text box.</p>\n\n<p>Even still, I saw that it didn't handle some (albeit weird) edge cases that Google Calendar did. So I reworked it from the ground up and this is what I came up with. I also added it to <a href=\"https://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas/53738137#53738137\">my compilation answer</a>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// attempt to parse string as time. return js date object\r\nfunction parseTime(string) {\r\n string = String(string);\r\n\r\n var am = null;\r\n\r\n // check if \"apm\" or \"pm\" explicitly specified, otherwise null\r\n if (string.toLowerCase().includes(\"p\")) am = false;\r\n else if (string.toLowerCase().includes(\"a\")) am = true;\r\n\r\n string = string.replace(/\\D/g, \"\"); // remove non-digit characters\r\n string = string.substring(0, 4); // take only first 4 digits\r\n if (string.length === 3) string = \"0\" + string; // consider eg \"030\" as \"0030\"\r\n string = string.replace(/^00/, \"24\"); // add 24 hours to preserve eg \"0012\" as \"00:12\" instead of \"12:00\", since will be converted to integer\r\n\r\n var time = parseInt(string); // convert to integer\r\n // default time if all else fails\r\n var hours = 12,\r\n minutes = 0;\r\n\r\n // if able to parse as int\r\n if (Number.isInteger(time)) {\r\n // treat eg \"4\" as \"4:00pm\" (or \"4:00am\" if \"am\" explicitly specified)\r\n if (time &gt;= 0 &amp;&amp; time &lt;= 12) {\r\n hours = time;\r\n minutes = 0;\r\n // if \"am\" or \"pm\" not specified, establish from number\r\n if (am === null) {\r\n if (hours &gt;= 1 &amp;&amp; hours &lt;= 12) am = false;\r\n else am = true;\r\n }\r\n }\r\n // treat eg \"20\" as \"8:00pm\"\r\n else if (time &gt;= 13 &amp;&amp; time &lt;= 99) {\r\n hours = time % 24;\r\n minutes = 0;\r\n // if \"am\" or \"pm\" not specified, force \"am\"\r\n if (am === null) am = true;\r\n }\r\n // treat eg \"52:95\" as 52 hours 95 minutes \r\n else if (time &gt;= 100) {\r\n hours = Math.floor(time / 100); // take first two digits as hour\r\n minutes = time % 100; // take last two digits as minute\r\n // if \"am\" or \"pm\" not specified, establish from number\r\n if (am === null) {\r\n if (hours &gt;= 1 &amp;&amp; hours &lt;= 12) am = false;\r\n else am = true;\r\n }\r\n }\r\n\r\n // add 12 hours if \"pm\"\r\n if (am === false &amp;&amp; hours !== 12) hours += 12;\r\n // sub 12 hours if \"12:00am\" (midnight), making \"00:00\"\r\n if (am === true &amp;&amp; hours === 12) hours = 0;\r\n\r\n // keep hours within 24 and minutes within 60\r\n // eg 52 hours 95 minutes becomes 4 hours 35 minutes\r\n hours = hours % 24;\r\n minutes = minutes % 60;\r\n }\r\n\r\n // convert to js date object\r\n var date = new Date();\r\n date.setHours(hours);\r\n date.setMinutes(minutes);\r\n date.setSeconds(0);\r\n return date;\r\n}\r\n\r\nvar tests = [\r\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\r\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \r\n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\r\n '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];\r\n\r\nfor ( var i = 0; i &lt; tests.length; i++ ) {\r\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parseTime(tests[i]) );\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I feel that this is the closest I can get for my needs, but suggestions are welcome. <strong>Note:</strong> This is American-centric in that it defaults to am/pm for certain patterns:</p>\n\n<ul>\n<li><code>1</code> => <code>13:00</code> (<code>1:00pm</code>)</li>\n<li><code>1100</code> => <code>23:00</code> (<code>11:00pm</code>)</li>\n<li><code>456</code> => <code>16:56</code> (<code>4:56pm</code>)</li>\n</ul>\n" }, { "answer_id": 66371079, "author": "Gabriel", "author_id": 5660086, "author_profile": "https://Stackoverflow.com/users/5660086", "pm_score": 0, "selected": false, "text": "<p>I've needed a time parser function and based on some of the answers i ended up with this function</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function parse(time){\n let post_meridiem = time.match(/p/i) !== null;\n let result;\n time = time.replace(/[^\\d:-]/g, '');\n let hours = 0;\n let minutes = 0;\n if (!time) return;\n let parts = time.split(':');\n if (parts.length &gt; 2) time = parts[0] + ':' + parts[1];\n if (parts[0] &gt; 59 &amp;&amp; parts.length === 2) time = parts[0];\n if (!parts[0] &amp;&amp; parts[1] &lt; 60) minutes = parts[1];\n else if (!parts[0] &amp;&amp; parts[1] &gt;= 60) return;\n time = time.replace(/^00/, '24');\n time = parseInt(time.replace(/\\D/g, ''));\n if (time &gt;= 2500) return;\n if (time &gt; 0 &amp;&amp; time &lt; 24 &amp;&amp; parts.length === 1) hours = time;\n else if (time &lt; 59) minutes = time;\n else if (time &gt;= 60 &amp;&amp; time &lt;= 99 &amp;&amp; parts[0]) {\n hours = ('' + time)[0];\n minutes = ('' + time)[1];\n } else if (time &gt;= 100 &amp;&amp; time &lt;= 2359) {\n hours = ~~(time / 100);\n minutes = time % 100;\n } else if (time &gt;= 2400) {\n hours = ~~(time / 100) - 24;\n minutes = time % 100;\n post_meridiem = false;\n }\n if (hours &gt; 59 || minutes &gt; 59) return;\n if (post_meridiem &amp;&amp; hours !== 0) hours += 12;\n if (minutes &gt; 59) minutes = 59;\n if (hours &gt; 23) hours = 0;\n result = ('' + hours).padStart(2, '0') + ':' + ('' + minutes).padStart(2, '0');\n return result;\n}\n var tests = [\n '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',\n '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', \n '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',\n '1234', '1', '9', '99', '999', '9999', '0000', '0011', '-1', 'mioaw',\n \"0820\",\n \"32\",\n \"124\",\n \"1330\",\n \"130pm\",\n \"456\",\n \":40\",\n \":90\",\n \"12:69\",\n \"50:90\",\n \"aaa12:34aaa\",\n \"aaa50:00aaa\",\n ];\n\n for ( var i = 0; i &lt; tests.length; i++ ) {\n console.log( tests[i].padStart( 9, ' ' ) + \" = \" + parse(tests[i]) );\n }</code></pre>\r\n</div>\r\n</div>\r\n\nalso it's on Compilation table of other answers here is a fork\n<a href=\"http://jsfiddle.net/gabihp30/8tur5kb4/9/\" rel=\"nofollow noreferrer\">Compilation table of other answers</a></p>\n" }, { "answer_id": 71097961, "author": "Jacob Lockett", "author_id": 8429492, "author_profile": "https://Stackoverflow.com/users/8429492", "pm_score": 0, "selected": false, "text": "<p>The main upvoted and selected answers were causing trouble for me and outputting ridiculous results. Below is my stab at it which seems to solve all the issues most people were having, including mine. An added functionality to mine is the ability to specify 'am' or 'pm' as a time of day to default to should the user input not specify (e.g. 1:00). By default, it's set to 'pm'.</p>\n<p>One thing to note is this function assumes the user wants to (and attempted to) provide a string representing a time input. Because of this, the &quot;input validation and sanitation&quot; only goes so far as to rule out anything that would cause an error, not anything that doesn't necessarily look like a time. This is best represented by the final three test entries in the array towards the bottom of the code snippet.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const parseTime = (timeString, assumedTimeOfDay = \"pm\") =&gt; {\n // Validate timeString input\n if (!timeString) return null\n\n const regex = /(\\d{1,2})(\\d{2})?([a|p]m?)?/\n const noOfDigits = timeString.replace(/[^\\d]/g, \"\").length\n\n if (noOfDigits === 0) return null\n\n // Seconds are unsupported (rare use case in my eyes, feel free to edit)\n if (noOfDigits &gt; 4) return null\n\n // Add a leading 0 to prevent bad regex match (i.e. 100 = 1hr 00min, not 10hr 0min)\n const sanitized = `${noOfDigits === 3 ? \"0\" : \"\"}${timeString}`\n .toLowerCase()\n .replace(/[^\\dapm]/g, \"\")\n const parsed = sanitized.match(regex)\n\n if (!parsed) return null\n\n // Clean up and name parsed data\n const {\n input,\n hours,\n minutes,\n meridian\n } = {\n input: parsed[0],\n hours: Number(parsed[1] || 0),\n minutes: Number(parsed[2] || 0),\n // Defaults to pm if user provided assumedTimeOfDay is not am or pm\n meridian: /am/.test(`${parsed[3] || assumedTimeOfDay.toLowerCase()}m`) ?\n \"am\" : \"pm\",\n }\n\n // Quick check for valid numbers\n if (hours &lt; 0 || hours &gt;= 24 || minutes &lt; 0 || minutes &gt;= 60) return null\n\n // Convert hours to 24hr format\n const timeOfDay = hours &gt;= 13 ? \"pm\" : meridian\n const newHours =\n hours &gt;= 13 ?\n hours :\n hours === 12 &amp;&amp; timeOfDay === \"am\" ?\n 0 :\n (hours === 12 &amp;&amp; timeOfDay === \"pm\") || timeOfDay === \"am\" ?\n hours :\n hours + 12\n\n // Convert data to Date object and return\n return new Date(new Date().setHours(newHours, minutes, 0))\n}\n\nconst times = [\n '12',\n '12p',\n '12pm',\n '12p.m.',\n '12 p',\n '12 pm',\n '12 p.m.',\n '12:00',\n '12:00p',\n '12:00pm',\n '12:00p.m.',\n '12:00 p',\n '12:00 pm',\n '12:00 p.m.',\n '12:00',\n '12:00p',\n '12:00pm',\n '12:00p.m.',\n '12:00 p',\n '12:00 pm',\n '12:00 p.m.',\n '1200',\n '1200p',\n '1200pm',\n '1200p.m.',\n '1200 p',\n '1200 pm',\n '1200 p.m.',\n '12',\n '1200',\n '12:00',\n '1',\n '1p',\n '1pm',\n '1p.m.',\n '1 p',\n '1 pm',\n '1 p.m.',\n '1:00',\n '1:00p',\n '1:00pm',\n '1:00p.m.',\n '1:00 p',\n '1:00 pm',\n '1:00 p.m.',\n '01:00',\n '01:00p',\n '01:00pm',\n '01:00p.m.',\n '01:00 p',\n '01:00 pm',\n '01:00 p.m.',\n '0100',\n '0100p',\n '0100pm',\n '0100p.m.',\n '0100 p',\n '0100 pm',\n '0100 p.m.',\n '13',\n '1300',\n '13:00',\n 'random',\n '092fsd9)*(U243',\n '092fsd9)*(U'\n]\n\ntimes.map(t =&gt; {\n const parsed = parseTime(t)\n\n if (parsed) {\n console.log(`${parsed.toLocaleTimeString()} from ${t}`)\n } else {\n console.log(`Invalid Time (${t})`)\n }\n})</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Although I've tested this quite a bit, I'm sure I tunnel-visioned on something. If someone is able to break it (in a reasonable way), please comment and I'll see about updating!</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18986/" ]
I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript `Date()` object so I can easily perform comparisons and other things on it. I tried the `parse()` method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same `Date()` object: * 1:00 pm * 1:00 p.m. * 1:00 p * 1:00pm * 1:00p.m. * 1:00p * 1 pm * 1 p.m. * 1 p * 1pm * 1p.m. * 1p * 13:00 * 13 I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my `Date()` object. What is the best way to do this?
A quick solution which works on the input that you've specified: ```js function parseTime( t ) { var d = new Date(); var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ ); d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) ); d.setMinutes( parseInt( time[2]) || 0 ); return d; } var tests = [ '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm', '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p', '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ]; for ( var i = 0; i < tests.length; i++ ) { console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) ); } ``` It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example). > > Warning: The code doe not work with 12:00 AM, etc. > > >
141,351
<p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="https://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p> <p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
[ { "answer_id": 142138, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 2, "selected": false, "text": "<p>I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.</p>\n\n<p>If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:</p>\n\n<pre><code>x = SomeObject()\n... later ...\noldRefCount = sys.getrefcount( x )\nsuspiciousFunction( x )\nif (oldRefCount != sys.getrefcount(x)):\n print \"Possible memory leak...\"\n</code></pre>\n\n<p>You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the <code>Py_INCREF</code> and <code>Py_DECREF</code> macros with your own. This might be a bit dangerous in a production app, though.</p>\n\n<p>Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.</p>\n\n<p><a href=\"http://www.python.org/doc/essays/refcnt/\" rel=\"nofollow noreferrer\" title=\"Debugging Reference Counts\">Debugging Reference Counts</a></p>\n" }, { "answer_id": 142177, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://docs.python.org/lib/module-gc.html\" rel=\"nofollow noreferrer\"><code>gc</code> module</a> has some functions that might be useful, like listing all objects the garbage collector found to be unreachable but cannot free, or a list of all objects being tracked.</p>\n\n<p>If you have a suspicion which objects might leak, the <a href=\"http://docs.python.org/lib/module-weakref.html\" rel=\"nofollow noreferrer\">weakref</a> module could be handy to find out if/when objects are collected.</p>\n" }, { "answer_id": 142500, "author": "Brett", "author_id": 22892, "author_profile": "https://Stackoverflow.com/users/22892", "pm_score": 3, "selected": false, "text": "<p>Could you record the traffic (via a log) on your production site, then re-play it on your development server instrumented with a python memory debugger? (I recommend dozer: <a href=\"http://pypi.python.org/pypi/Dozer\" rel=\"noreferrer\">http://pypi.python.org/pypi/Dozer</a>)</p>\n" }, { "answer_id": 142571, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.gsp.com/cgi-bin/man.cgi?section=1&amp;topic=gcore\" rel=\"nofollow noreferrer\">Make your program dump core</a>, then clone an instance of the program on a sufficiently similar box using <a href=\"http://www.gsp.com/cgi-bin/man.cgi?section=1&amp;topic=gdb\" rel=\"nofollow noreferrer\">gdb</a>. There are <a href=\"http://wiki.python.org/moin/DebuggingWithGdb\" rel=\"nofollow noreferrer\">special macros</a> to help with debugging python programs within gdb, but if you can get your program to concurrently <a href=\"http://blog.vrplumber.com/index.php?/archives/1631-Minimal-example-of-using-twisted.manhole-Since-it-took-me-so-long-to-get-it-working....html\" rel=\"nofollow noreferrer\">serve up a remote shell</a>, you could just continue the program's execution, and query it with python.</p>\n\n<p>I have never had to do this, so I'm not 100% sure it'll work, but perhaps the pointers will be helpful.</p>\n" }, { "answer_id": 2170051, "author": "keturn", "author_id": 9585, "author_profile": "https://Stackoverflow.com/users/9585", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://edge.launchpad.net/meliae\" rel=\"nofollow noreferrer\">Meliae</a> looks promising:</p>\n<blockquote>\n<p>This project is similar to heapy (in the 'guppy' project), in its attempt to understand how memory has been allocated.</p>\n<p>Currently, its main difference is that it splits the task of computing summary statistics, etc of memory consumption from the actual scanning of memory consumption. It does this, because I often want to figure out what is going on in my process, while my process is consuming huge amounts of memory (1GB, etc). It also allows dramatically simplifying the scanner, as I don't allocate python objects while trying to analyze python object memory consumption.</p>\n</blockquote>\n" }, { "answer_id": 9567831, "author": "gerdemb", "author_id": 27478, "author_profile": "https://Stackoverflow.com/users/27478", "pm_score": 5, "selected": false, "text": "<p>Using Python's <code>gc</code> garbage collector interface and <code>sys.getsizeof()</code> it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak:</p>\n\n<pre><code>rss = psutil.Process(os.getpid()).get_memory_info().rss\n# Dump variables if using more than 100MB of memory\nif rss &gt; 100 * 1024 * 1024:\n memory_dump()\n os.abort()\n\ndef memory_dump():\n dump = open(\"memory.pickle\", 'wb')\n xs = []\n for obj in gc.get_objects():\n i = id(obj)\n size = sys.getsizeof(obj, 0)\n # referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]\n referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]\n if hasattr(obj, '__class__'):\n cls = str(obj.__class__)\n xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})\n cPickle.dump(xs, dump)\n</code></pre>\n\n<p>Note that I'm only saving data from objects that have a <code>__class__</code> attribute because those are the only objects I care about. It should be possible to save the complete list of objects, but you will need to take care choosing other attributes. Also, I found that getting the referrers for each object was extremely slow so I opted to save only the referents. Anyway, after the crash, the resulting pickled data can be read back like this:</p>\n\n<pre><code>with open(\"memory.pickle\", 'rb') as dump:\n objs = cPickle.load(dump)\n</code></pre>\n\n<h2>Added 2017-11-15</h2>\n\n<p>The Python 3.6 version is here:</p>\n\n<pre><code>import gc\nimport sys\nimport _pickle as cPickle\n\ndef memory_dump():\n with open(\"memory.pickle\", 'wb') as dump:\n xs = []\n for obj in gc.get_objects():\n i = id(obj)\n size = sys.getsizeof(obj, 0)\n # referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]\n referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]\n if hasattr(obj, '__class__'):\n cls = str(obj.__class__)\n xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})\n cPickle.dump(xs, dump)\n</code></pre>\n" }, { "answer_id": 61260839, "author": "saaj", "author_id": 2072035, "author_profile": "https://Stackoverflow.com/users/2072035", "pm_score": 6, "selected": true, "text": "<p>I will expand on Brett's answer from my recent experience. <a href=\"https://pypi.org/project/Dozer/\" rel=\"noreferrer\">Dozer package</a> is <a href=\"https://github.com/mgedmin/dozer\" rel=\"noreferrer\">well maintained</a>, and despite advancements, like addition of <code>tracemalloc</code> to stdlib in Python 3.4, its <code>gc.get_objects</code> counting chart is my go-to tool to tackle memory leaks. Below I use <code>dozer &gt; 0.7</code> which has not been released at the time of writing (well, because I contributed a couple of fixes there recently).</p>\n<h1>Example</h1>\n<p>Let's look at a non-trivial memory leak. I'll use <a href=\"http://www.celeryproject.org/\" rel=\"noreferrer\">Celery</a> 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 <em>venv</em> where I <code>pip install celery &lt; 4.5</code>. And have the following module.</p>\n<p><em>demo.py</em></p>\n<pre><code>import time\n\nimport celery \n\n\nredis_dsn = 'redis://localhost'\napp = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)\n\[email protected]\ndef subtask():\n pass\n\[email protected]\ndef task():\n for i in range(10_000):\n subtask.delay()\n time.sleep(0.01)\n\n\nif __name__ == '__main__':\n task.delay().get()\n</code></pre>\n<p>Basically a task which schedules a bunch of subtasks. What can go wrong?</p>\n<p>I'll use <a href=\"https://pypi.org/project/Procpath/\" rel=\"noreferrer\"><code>procpath</code></a> to analyse Celery node memory consumption. <code>pip install procpath</code>. I have 4 terminals:</p>\n<ol>\n<li><code>procpath record -d celery.sqlite -i1 &quot;$..children[?('celery' in @.cmdline)]&quot;</code> to record the Celery node's process tree stats</li>\n<li><code>docker run --rm -it -p 6379:6379 redis</code> to run Redis which will serve as Celery broker and result backend</li>\n<li><code>celery -A demo worker --concurrency 2</code> to run the node with 2 workers</li>\n<li><code>python demo.py</code> to finally run the example</li>\n</ol>\n<p>(4) will finish under 2 minutes.</p>\n<p>Then I use <a href=\"https://github.com/lana-k/sqliteviz\" rel=\"noreferrer\">sqliteviz</a> (<a href=\"https://lana-k.github.io/sqliteviz/\" rel=\"noreferrer\">pre-built version</a>) to visualise what <code>procpath</code> has recorder. I drop the <code>celery.sqlite</code> there and use this query:</p>\n<pre><code>SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss\nFROM record \n</code></pre>\n<p>And in sqliteviz I create a line chart trace with <code>X=ts</code>, <code>Y=rss</code>, and add split transform <code>By=stat_pid</code>. The result chart is:</p>\n<p><a href=\"https://i.stack.imgur.com/US20P.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/US20P.png\" alt=\"Celery node leak\" /></a></p>\n<p>This shape is likely pretty familiar to anyone who fought with memory leaks.</p>\n<h1>Finding leaking objects</h1>\n<p>Now it's time for <code>dozer</code>. I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use <a href=\"https://pypi.org/project/pyrasite/\" rel=\"noreferrer\">Pyrasite</a>. There are two things to know about it:</p>\n<ul>\n<li>To run it, <a href=\"http://man7.org/linux/man-pages/man2/ptrace.2.html\" rel=\"noreferrer\">ptrace</a> has to be configured as &quot;classic ptrace permissions&quot;: <code>echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope</code>, which is may be a security risk</li>\n<li>There are non-zero chances that your target Python process will crash</li>\n</ul>\n<p>With that caveat I:</p>\n<ul>\n<li><code>pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip</code> (that's to-be 0.8 I mentioned above)</li>\n<li><code>pip install pillow</code> (which <code>dozer</code> uses for charting)</li>\n<li><code>pip install pyrasite</code></li>\n</ul>\n<p>After that I can get Python shell in the target process:</p>\n<pre><code>pyrasite-shell 26572\n</code></pre>\n<p>And inject the following, which will run Dozer's WSGI application using stdlib's <code>wsgiref</code>'s server.</p>\n<pre><code>import threading\nimport wsgiref.simple_server\n\nimport dozer\n\n\ndef run_dozer():\n app = dozer.Dozer(app=None, path='/')\n with wsgiref.simple_server.make_server('', 8000, app) as httpd:\n print('Serving Dozer on port 8000...')\n httpd.serve_forever()\n\nthreading.Thread(target=run_dozer, daemon=True).start()\n</code></pre>\n<p>Opening <code>http://localhost:8000</code> in a browser there should see something like:</p>\n<p><a href=\"https://i.stack.imgur.com/5hDUb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5hDUb.png\" alt=\"dozer\" /></a></p>\n<p>After that I run <code>python demo.py</code> from (4) again and wait for it to finish. Then in Dozer I set &quot;Floor&quot; to 5000, and here's what I see:</p>\n<p><a href=\"https://i.stack.imgur.com/VoTDD.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VoTDD.png\" alt=\"dozer shows Celery leak\" /></a></p>\n<p>Two types related to Celery grow as the subtask are scheduled:</p>\n<ul>\n<li><code>celery.result.AsyncResult</code></li>\n<li><code>vine.promises.promise</code></li>\n</ul>\n<p><code>weakref.WeakMethod</code> has the same shape and numbers and must be caused by the same thing.</p>\n<h1>Finding root cause</h1>\n<p>At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has &quot;TRACE&quot; link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers (<code>gc.get_referrers</code>) and referents (<code>gc.get_referents</code>), and continue the process again traversing the graph.</p>\n<p>But a picture says a thousand words, right? So I'll show how to use <a href=\"https://pypi.org/project/objgraph/\" rel=\"noreferrer\"><code>objgraph</code></a> to render chosen object's dependency graph.</p>\n<ul>\n<li><code>pip install objgraph</code></li>\n<li><code>apt-get install graphviz</code></li>\n</ul>\n<p>Then:</p>\n<ul>\n<li>I run <code>python demo.py</code> from (4) again</li>\n<li>in Dozer I set <code>floor=0</code>, <code>filter=AsyncResult</code></li>\n<li>and click &quot;TRACE&quot; which should yield</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/GRp77.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GRp77.png\" alt=\"trace\" /></a></p>\n<p>Then in Pyrasite shell run:</p>\n<pre><code>objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png')\n</code></pre>\n<p>The PNG file should contain:</p>\n<p><a href=\"https://i.stack.imgur.com/TrU1M.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TrU1M.png\" alt=\"backref chart\" /></a></p>\n<p>Basically there's some <code>Context</code> object containing a <code>list</code> called <code>_children</code> that in turn is containing many instances of <code>celery.result.AsyncResult</code>, which leak. Changing <code>Filter=celery.*context</code> in Dozer here's what I see:</p>\n<p><a href=\"https://i.stack.imgur.com/sIplB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sIplB.png\" alt=\"Celery context\" /></a></p>\n<p>So the culprit is <code>celery.app.task.Context</code>. Searching that type would certainly lead you to <a href=\"https://docs.celeryproject.org/en/stable/reference/celery.app.task.html\" rel=\"noreferrer\">Celery task page</a>. Quickly searching for &quot;children&quot; there, here's what it says:</p>\n<blockquote>\n<p><code>trail = True</code></p>\n<p>If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result (<code>result.children</code>).</p>\n</blockquote>\n<p>Disabling the trail by setting <code>trail=False</code> like:</p>\n<pre><code>@app.task(trail=False)\ndef task():\n for i in range(10_000):\n subtask.delay()\n time.sleep(0.01)\n</code></pre>\n<p>Then restarting the Celery node from (3) and <code>python demo.py</code> from (4) yet again, shows this memory consumption.</p>\n<p><a href=\"https://i.stack.imgur.com/CzTin.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CzTin.png\" alt=\"solved\" /></a></p>\n<p>Problem solved!</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9585/" ]
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a [Python memory profiler](https://stackoverflow.com/questions/110259/python-memory-profiler) (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server. What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get\_objects), and then analyze it offline to see where it is using memory. [How do I get a core dump of a python process like this?](https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection) Once I have one, how do I do something useful with it?
I will expand on Brett's answer from my recent experience. [Dozer package](https://pypi.org/project/Dozer/) is [well maintained](https://github.com/mgedmin/dozer), and despite advancements, like addition of `tracemalloc` to stdlib in Python 3.4, its `gc.get_objects` counting chart is my go-to tool to tackle memory leaks. Below I use `dozer > 0.7` which has not been released at the time of writing (well, because I contributed a couple of fixes there recently). Example ======= Let's look at a non-trivial memory leak. I'll use [Celery](http://www.celeryproject.org/) 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 *venv* where I `pip install celery < 4.5`. And have the following module. *demo.py* ``` import time import celery redis_dsn = 'redis://localhost' app = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn) @app.task def subtask(): pass @app.task def task(): for i in range(10_000): subtask.delay() time.sleep(0.01) if __name__ == '__main__': task.delay().get() ``` Basically a task which schedules a bunch of subtasks. What can go wrong? I'll use [`procpath`](https://pypi.org/project/Procpath/) to analyse Celery node memory consumption. `pip install procpath`. I have 4 terminals: 1. `procpath record -d celery.sqlite -i1 "$..children[?('celery' in @.cmdline)]"` to record the Celery node's process tree stats 2. `docker run --rm -it -p 6379:6379 redis` to run Redis which will serve as Celery broker and result backend 3. `celery -A demo worker --concurrency 2` to run the node with 2 workers 4. `python demo.py` to finally run the example (4) will finish under 2 minutes. Then I use [sqliteviz](https://github.com/lana-k/sqliteviz) ([pre-built version](https://lana-k.github.io/sqliteviz/)) to visualise what `procpath` has recorder. I drop the `celery.sqlite` there and use this query: ``` SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss FROM record ``` And in sqliteviz I create a line chart trace with `X=ts`, `Y=rss`, and add split transform `By=stat_pid`. The result chart is: [![Celery node leak](https://i.stack.imgur.com/US20P.png)](https://i.stack.imgur.com/US20P.png) This shape is likely pretty familiar to anyone who fought with memory leaks. Finding leaking objects ======================= Now it's time for `dozer`. I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use [Pyrasite](https://pypi.org/project/pyrasite/). There are two things to know about it: * To run it, [ptrace](http://man7.org/linux/man-pages/man2/ptrace.2.html) has to be configured as "classic ptrace permissions": `echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope`, which is may be a security risk * There are non-zero chances that your target Python process will crash With that caveat I: * `pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip` (that's to-be 0.8 I mentioned above) * `pip install pillow` (which `dozer` uses for charting) * `pip install pyrasite` After that I can get Python shell in the target process: ``` pyrasite-shell 26572 ``` And inject the following, which will run Dozer's WSGI application using stdlib's `wsgiref`'s server. ``` import threading import wsgiref.simple_server import dozer def run_dozer(): app = dozer.Dozer(app=None, path='/') with wsgiref.simple_server.make_server('', 8000, app) as httpd: print('Serving Dozer on port 8000...') httpd.serve_forever() threading.Thread(target=run_dozer, daemon=True).start() ``` Opening `http://localhost:8000` in a browser there should see something like: [![dozer](https://i.stack.imgur.com/5hDUb.png)](https://i.stack.imgur.com/5hDUb.png) After that I run `python demo.py` from (4) again and wait for it to finish. Then in Dozer I set "Floor" to 5000, and here's what I see: [![dozer shows Celery leak](https://i.stack.imgur.com/VoTDD.png)](https://i.stack.imgur.com/VoTDD.png) Two types related to Celery grow as the subtask are scheduled: * `celery.result.AsyncResult` * `vine.promises.promise` `weakref.WeakMethod` has the same shape and numbers and must be caused by the same thing. Finding root cause ================== At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has "TRACE" link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers (`gc.get_referrers`) and referents (`gc.get_referents`), and continue the process again traversing the graph. But a picture says a thousand words, right? So I'll show how to use [`objgraph`](https://pypi.org/project/objgraph/) to render chosen object's dependency graph. * `pip install objgraph` * `apt-get install graphviz` Then: * I run `python demo.py` from (4) again * in Dozer I set `floor=0`, `filter=AsyncResult` * and click "TRACE" which should yield [![trace](https://i.stack.imgur.com/GRp77.png)](https://i.stack.imgur.com/GRp77.png) Then in Pyrasite shell run: ``` objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png') ``` The PNG file should contain: [![backref chart](https://i.stack.imgur.com/TrU1M.png)](https://i.stack.imgur.com/TrU1M.png) Basically there's some `Context` object containing a `list` called `_children` that in turn is containing many instances of `celery.result.AsyncResult`, which leak. Changing `Filter=celery.*context` in Dozer here's what I see: [![Celery context](https://i.stack.imgur.com/sIplB.png)](https://i.stack.imgur.com/sIplB.png) So the culprit is `celery.app.task.Context`. Searching that type would certainly lead you to [Celery task page](https://docs.celeryproject.org/en/stable/reference/celery.app.task.html). Quickly searching for "children" there, here's what it says: > > `trail = True` > > > If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result (`result.children`). > > > Disabling the trail by setting `trail=False` like: ``` @app.task(trail=False) def task(): for i in range(10_000): subtask.delay() time.sleep(0.01) ``` Then restarting the Celery node from (3) and `python demo.py` from (4) yet again, shows this memory consumption. [![solved](https://i.stack.imgur.com/CzTin.png)](https://i.stack.imgur.com/CzTin.png) Problem solved!
141,368
<p>Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday.</p> <p>This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday.</p> <p>Can anyone suggest any optimizations or alternatives.</p> <pre><code> public decimal ElapsedWorkingHours(DateTime start, DateTime finish) { decimal counter = 0; while (start.CompareTo(finish) &lt;= 0) { if (IsWorkingDay(start) &amp;&amp; IsOfficeHours(start)) { start = start.AddMinutes(1); counter++; } else { start = start.AddMinutes(1); } } decimal hours; if (counter != 0) { hours = counter/60; } return hours; } </code></pre>
[ { "answer_id": 141384, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>especially considering the IsWorkingDay method hits the DB to see if that day is a public holiday</p>\n</blockquote>\n\n<p>If the problem is the number of queries rather than the amount of data, query the working day data from the data base for the entire day range you need at the beginning instead of querying in each loop iteration.</p>\n" }, { "answer_id": 141392, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 2, "selected": false, "text": "<p>Before you start optimizing it, ask yourself two questions.</p>\n\n<p>a) Does it work?</p>\n\n<p>b) Is it too slow?</p>\n\n<p>Only if the answer to both question is \"yes\" are you ready to start optimizing.</p>\n\n<p>Apart from that</p>\n\n<ul>\n<li>you only need to worry about minutes and hours on the start day and end day. Intervening days will obviously be a full 9/9.5 hours, unless they are holidays or weekends</li>\n<li>No need to check a weekend day to see if it's a holiday</li>\n</ul>\n\n<p>Here's how I'd do it </p>\n\n<pre><code>// Normalise start and end \nwhile start.day is weekend or holiday, start.day++, start.time = 0.00am\n if start.day is monday,\n start.time = max(start.time, 8am)\n else\n start.time = max(start.time, 8.30am)\nwhile end.day is weekend or holiday, end.day--, end.time = 11.59pm\nend.time = min(end.time, 5.30pm)\n\n// Now we've normalised, is there any time left? \nif start &gt; end\n return 0\n\n// Calculate time in first day \ntimediff = 5.30pm - start.time\nday = start.day + 1\n// Add time on all intervening days\nwhile(day &lt; end.day)\n // returns 9 or 9.30hrs or 0 as appropriate, could be optimised to grab all records\n // from the database in 1 or 2 hits, by counting all intervening mondays, and all\n // intervening tue-fris (non-holidays)\n timediff += duration(day) \n\n// Add time on last day\ntimediff += end.time - 08.30am\nif end.day is Monday then\n timediff += end.time - 08.00am\nelse\n timediff += end.time - 08.30am\n\nreturn timediff\n</code></pre>\n\n<p>You could do something like\nSELECT COUNT(DAY) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End GROUP BY DAY</p>\n\n<p>to count the number of holidays falling on Monday, Tuesday, Wednesday, and so forth. Probably a way of getting SQL to count just Mondays and non-Mondays, though can't think of anything at the moment.</p>\n" }, { "answer_id": 141401, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": false, "text": "<p>Take a look at the TimeSpan Class. That will give you the hours between any 2 times.</p>\n\n<p>A single DB call can also get the holidays between your two times; something along the lines of:</p>\n\n<pre><code>SELECT COUNT(*) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End\n</code></pre>\n\n<p>Multiply that count by 8 and subtract it from your total hours.</p>\n\n<p>-Ian</p>\n\n<p><strong>EDIT</strong>: In response to below, If you're holiday's are not a constant number of hours. you can keep a <code>HolidayStart</code> and a <code>HolidayEnd</code> Time in your DB and and just return them from the call to the db as well. Do an hour count similar to whatever method you settle on for the main routine.</p>\n" }, { "answer_id": 141415, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Building on what @OregonGhost said, rather than using an IsWorkingDay() function at accepts a day and returns a boolean, have a HolidayCount() function that accepts a range and returns an integer giving the number of Holidays in the range. The trick here is if you're dealing with a partial date for your boundry beginning and end days you may still need to determine if those dates are themselves holidays. But even then, you could use the new method to make sure you needed <em>at most</em> three calls the to DB.</p>\n" }, { "answer_id": 141473, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>Try something along these lines:</p>\n\n<pre><code>TimeSpan = TimeSpan Between Date1 And Date2\ncntDays = TimeSpan.Days \ncntNumberMondays = Iterate Between Date1 And Date2 Counting Mondays \ncntdays = cntdays - cntnumbermondays\nNumHolidays = DBCall To Get # Holidays BETWEEN Date1 AND Date2\nCntdays = cntdays - numholidays \nnumberhours = ((decimal)cntdays * NumberHoursInWorkingDay )+((decimal)cntNumberMondays * NumberHoursInMondayWorkDay )\n</code></pre>\n" }, { "answer_id": 141494, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 1, "selected": false, "text": "<p>There's also the recursive solution. Not necessarily efficient, but a lot of fun:</p>\n\n<pre><code>public decimal ElapseddWorkingHours(DateTime start, DateTime finish)\n{\n if (start.Date == finish.Date)\n return (finish - start).TotalHours;\n\n if (IsWorkingDay(start.Date))\n return ElapsedWorkingHours(start, new DateTime(start.Year, start.Month, start.Day, 17, 30, 0))\n + ElapsedWorkingHours(start.Date.AddDays(1).AddHours(DateStartTime(start.Date.AddDays(1)), finish);\n else\n return ElapsedWorkingHours(start.Date.AddDays(1), finish);\n}\n</code></pre>\n" }, { "answer_id": 141529, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>The most efficient way to do this is to calculate the total time difference, then subtract the time that is a weekend or holiday. There are quite a few edge cases to consider, but you can simplify that by taking the first and last days of the range and calculating them seperately.</p>\n\n<p>The COUNT(*) method suggested by <a href=\"https://stackoverflow.com/questions/141368/calculating-the-elapsed-working-hours-between-2-dates#141401\">Ian Jacobs</a> seems like a good way to count the holidays. Whatever you use, it will just handle the whole days, you need to cover the start and end dates separately.</p>\n\n<p>Counting the weekend days is easy; if you have a function Weekday(date) that returns 0 for Monday through 6 for Sunday, it looks like this:</p>\n\n<pre><code>saturdays = ((finish - start) + Weekday(start) + 2) / 7;\nsundays = ((finish - start) + Weekday(start) + 1) / 7;\n</code></pre>\n\n<p>Note: (finish - start) isn't to be taken literally, replace it with something that calculates the time span in days.</p>\n" }, { "answer_id": 141550, "author": "jgreep", "author_id": 16345, "author_profile": "https://Stackoverflow.com/users/16345", "pm_score": 0, "selected": false, "text": "<p>Use @Ian's query to check between dates to find out which days are not working days. Then do some math to find out if your start time or end time falls on a non-working day and subtract the difference.</p>\n\n<p>So if start is Saturday noon, and end is Monday noon, the query should give you back 2 days, from which you calculate 48 hours (2 x 24). If your query on IsWorkingDay(start) returns false, subtract from 24 the time from start to midnight, which would give you 12 hours, or 36 hours total non-working hours.</p>\n\n<p>Now, if your office hours are the same for every day, you do a similar thing. If your office hours are a bit scattered, you'll have more trouble.</p>\n\n<p>Ideally, make a single query on the database that gives you all of the office hours between the two times (or even dates). Then do the math locally from that set.</p>\n" }, { "answer_id": 3603200, "author": "Wes", "author_id": 435243, "author_profile": "https://Stackoverflow.com/users/435243", "pm_score": -1, "selected": false, "text": "<pre><code>Dim totalMinutes As Integer = 0\n\nFor minute As Integer = 0 To DateDiff(DateInterval.Minute, contextInParameter1, contextInParameter2)\n Dim d As Date = contextInParameter1.AddMinutes(minute)\n If d.DayOfWeek &lt;= DayOfWeek.Friday AndAlso _\n d.DayOfWeek &gt;= DayOfWeek.Monday AndAlso _\n d.Hour &gt;= 8 AndAlso _\n d.Hour &lt;= 17 Then\n totalMinutes += 1\n Else\n Dim test = \"\"\n End If\nNext minute\n\nDim totalHours = totalMinutes / 60\n</code></pre>\n\n<p>Piece of Cake! </p>\n\n<p>Cheers!</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday. This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday. Can anyone suggest any optimizations or alternatives. ``` public decimal ElapsedWorkingHours(DateTime start, DateTime finish) { decimal counter = 0; while (start.CompareTo(finish) <= 0) { if (IsWorkingDay(start) && IsOfficeHours(start)) { start = start.AddMinutes(1); counter++; } else { start = start.AddMinutes(1); } } decimal hours; if (counter != 0) { hours = counter/60; } return hours; } ```
Before you start optimizing it, ask yourself two questions. a) Does it work? b) Is it too slow? Only if the answer to both question is "yes" are you ready to start optimizing. Apart from that * you only need to worry about minutes and hours on the start day and end day. Intervening days will obviously be a full 9/9.5 hours, unless they are holidays or weekends * No need to check a weekend day to see if it's a holiday Here's how I'd do it ``` // Normalise start and end while start.day is weekend or holiday, start.day++, start.time = 0.00am if start.day is monday, start.time = max(start.time, 8am) else start.time = max(start.time, 8.30am) while end.day is weekend or holiday, end.day--, end.time = 11.59pm end.time = min(end.time, 5.30pm) // Now we've normalised, is there any time left? if start > end return 0 // Calculate time in first day timediff = 5.30pm - start.time day = start.day + 1 // Add time on all intervening days while(day < end.day) // returns 9 or 9.30hrs or 0 as appropriate, could be optimised to grab all records // from the database in 1 or 2 hits, by counting all intervening mondays, and all // intervening tue-fris (non-holidays) timediff += duration(day) // Add time on last day timediff += end.time - 08.30am if end.day is Monday then timediff += end.time - 08.00am else timediff += end.time - 08.30am return timediff ``` You could do something like SELECT COUNT(DAY) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End GROUP BY DAY to count the number of holidays falling on Monday, Tuesday, Wednesday, and so forth. Probably a way of getting SQL to count just Mondays and non-Mondays, though can't think of anything at the moment.
141,370
<p>What is the best way to specify a property name when using INotifyPropertyChanged? </p> <p>Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.</p>
[ { "answer_id": 141379, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 4, "selected": false, "text": "<p>The reflection overhead here is pretty much overkill especially since INotifyPropertyChanged gets called <strong>a lot</strong>. It's best just to hard code the value if you can.</p>\n\n<p>If you aren't concerned about performance then I'd look at the various approached mentioned below and pick that that requires the least amount of coding. If you could do something to completely removes the need for the explicit call then that would be best (e.g. AOP).</p>\n" }, { "answer_id": 141416, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 3, "selected": false, "text": "<p>Yeah I see the use and simplicity of the function you are suggesting, but when considering the running cost due to reflection, yeah that is a bad idea, What I use for this scenario is having a <strong>Code snippet</strong> added properly to take advantage of the time and error in writing a property with all the Notifyproperty event firing.</p>\n" }, { "answer_id": 141559, "author": "rdeetz", "author_id": 22789, "author_profile": "https://Stackoverflow.com/users/22789", "pm_score": 1, "selected": false, "text": "<p>Additionally, we found an issue where getting a method name worked differently in Debug vs. Release builds:</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/244d3f24-4cc4-4925-aebe-85f55b39ec92\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/244d3f24-4cc4-4925-aebe-85f55b39ec92</a></p>\n\n<p>(The code we were using wasn't exactly reflection in the way you suggested, but it convinced us that hardcoding the property name was the fastest and most reliable solution.)</p>\n" }, { "answer_id": 142403, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 1, "selected": false, "text": "<p>I did something like this once as an experiment, from memory it worked OK, and removed the need to hardcode all the property names in strings. Performance could be in issue if your building a high volume server application, on the desktop you'll probably never notice the difference.</p>\n\n<pre><code>protected void OnPropertyChanged()\n{\n OnPropertyChanged(PropertyName);\n}\n\nprotected string PropertyName\n{\n get\n {\n MethodBase mb = new StackFrame(1).GetMethod();\n string name = mb.Name;\n if(mb.Name.IndexOf(\"get_\") &gt; -1)\n name = mb.Name.Replace(\"get_\", \"\");\n\n if(mb.Name.IndexOf(\"set_\") &gt; -1)\n name = mb.Name.Replace(\"set_\", \"\");\n\n return name;\n }\n}\n</code></pre>\n" }, { "answer_id": 142973, "author": "Dominic Hopton", "author_id": 9475, "author_profile": "https://Stackoverflow.com/users/9475", "pm_score": 1, "selected": false, "text": "<p>The problem with the reflection based method is that it's rather expensive, and isn't terribly quick. Sure, it is much more flexible, and less brittle towards refactoring.</p>\n\n<p>However, it really can hurt performance, especially when things are called frequently. The stackframe method, also (I believe) has issues in CAS (e.g. restricted trust levels, such as XBAP). It's best to hard code it.</p>\n\n<p>If your looking for fast, flexible property notification in WPF there is a solution -- use DependencyObject :) Thats what it was designed for. If you don't want to take the dependency, or worry about the thread affinity issues, move the property name into a constant, and boom! your good.</p>\n" }, { "answer_id": 143611, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 7, "selected": true, "text": "<p>Don't forget one thing : <code>PropertyChanged</code> event is mainly consumed by components that will <strong>use reflection</strong> to get the value of the named property.</p>\n\n<p>The most obvious example is databinding.</p>\n\n<p>When you fire <code>PropertyChanged</code> event, passing the name of the property as a parameter, you should know that <em>the subscriber of this event is likely to use reflection</em> by calling, for instance, <code>GetProperty</code> (at least the first time if it uses a cache of <code>PropertyInfo</code>), then <code>GetValue</code>. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the <code>GetProperty</code> which only queries meta data. (Note that data binding relies on the whole <a href=\"http://msdn.microsoft.com/en-us/library/ms171819.aspx\" rel=\"noreferrer\">TypeDescriptor</a> thing -- but the default implementation uses reflection.)</p>\n\n<p>So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism.</p>\n\n<p>Here is what I use sometimes in C# 3.0, when performances would not be a concern :</p>\n\n<pre><code>public class Person : INotifyPropertyChanged\n{\n private string name;\n\n public string Name\n {\n get { return this.name; }\n set \n { \n this.name = value;\n FirePropertyChanged(p =&gt; p.Name);\n }\n }\n\n private void FirePropertyChanged&lt;TValue&gt;(Expression&lt;Func&lt;Person, TValue&gt;&gt; propertySelector)\n {\n if (PropertyChanged == null)\n return;\n\n var memberExpression = propertySelector.Body as MemberExpression;\n if (memberExpression == null)\n return;\n\n PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n}\n</code></pre>\n\n<p>Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an <code>Expression</code> :</p>\n\n<pre><code>FirePropertyChanged(p =&gt; p.Name);\n</code></pre>\n" }, { "answer_id": 283844, "author": "Philipp", "author_id": 36889, "author_profile": "https://Stackoverflow.com/users/36889", "pm_score": 4, "selected": false, "text": "<p>Roman:</p>\n\n<p>I'd say you wouldn't even need the \"Person\" parameter - accordingly, a completely generic snippet like the one below should do:</p>\n\n<pre><code>private int age;\npublic int Age\n{\n get { return age; }\n set\n {\n age = value;\n OnPropertyChanged(() =&gt; Age);\n }\n}\n\n\nprivate void OnPropertyChanged&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; exp)\n{\n //the cast will always succeed\n MemberExpression memberExpression = (MemberExpression) exp.Body;\n string propertyName = memberExpression.Member.Name;\n\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n}\n</code></pre>\n\n<p>...however, I prefer sticking to string parameters with conditional validation in Debug builds. Josh Smith posted a nice sample on this: </p>\n\n<p><a href=\"http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/\" rel=\"noreferrer\">A base class which implements INotifyPropertyChanged</a></p>\n\n<p>Cheers :)\nPhilipp</p>\n" }, { "answer_id": 400214, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 1, "selected": false, "text": "<p>You might want to avoid INotifyPropertyChanged altogether. It adds unnecessary bookkeeping code to your project. Consider using <a href=\"http://codeplex.com/updatecontrols\" rel=\"nofollow noreferrer\">Update Controls .NET</a> instead.</p>\n" }, { "answer_id": 764156, "author": "jbe", "author_id": 92594, "author_profile": "https://Stackoverflow.com/users/92594", "pm_score": 2, "selected": false, "text": "<p>You might be interessted in this discussion about </p>\n\n<p><a href=\"http://compositeextensions.codeplex.com/Thread/View.aspx?ThreadId=53731\" rel=\"nofollow noreferrer\">\"Best Practices: How to implement INotifyPropertyChanged right?\"</a></p>\n\n<p>too.</p>\n" }, { "answer_id": 780119, "author": "Peter Gfader", "author_id": 35693, "author_profile": "https://Stackoverflow.com/users/35693", "pm_score": 2, "selected": false, "text": "<p>Another VERY NICE method I can think of is</p>\n\n<p><strong>Auto-implement INotifyPropertyChanged with Aspects</strong><br>\nAOP: Aspect oriented programming</p>\n\n<p>Nice article on codeproject: <a href=\"http://www.codeproject.com/KB/cs/NotifyingAttribute.aspx\" rel=\"nofollow noreferrer\">AOP Implementation of INotifyPropertyChanged</a></p>\n" }, { "answer_id": 1209104, "author": "Phil", "author_id": 148089, "author_profile": "https://Stackoverflow.com/users/148089", "pm_score": 4, "selected": false, "text": "<p>The performance hit involved in the use of expression trees is due to the repeated resolution of the expression tree.</p>\n\n<p>The following code still uses expression trees and thus has the consequent advantages of being refactoring friendly and obfuscation friendly, but is actually approx 40% faster (very rough tests) than the usual technique - which consists of newing up a PropertyChangedEventArgs object for every change notification.</p>\n\n<p>It's quicker and avoids the performance hit of the expression tree because we cache a static PropertyChangedEventArgs object for each property.</p>\n\n<p>There's one thing which I'm not yet doing - I intend to add some code which checks for debug builds that the property name for the supplied PropertChangedEventArgs object matches the property within which it is being used - at the moment with this code it is still possible for the developer to supply the wrong object.</p>\n\n<p>Check it out:</p>\n\n<pre><code> public class Observable&lt;T&gt; : INotifyPropertyChanged\n where T : Observable&lt;T&gt;\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected static PropertyChangedEventArgs CreateArgs(\n Expression&lt;Func&lt;T, object&gt;&gt; propertyExpression)\n {\n var lambda = propertyExpression as LambdaExpression;\n MemberExpression memberExpression;\n if (lambda.Body is UnaryExpression)\n {\n var unaryExpression = lambda.Body as UnaryExpression;\n memberExpression = unaryExpression.Operand as MemberExpression;\n }\n else\n {\n memberExpression = lambda.Body as MemberExpression;\n }\n\n var propertyInfo = memberExpression.Member as PropertyInfo;\n\n return new PropertyChangedEventArgs(propertyInfo.Name);\n }\n\n protected void NotifyChange(PropertyChangedEventArgs args)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, args);\n }\n }\n}\n\npublic class Person : Observable&lt;Person&gt;\n{\n // property change event arg objects\n static PropertyChangedEventArgs _firstNameChangeArgs = CreateArgs(x =&gt; x.FirstName);\n static PropertyChangedEventArgs _lastNameChangeArgs = CreateArgs(x =&gt; x.LastName);\n\n string _firstName;\n string _lastName;\n\n public string FirstName\n {\n get { return _firstName; }\n set\n {\n _firstName = value;\n NotifyChange(_firstNameChangeArgs);\n }\n }\n\n public string LastName\n {\n get { return _lastName; }\n set\n {\n _lastName = value;\n NotifyChange(_lastNameChangeArgs);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1255101, "author": "Boris Modylevsky", "author_id": 91714, "author_profile": "https://Stackoverflow.com/users/91714", "pm_score": 0, "selected": false, "text": "<p>Take a look at this blog post:\n<a href=\"http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code\" rel=\"nofollow noreferrer\"> <a href=\"http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code\" rel=\"nofollow noreferrer\">http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code</a> </a></p>\n" }, { "answer_id": 9192761, "author": "Kévin Rapaille", "author_id": 1073448, "author_profile": "https://Stackoverflow.com/users/1073448", "pm_score": 2, "selected": false, "text": "<p>Without be irrevelant, between Hardcode and reflection, my choice is : <a href=\"http://github.com/SimonCropp/NotifyPropertyWeaver\" rel=\"nofollow\">notifypropertyweaver</a>.</p>\n\n<p>This Visual Studio package allow you to have the benefits of reflection (maintainability, readability,..) without have to lose perfs.</p>\n\n<p>Actually, you just have to implement the INotifyPropertyChanged and it add all the \"notification stuff\" at the compilation.</p>\n\n<p>This is also fully parametrable if you want to fully optimize your code.</p>\n\n<p>For example, with notifypropertyweaver, you will have this code in you editor :</p>\n\n<pre><code>public class Person : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n public string GivenNames { get; set; }\n public string FamilyName { get; set; }\n\n public string FullName\n {\n get\n {\n return string.Format(\"{0} {1}\", GivenNames, FamilyName);\n }\n }\n}\n</code></pre>\n\n<p>Instead of :</p>\n\n<pre><code>public class Person : INotifyPropertyChanged\n{\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n private string givenNames;\n public string GivenNames\n {\n get { return givenNames; }\n set\n {\n if (value != givenNames)\n {\n givenNames = value;\n OnPropertyChanged(\"GivenNames\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n private string familyName;\n public string FamilyName\n {\n get { return familyName; }\n set\n {\n if (value != familyName)\n {\n familyName = value;\n OnPropertyChanged(\"FamilyName\");\n OnPropertyChanged(\"FullName\");\n }\n }\n }\n\n public string FullName\n {\n get\n {\n return string.Format(\"{0} {1}\", GivenNames, FamilyName);\n }\n }\n\n public virtual void OnPropertyChanged(string propertyName)\n {\n var propertyChanged = PropertyChanged;\n if (propertyChanged != null)\n {\n propertyChanged(this, new PropertyChangedEventArgs(propertyName));\n }\n }\n}\n</code></pre>\n\n<p>For french speakers : <a href=\"http://www.kevinrapaille.com/2012/02/amliorez-la-lisibilit-de-votre-code-et-simplifiez-vous-la-vie-avec-notifypropertyweaver/\" rel=\"nofollow\">Améliorez la lisibilité de votre code et simplifiez vous la vie avec notifypropertyweaver</a></p>\n" }, { "answer_id": 12513531, "author": "Harry von Borstel", "author_id": 1573345, "author_profile": "https://Stackoverflow.com/users/1573345", "pm_score": 1, "selected": false, "text": "<p>Yet another approach: <a href=\"http://www.codeproject.com/Articles/450688/Enhanced-MVVM-Design-w-Type-Safe-View-Models-TVM\" rel=\"nofollow\">http://www.codeproject.com/Articles/450688/Enhanced-MVVM-Design-w-Type-Safe-View-Models-TVM</a></p>\n" }, { "answer_id": 14133657, "author": "Denys Wessels", "author_id": 923095, "author_profile": "https://Stackoverflow.com/users/923095", "pm_score": 5, "selected": false, "text": "<p>In .NET 4.5 (C# 5.0) there is a new attribute called - <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx\" rel=\"noreferrer\">CallerMemberName</a> it helps avoid hardcoded property names preventing the onset of bugs if developers decide to change a property name, here's an example:</p>\n\n<pre><code>public event PropertyChangedEventHandler PropertyChanged = delegate { };\n\npublic void OnPropertyChanged([CallerMemberName]string propertyName=\"\")\n{\n PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n}\n\nprivate string name;\npublic string Name\n{\n get { return name; }\n set \n { \n name = value;\n OnPropertyChanged();\n }\n}\n</code></pre>\n" }, { "answer_id": 43206049, "author": "Rekshino", "author_id": 7713750, "author_profile": "https://Stackoverflow.com/users/7713750", "pm_score": 2, "selected": false, "text": "<p>Since C# 6.0 there is a <strong>nameof()</strong> keyword it will be evaluated at compile time, so it will has the performance as hardcoded value and is protected against mismatch with notified property. </p>\n\n<pre><code>public event PropertyChangedEventHandler PropertyChanged;\n\nprotected void NotifyPropertyChanged(string info)\n{ \n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));\n}\npublic string SelectedItem\n{\n get\n {\n return _selectedItem;\n }\n set\n {\n if (_selectedItem != value)\n {\n _selectedItem = value;\n NotifyPropertyChanged(nameof(SelectedItem));\n }\n }\n}\nprivate string _selectedItem;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22813/" ]
What is the best way to specify a property name when using INotifyPropertyChanged? Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.
Don't forget one thing : `PropertyChanged` event is mainly consumed by components that will **use reflection** to get the value of the named property. The most obvious example is databinding. When you fire `PropertyChanged` event, passing the name of the property as a parameter, you should know that *the subscriber of this event is likely to use reflection* by calling, for instance, `GetProperty` (at least the first time if it uses a cache of `PropertyInfo`), then `GetValue`. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the `GetProperty` which only queries meta data. (Note that data binding relies on the whole [TypeDescriptor](http://msdn.microsoft.com/en-us/library/ms171819.aspx) thing -- but the default implementation uses reflection.) So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism. Here is what I use sometimes in C# 3.0, when performances would not be a concern : ``` public class Person : INotifyPropertyChanged { private string name; public string Name { get { return this.name; } set { this.name = value; FirePropertyChanged(p => p.Name); } } private void FirePropertyChanged<TValue>(Expression<Func<Person, TValue>> propertySelector) { if (PropertyChanged == null) return; var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression == null) return; PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); } public event PropertyChangedEventHandler PropertyChanged; } ``` Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an `Expression` : ``` FirePropertyChanged(p => p.Name); ```
141,372
<p>Emacs has a useful <code>transpose-words</code> command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.</p> <p>For example, ‘<code>stack |overflow</code>’ + M-t = ‘<code>overflow stack|</code>’ (‘<code>|</code>’ is the cursor position).</p> <p><code>&lt;a&gt;|&lt;p&gt;</code> becomes <code>&lt;p&gt;&lt;a|&gt;</code>.</p> <p>Is it possible to emulate it in Vim? I know I can use <code>dwwP</code>, but it doesn’t work well with punctuation.</p> <p><em>Update:</em> No, <code>dwwP</code> is <em>really</em> not a solution. Imagine:</p> <pre><code>SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) ) // with cursor here ^ </code></pre> <p>Emacs’ M-t would have exchanged <code>b</code> and <code>c</code>, resulting in <code>(a)(c)(b)</code>.</p> <p>What works is <code>/\w yiwNviwpnviwgp</code>. But it spoils <code>""</code> and <code>"/</code>. Is there a cleaner solution?</p> <p><em>Update²:</em></p> <h1>Solved</h1> <pre><code>:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,&lt;CR&gt;kgJ:nohl&lt;CR&gt; </code></pre> <p>Imperfect, but works.</p> <p>Thanks Camflan for bringing the <code>%#</code> item to my attention. Of course, it’s all on the <a href="http://vim.wikia.com/wiki/VimTip47" rel="noreferrer">wiki</a>, but I didn’t realize it could solve the problem of <em>exact</em> (Emacs got it completely right) duplication of the <code>transpose-words</code> feature.</p>
[ { "answer_id": 141447, "author": "Sam Martin", "author_id": 19088, "author_profile": "https://Stackoverflow.com/users/19088", "pm_score": 3, "selected": false, "text": "<p>Depending on the situation, you can use the W or B commands, as in dWwP. The \"capital\" versions skip to the next/previous space, including punctuation. The f and t commands can help, as well, for specifying the end of the deleted range.</p>\n\n<p>There's also a discussion on the <a href=\"http://vim.wikia.com/wiki/VimTip47\" rel=\"nofollow noreferrer\">Vim Tips Wiki</a> about various swapping techniques.</p>\n" }, { "answer_id": 141485, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>In the middle of a line, go to the first letter of the first word, then do</p>\n\n<pre><code>dw wP\n</code></pre>\n\n<p>At the end of a line (ie the last two words of the line), go to the space between the words and do</p>\n\n<pre><code>2dw bhP\n</code></pre>\n\n<p><em>From the handy <a href=\"http://danzig.jct.ac.il/unix_class/emacs-vi-Commands.html\" rel=\"nofollow noreferrer\">Equivalence of VIM &amp; Emacs commands</a></em></p>\n\n<hr>\n\n<p>You could add shortcut keys for those by adding something like the following to your vimrc file:</p>\n\n<pre><code>map L dwwP\nmap M 2dwbhP \n</code></pre>\n\n<p>In that case, SHIFT-L (in command-mode) would switch words in the middle of the line and SHIFT-M would do it at the end.</p>\n\n<p><em>NB: This works best with space-separated words and doesn't handle the OP's specific case very well.</em></p>\n" }, { "answer_id": 141551, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 0, "selected": false, "text": "<p>You can use dwwP or dWwP as Mark and CapnNefarious have said, but I have a few notes of my own: </p>\n\n<ul>\n<li>If the cursor is on the first letter of the second word, as in the example you gave, you can use dwbP (or dWbP to handle punctuation);</li>\n<li>If the cursor is in the middle of the word, you can use dawbP/daWbP.</li>\n</ul>\n" }, { "answer_id": 141824, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 4, "selected": true, "text": "<p>These are from my .vimrc and work well for me.</p>\n\n<pre><code>\" swap two words\n:vnoremap &lt;C-X&gt; &lt;Esc&gt;`.``gvP``P\n\" Swap word with next word\nnmap &lt;silent&gt; gw \"_yiw:s/\\(\\%#\\w\\+\\)\\(\\_W\\+\\)\\(\\w\\+\\)/\\3\\2\\1/&lt;cr&gt;&lt;c-o&gt;&lt;c-l&gt; *N*\n</code></pre>\n" }, { "answer_id": 12512287, "author": "Ji Han", "author_id": 1685865, "author_profile": "https://Stackoverflow.com/users/1685865", "pm_score": 2, "selected": false, "text": "<p>There's a tip on <a href=\"http://vim.wikia.com/wiki/VimTip10\" rel=\"nofollow\">http://vim.wikia.com/wiki/VimTip10</a>. But I choose to roll my own.\nMy snippet has two obvious advantages over the method mentioned in the tip: 1) it works when the cursor isn't in a word. 2) it won't high-light the entire screen.</p>\n\n<p>It works almost like emacs 'transpose-words', except that when transposition is impossible, it does nothing. (emacs 'transpose-words' would blink and change cursor position to the beginning of current word.)</p>\n\n<pre><code>\"transpose words (like emacs `transpose-words')\nfunction! TransposeWords()\n if search('\\w\\+\\%#\\w*\\W\\+\\w\\+')\n elseif search('\\w\\+\\W\\+\\%#\\W*\\w\\+')\n endif\n let l:pos = getpos('.')\n exec 'silent! :s/\\(\\%#\\w\\+\\)\\(\\W\\+\\)\\(\\w\\+\\)/\\3\\2\\1/'\n call setpos('.', l:pos)\n let l:_ = search('\\(\\%#\\w\\+\\W\\+\\)\\@&lt;=\\w\\+')\n normal el\nendfunction\n\nnmap &lt;silent&gt; &lt;M-right&gt; :call TransposeWords()&lt;CR&gt;\nimap &lt;silent&gt; &lt;M-right&gt; &lt;C-O&gt;:call TransposeWords()&lt;CR&gt;\n</code></pre>\n" }, { "answer_id": 56773865, "author": "Marius Gedminas", "author_id": 110151, "author_profile": "https://Stackoverflow.com/users/110151", "pm_score": 0, "selected": false, "text": "<p>There's a <a href=\"https://www.vim.org/scripts/script.php?script_id=3656\" rel=\"nofollow noreferrer\">transpose-words script</a> on vim.org that works beautifully.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21055/" ]
Emacs has a useful `transpose-words` command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation. For example, ‘`stack |overflow`’ + M-t = ‘`overflow stack|`’ (‘`|`’ is the cursor position). `<a>|<p>` becomes `<p><a|>`. Is it possible to emulate it in Vim? I know I can use `dwwP`, but it doesn’t work well with punctuation. *Update:* No, `dwwP` is *really* not a solution. Imagine: ``` SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) ) // with cursor here ^ ``` Emacs’ M-t would have exchanged `b` and `c`, resulting in `(a)(c)(b)`. What works is `/\w yiwNviwpnviwgp`. But it spoils `""` and `"/`. Is there a cleaner solution? *Update²:* Solved ====== ``` :nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR> ``` Imperfect, but works. Thanks Camflan for bringing the `%#` item to my attention. Of course, it’s all on the [wiki](http://vim.wikia.com/wiki/VimTip47), but I didn’t realize it could solve the problem of *exact* (Emacs got it completely right) duplication of the `transpose-words` feature.
These are from my .vimrc and work well for me. ``` " swap two words :vnoremap <C-X> <Esc>`.``gvP``P " Swap word with next word nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N* ```
141,388
<p>Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:</p> <pre><code>&lt;ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}" dataProvider="{_data.staticData.dead_reason}" labelField="@label" width="300"/&gt; </code></pre> <p>The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?</p>
[ { "answer_id": 141408, "author": "bill d", "author_id": 1798, "author_profile": "https://Stackoverflow.com/users/1798", "pm_score": 2, "selected": false, "text": "<p>Try using an &lt;mx:Repeater&gt; Something like:</p>\n\n<pre><code>&lt;mx:Repeater dataProvider=\"{_data.staticData.dead_reason}\"&gt;\n &lt;mx:RadioButton groupName=\"reasons\" ...&gt;\n&lt;/mx:Repeater&gt;\n</code></pre>\n" }, { "answer_id": 806732, "author": "Kevin", "author_id": 98514, "author_profile": "https://Stackoverflow.com/users/98514", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;mx:RadioButtonGroup id=\"RDO_Group\"/&gt;\n&lt;mx:Repeater id=\"myRepeater\" dataProvider=\"{_data.staticData.dead_reason}\"&gt;\n&lt;mx:RadioButton id=\"rdo\" label=\"{myRepeater.currentItem}\" value=\"{myRepeater.currentItem}\" groupName=\"RDO_Group\"/&gt;\n&lt;/mx:Repeater&gt;\n</code></pre>\n\n<p> is the best way.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine: ``` <ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}" dataProvider="{_data.staticData.dead_reason}" labelField="@label" width="300"/> ``` The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?
Try using an <mx:Repeater> Something like: ``` <mx:Repeater dataProvider="{_data.staticData.dead_reason}"> <mx:RadioButton groupName="reasons" ...> </mx:Repeater> ```
141,422
<p>Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n'</p> <pre><code>Ax^(n-1) + Bx^(n-2) + ... + Z </code></pre> <p>I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system.</p> <p>If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction...</p> <p>Update: Coordinate systems are linearly related. Would have been useful info eh?</p>
[ { "answer_id": 141493, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 0, "selected": false, "text": "<p>You have the equation:</p>\n\n<pre><code>y = Ax^(n-1) + Bx^(n-2) + ... + Z\n</code></pre>\n\n<p>In xy space, and you want it in some x'y' space. What you need is transformation functions f(x) = x' and g(y) = y' (or h(x') = x and j(y') = y). In the first case you need to solve for x and solve for y. Once you have x and y, you can substituted those results into your original equation and solve for y'.</p>\n\n<p>Whether or not this is trivial depends on the complexity of the functions used to transform from one space to another. For example, equations such as:</p>\n\n<pre><code>5x = x' and 10y = y'\n</code></pre>\n\n<p>are extremely easy to solve for the result</p>\n\n<pre><code>y' = 2Ax'^(n-1) + 2Bx'^(n-2) + ... + 10Z\n</code></pre>\n" }, { "answer_id": 141509, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 0, "selected": false, "text": "<p>If the input spaces are linearly related, then yes, a matrix should be able to transform one set of coefficients to another. For example, if you had your polynomial in your \"original\" x-space:</p>\n\n<p>ax^3 + bx^2 + cx + d</p>\n\n<p>and you wanted to transform into a different w-space where w = px+q</p>\n\n<p>then you want to find a', b', c', and d' such that</p>\n\n<p>ax^3 + bx^2 + cx + d = a'w^3 + b'w^2 + c'w + d'</p>\n\n<p>and with some algebra, </p>\n\n<p>a'w^3 + b'w^2 + c'w + d' = a'p^3x^3 + 3a'p^2qx^2 + 3a'pq^2x + a'q^3 + b'p^2x^2 + 2b'pqx + b'q^2 + c'px + c'q + d'</p>\n\n<p>therefore</p>\n\n<p>a = a'p^3</p>\n\n<p>b = 3a'p^2q + b'p^2</p>\n\n<p>c = 3a'pq^2 + 2b'pq + c'p</p>\n\n<p>d = a'q^3 + b'q^2 + c'q + d'</p>\n\n<p>which can be rewritten as a matrix problem and solved.</p>\n" }, { "answer_id": 142342, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 2, "selected": false, "text": "<p>If I understand your question correctly, there is no guarantee that the function will remain polynomial after you change coordinates. For example, let y=x^2, and the new coordinate system x'=y, y'=x. Now the equation becomes y' = sqrt(x'), which isn't polynomial.</p>\n" }, { "answer_id": 142436, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 4, "selected": true, "text": "<p>The problem statement is slightly unclear, so first I will clarify my own interpretation of it:</p>\n\n<p>You have a polynomial function</p>\n\n<p><strong>f(x) = C<sub>n</sub>x<sup>n</sup> + C<sub>n-1</sub>x<sup>n-1</sup> + ... + C<sub>0</sub></strong></p>\n\n<p>[I changed A, B, ... Z into C<sub>n</sub>, C<sub>n-1</sub>, ..., C<sub>0</sub> to more easily work with linear algebra below.]</p>\n\n<p>Then you also have a transformation such as: &nbsp; <strong>z = ax + b</strong> &nbsp; that you want to use to find coefficients for the <em>same</em> polynomial, but in terms of <em>z</em>:</p>\n\n<p><strong>f(z) = D<sub>n</sub>z<sup>n</sup> + D<sub>n-1</sub>z<sup>n-1</sup> + ... + D<sub>0</sub></strong></p>\n\n<p>This can be done pretty easily with some linear algebra. In particular, you can define an (n+1)&times;(n+1) matrix <em>T</em> which allows us to do the matrix multiplication</p>\n\n<p>&nbsp; <strong><em>d</em> = <em>T</em> * <em>c</em></strong> ,</p>\n\n<p>where <em>d</em> is a column vector with top entry <em>D<sub>0</sub></em>, to last entry <em>D<sub>n</sub></em>, column vector <em>c</em> is similar for the <em>C<sub>i</sub></em> coefficients, and matrix <em>T</em> has (i,j)-th [i<sup>th</sup> row, j<sup>th</sup> column] entry <em>t<sub>ij</sub></em> given by</p>\n\n<p>&nbsp; <strong><em>t<sub>ij</sub></em> = (<em>j</em> choose <em>i</em>) <em>a<sup>i</sup></em> <em>b<sup>j-i</sup></em></strong>.</p>\n\n<p>Where (<em>j</em> choose <em>i</em>) is the binomial coefficient, and = 0 when <em>i</em> > <em>j</em>. Also, unlike standard matrices, I'm thinking that i,j each range from 0 to n (usually you start at 1).</p>\n\n<p>This is basically a nice way to write out the expansion and re-compression of the polynomial when you plug in z=ax+b by hand and use the <a href=\"http://en.wikipedia.org/wiki/Binomial_theorem\" rel=\"noreferrer\">binomial theorem</a>.</p>\n" }, { "answer_id": 143518, "author": "Camille", "author_id": 16990, "author_profile": "https://Stackoverflow.com/users/16990", "pm_score": 2, "selected": false, "text": "<p>Tyler's answer is the right answer if you have to compute this change of variable z = ax+b many times (I mean for many different polynomials). On the other hand, if you have to do it just once, it is much faster to combine the computation of the coefficients of the matrix with the final evaluation. The best way to do it is to symbolically evaluate your polynomial at point (ax+b) by Hörner's method:</p>\n\n<ul>\n<li>you store the polynomial coefficients in a vector V (at the beginning, all coefficients are zero), and for i = n to 0, you multiply it by (ax+b) and add C<sub>i</sub>.</li>\n<li>adding C<sub>i</sub> means adding it to the constant term</li>\n<li>multiplying by (ax+b) means multiplying all coefficients by b into a vector K<sub>1</sub>, multiplying all coefficients by a and shifting them away from the constant term into a vector K<sub>2</sub>, and putting K<sub>1</sub>+K<sub>2</sub> back into V.</li>\n</ul>\n\n<p>This will be easier to program, and faster to compute. </p>\n\n<p>Note that changing y into w = cy+d is really easy. Finally, as mattiast points out, a general change of coordinates will not give you a polynomial.</p>\n\n<p><strong>Technical note</strong>: if you still want to compute matrix T (as defined by Tyler), you should compute it by using a weighted version of Pascal's rule (this is what the Hörner computation does implicitely):</p>\n\n<p>t<sub>i,j</sub> = b t<sub>i,j-1</sub> + a t<sub>i-1,j-1</sub></p>\n\n<p>This way, you compute it simply, column after column, from left to right.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287/" ]
Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n' ``` Ax^(n-1) + Bx^(n-2) + ... + Z ``` I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system. If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction... Update: Coordinate systems are linearly related. Would have been useful info eh?
The problem statement is slightly unclear, so first I will clarify my own interpretation of it: You have a polynomial function **f(x) = Cnxn + Cn-1xn-1 + ... + C0** [I changed A, B, ... Z into Cn, Cn-1, ..., C0 to more easily work with linear algebra below.] Then you also have a transformation such as:   **z = ax + b**   that you want to use to find coefficients for the *same* polynomial, but in terms of *z*: **f(z) = Dnzn + Dn-1zn-1 + ... + D0** This can be done pretty easily with some linear algebra. In particular, you can define an (n+1)×(n+1) matrix *T* which allows us to do the matrix multiplication   ***d* = *T* \* *c*** , where *d* is a column vector with top entry *D0*, to last entry *Dn*, column vector *c* is similar for the *Ci* coefficients, and matrix *T* has (i,j)-th [ith row, jth column] entry *tij* given by   ***tij* = (*j* choose *i*) *ai* *bj-i***. Where (*j* choose *i*) is the binomial coefficient, and = 0 when *i* > *j*. Also, unlike standard matrices, I'm thinking that i,j each range from 0 to n (usually you start at 1). This is basically a nice way to write out the expansion and re-compression of the polynomial when you plug in z=ax+b by hand and use the [binomial theorem](http://en.wikipedia.org/wiki/Binomial_theorem).
141,432
<p>I have created a brand new project in XCode and have the following in my AppDelegate.py file:</p> <pre><code>from Foundation import * from AppKit import * class MyApplicationAppDelegate(NSObject): def applicationDidFinishLaunching_(self, sender): NSLog("Application did finish launching.") statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setTitle_(u"12%") statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) </code></pre> <p>However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.</p>
[ { "answer_id": 142162, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 4, "selected": true, "text": "<p>I had to do this to make it work:</p>\n\n<ol>\n<li><p>Open MainMenu.xib. Make sure the class of the app delegate is <code>MyApplicationAppDelegate</code>. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.</p></li>\n<li><p>Add <code>statusItem.retain()</code> because it gets autoreleased right away.</p></li>\n</ol>\n" }, { "answer_id": 4379633, "author": "brandon", "author_id": 445251, "author_profile": "https://Stackoverflow.com/users/445251", "pm_score": 3, "selected": false, "text": "<p>The above usage of .retain() is required because the statusItem is being destroyed upon return from the applicationDidFinishLaunching() method. Bind that variable as a field in instances of MyApplicationAppDelegate using self.statusItem instead.</p>\n\n<p>Here is a modified example that does not require a .xib / etc...</p>\n\n<pre><code>from Foundation import *\nfrom AppKit import *\nfrom PyObjCTools import AppHelper\n\nstart_time = NSDate.date()\n\n\nclass MyApplicationAppDelegate(NSObject):\n\n state = 'idle'\n\n def applicationDidFinishLaunching_(self, sender):\n NSLog(\"Application did finish launching.\")\n\n self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)\n self.statusItem.setTitle_(u\"Hello World\")\n self.statusItem.setHighlightMode_(TRUE)\n self.statusItem.setEnabled_(TRUE)\n\n # Get the timer going\n self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)\n NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)\n self.timer.fire()\n\n def sync_(self, notification):\n print \"sync\"\n\n def tick_(self, notification):\n print self.state\n\n\nif __name__ == \"__main__\":\n app = NSApplication.sharedApplication()\n delegate = MyApplicationAppDelegate.alloc().init()\n app.setDelegate_(delegate)\n AppHelper.runEventLoop()\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
I have created a brand new project in XCode and have the following in my AppDelegate.py file: ``` from Foundation import * from AppKit import * class MyApplicationAppDelegate(NSObject): def applicationDidFinishLaunching_(self, sender): NSLog("Application did finish launching.") statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setTitle_(u"12%") statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) ``` However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.
I had to do this to make it work: 1. Open MainMenu.xib. Make sure the class of the app delegate is `MyApplicationAppDelegate`. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place. 2. Add `statusItem.retain()` because it gets autoreleased right away.
141,441
<p>In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?</p> <pre><code>try{ if(myInfo.person.name == newInfo.person.name &amp;&amp; myInfo.person.address.street == newInfo.person.address.street &amp;&amp; myInfo.person.address.zip == newInfo.person.address.zip) { this.setAddress(newInfo); } } catch(e) {} // ignore missing args </code></pre>
[ { "answer_id": 141474, "author": "pdavis", "author_id": 7819, "author_profile": "https://Stackoverflow.com/users/7819", "pm_score": -1, "selected": false, "text": "<p>For the example given I would say it was bad practice. There are instances however where it may be more <strong>efficient</strong> to simply trap for an <strong>expected</strong> error. Validating the format of a string before <a href=\"https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#104932\">casting it as a GUID</a> would be a good example.</p>\n" }, { "answer_id": 141476, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 1, "selected": false, "text": "<p>I would think that if you're going to catch the exception then do something with it. Otherwise, let it bubble up so a higher level can handle it in some way (even if it's just the browser reporting the error to you).</p>\n" }, { "answer_id": 141478, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 2, "selected": false, "text": "<p>Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired.</p>\n" }, { "answer_id": 141481, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>If you expect a particular condition, your code will be easier to maintain if you explicitly test for it. I would write the above as something like</p>\n\n<pre><code>if( myInfo &amp;&amp; newInfo \n &amp;&amp; myInfo.person &amp;&amp; newInfo.person\n &amp;&amp; myInfo.person.address &amp;&amp; newInfo.person.address\n &amp;&amp; ( myInfo.person.name == newInfo.person.name\n &amp;&amp; myInfo.person.address.street == newInfo.person.address.street\n &amp;&amp; myInfo.person.address.zip == newInfo.person.address.zip\n )\n) \n{\n this.setAddress(newInfo);\n} \n</code></pre>\n\n<p>This makes the effect much clearer - for instance, suppose newInfo is all filled out, but parts of myInfo are missing? Perhaps you actually want setAddress() to be called in that case? If so, you'll need to change that logic!</p>\n" }, { "answer_id": 141530, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>On a related note, in IE, even though the specs say you can, you can not use a try/finally combination. In order for your \"finally\" to execute, you must have a catch block defined, even if it is empty.</p>\n\n<pre><code>//this will [NOT] do the reset in Internet Explorer\ntry{\n doErrorProneAction();\n} finally {\n //clean up\n this.reset();\n}\n\n//this [WILL] do the reset in Internet Explorer\ntry{\n doErrorProneAction();\n} catch(ex){\n //do nothing\n} finally {\n //clean up\n this.reset();\n}\n</code></pre>\n" }, { "answer_id": 142186, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 0, "selected": false, "text": "<p>You could always write a helper function to do the checking for you:</p>\n\n<pre><code>function pathEquals(obj1, obj2, path)\n{\n var properties = path.split(\".\");\n for (var i = 0, l = properties.length; i &lt; l; i++)\n {\n var property = properties[i];\n if (obj1 === null || typeof obj1[property] == \"undefined\" ||\n obj2 === null || typeof obj2[property] == \"undefined\")\n {\n return false;\n }\n\n obj1 = obj1[property];\n obj2 = obj2[property];\n }\n\n return (obj1 === obj2);\n}\n\nif (pathEquals(myInfo, newInfo, \"person.name\") &amp;&amp;\n pathEquals(myInfo, newInfo, \"person.address.street\") &amp;&amp;\n pathEquals(myInfo, newInfo, \"person.address.zip\"))\n{\n this.setAddress(newInfo);\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22816/" ]
In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null? ``` try{ if(myInfo.person.name == newInfo.person.name && myInfo.person.address.street == newInfo.person.address.street && myInfo.person.address.zip == newInfo.person.address.zip) { this.setAddress(newInfo); } } catch(e) {} // ignore missing args ```
Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired.
141,449
<p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
[ { "answer_id": 141451, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 8, "selected": true, "text": "<p>For Python 2.x, use the <a href=\"https://docs.python.org/2/library/stringio.html\" rel=\"noreferrer\">StringIO</a> module. For example:</p>\n\n<pre><code>&gt;&gt;&gt; from cStringIO import StringIO\n&gt;&gt;&gt; f = StringIO('foo')\n&gt;&gt;&gt; f.read()\n'foo'\n</code></pre>\n\n<p>I use cStringIO (which is faster), but note that it doesn't <a href=\"http://docs.python.org/lib/module-cStringIO.html\" rel=\"noreferrer\">accept Unicode strings that cannot be encoded as plain ASCII strings</a>. (You can switch to StringIO by changing \"from cStringIO\" to \"from StringIO\".)</p>\n\n<p>For Python 3.x, use the <a href=\"https://docs.python.org/3/library/io.html#text-i-o\" rel=\"noreferrer\"><code>io</code></a> module.</p>\n\n<pre><code>f = io.StringIO('foo')\n</code></pre>\n" }, { "answer_id": 142251, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "<p>In Python 3.0:</p>\n<pre><code>import io\n\nwith io.StringIO() as f:\n f.write('abcdef')\n print('gh', file=f)\n f.seek(0)\n print(f.read())\n</code></pre>\n<p>The output is:</p>\n<pre><code>'abcdefgh'\n</code></pre>\n" }, { "answer_id": 49011746, "author": "guettli", "author_id": 633961, "author_profile": "https://Stackoverflow.com/users/633961", "pm_score": 4, "selected": false, "text": "<p>This works for Python2.7 and Python3.x:</p>\n\n<pre><code>io.StringIO(u'foo')\n</code></pre>\n" }, { "answer_id": 60083264, "author": "lensonp", "author_id": 5818920, "author_profile": "https://Stackoverflow.com/users/5818920", "pm_score": 3, "selected": false, "text": "<p>If your file-like object is expected to contain bytes, the string should first be encoded as bytes, and then a <a href=\"https://docs.python.org/3/library/io.html#text-i-o\" rel=\"noreferrer\">BytesIO</a> object can be used instead. In Python 3:</p>\n\n<pre><code>from io import BytesIO\n\nstring_repr_of_file = 'header\\n byline\\n body\\n body\\n end'\nfunction_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
How do I create a file-like object (same duck type as File) with the contents of a string?
For Python 2.x, use the [StringIO](https://docs.python.org/2/library/stringio.html) module. For example: ``` >>> from cStringIO import StringIO >>> f = StringIO('foo') >>> f.read() 'foo' ``` I use cStringIO (which is faster), but note that it doesn't [accept Unicode strings that cannot be encoded as plain ASCII strings](http://docs.python.org/lib/module-cStringIO.html). (You can switch to StringIO by changing "from cStringIO" to "from StringIO".) For Python 3.x, use the [`io`](https://docs.python.org/3/library/io.html#text-i-o) module. ``` f = io.StringIO('foo') ```
141,450
<p>I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:</p> <ul> <li>Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.</li> <li>Change events, but these only are triggered when the select box's value changes.</li> </ul> <p>Ideas?</p>
[ { "answer_id": 141535, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>I don't think there's direct support. You could also sit on the onblur of the select -- it gets called when the select loses focus.</p>\n\n<p>Depending on how important it is, you could try implementing your own control or starting from one like a drop-down menu control which is similar. Usually, unless it's critical to your application, it's not worth doing this. If you decide to go this route, here's a discussion of someone trying to do it using dojo as a basis:</p>\n\n<p><a href=\"http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select\" rel=\"nofollow noreferrer\">http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select</a></p>\n" }, { "answer_id": 141541, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<p>Keep track of the state using a JavaScript varialbe. We'll call it \"openX\".</p>\n\n<p>onfocus=\"openX=true\" onblur=\"openX=false\" onchange=\"openX=false\"</p>\n" }, { "answer_id": 142285, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": -1, "selected": false, "text": "<p>In jQuery, to test if something is visible:</p>\n\n<pre><code>$('something').css('display')\n</code></pre>\n\n<p>This will return something like 'block', 'inline', or 'none' (if element is not displayed). This is simply a representation of the CSS 'display' attribute.</p>\n" }, { "answer_id": 142490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This rudimentary example demonstrates how to do it with setInterval. It checks once every second for the display state of your select menu, and then hides or shows a piece of content. It works according to the description of your problem, and no matter what hides the select menu, it will display that piece of content accordingly. In other words, the toggleDisplay() was setup just to demonstrate that.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"&gt;\n&lt;head&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n\nvar STECHZ = {\n init : function() {\n STECHZ.setDisplayedInterval();\n },\n setDisplayedInterval : function() {\n STECHZ.isDisplayedInterval = window.setInterval(function(){\n if ( document.getElementById( \"mySelectMenu\" ).style.display == \"none\" ) {\n document.getElementById( \"myObjectToShow\" ).style.display = \"block\";\n } else {\n document.getElementById( \"myObjectToShow\" ).style.display = \"none\";\n }\n }, 1000);\n },\n isDisplayedInterval : null,\n toggleDisplay : function() {\n var mySelectMenu = document.getElementById( \"mySelectMenu\" );\n if ( mySelectMenu.style.display == \"none\" ) {\n mySelectMenu.style.display = \"block\";\n } else {\n mySelectMenu.style.display = \"none\";\n }\n }\n};\n\nwindow.onload = function(){\n\n STECHZ.init();\n\n}\n\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;p&gt;\n &lt;a href=\"#\" onclick=\"STECHZ.toggleDisplay();return false;\"&gt;Click to toggle display.&lt;/a&gt;\n &lt;/p&gt;\n &lt;select id=\"mySelectMenu\"&gt;\n &lt;option&gt;Option 1&lt;/option&gt;\n &lt;option&gt;Option 2&lt;/option&gt;\n &lt;option&gt;Option 3&lt;/option&gt;\n &lt;/select&gt;\n &lt;div id=\"myObjectToShow\" style=\"display: none;\"&gt;Only show when mySelectMenu is not showing.&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 1070950, "author": "Sampson", "author_id": 54680, "author_profile": "https://Stackoverflow.com/users/54680", "pm_score": 2, "selected": false, "text": "<p>Conditional-content, which is what you're asking about, isn't that difficult. The in the following example, I'll use <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> to accomplish our goal:</p>\n\n<pre><code>&lt;select id=\"theSelectId\"&gt;\n &lt;option value=\"dogs\"&gt;Dogs&lt;/option&gt;\n &lt;option value=\"birds\"&gt;Birds&lt;/option&gt;\n &lt;option value=\"cats\"&gt;Cats&lt;/option&gt;\n &lt;option value=\"horses\"&gt;Horses&lt;/option&gt;\n&lt;/select&gt;\n\n&lt;div id=\"myDiv\" style=\"width:300px;height:100px;background:#cc0000\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>We'll tie a couple events to show/hide #myDiv based upon the selected value of #theSelectId</p>\n\n<pre><code>$(\"#theSelectId\").change(function(){\n if ($(this).val() != \"dogs\")\n $(\"#myDiv\").fadeOut();\n else\n $(\"#myDiv\").fadeIn();\n});\n</code></pre>\n" }, { "answer_id": 1112669, "author": "Your Friend Ken", "author_id": 86295, "author_profile": "https://Stackoverflow.com/users/86295", "pm_score": 2, "selected": false, "text": "<p>here is how I would preferred to do it.\nfocus and blur is where it is at.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;SandBox&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;select id=\"ddlBox\"&gt;\n &lt;option&gt;Option 1&lt;/option&gt;\n &lt;option&gt;Option 2&lt;/option&gt;\n &lt;option&gt;Option 3&lt;/option&gt;\n &lt;/select&gt;\n &lt;div id=\"divMsg\"&gt;some text or whatever goes here.&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n&lt;script type=\"text/javascript\"&gt;\n window.onload = function() {\n var ddlBox = document.getElementById(\"ddlBox\");\n var divMsg = document.getElementById(\"divMsg\");\n if (ddlBox &amp;&amp; divMsg) {\n ddlBox.onfocus = function() {\n divMsg.style.display = \"none\";\n }\n ddlBox.onblur = function() {\n divMsg.style.display = \"\";\n }\n divMsg.style.display = \"\";\n }\n }\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10290/" ]
I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried: * Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser. * Change events, but these only are triggered when the select box's value changes. Ideas?
Conditional-content, which is what you're asking about, isn't that difficult. The in the following example, I'll use [jQuery](http://www.jquery.com) to accomplish our goal: ``` <select id="theSelectId"> <option value="dogs">Dogs</option> <option value="birds">Birds</option> <option value="cats">Cats</option> <option value="horses">Horses</option> </select> <div id="myDiv" style="width:300px;height:100px;background:#cc0000"></div> ``` We'll tie a couple events to show/hide #myDiv based upon the selected value of #theSelectId ``` $("#theSelectId").change(function(){ if ($(this).val() != "dogs") $("#myDiv").fadeOut(); else $("#myDiv").fadeIn(); }); ```
141,467
<p>I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?</p> <p>Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.</p>
[ { "answer_id": 141495, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 0, "selected": false, "text": "<pre><code>static class EnumerableExtensions\n{\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this IEnumerable&lt;IEnumerable&lt;T&gt;&gt; sequence)\n {\n foreach(var child in sequence)\n foreach(var item in child)\n yield return item;\n }\n}\n</code></pre>\n\n<p>Maybe like this? Or do you mean that it could potentially be infintly deep?</p>\n" }, { "answer_id": 141524, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p>Basicly, you need to have a master IENumerable that is outside of your recursive function, then in your recursive function (Psuedo-code)</p>\n\n<pre><code>private void flattenList(IEnumerable&lt;T&gt; list)\n{\n foreach (T item in list)\n {\n masterList.Add(item);\n\n if (item.Count &gt; 0)\n {\n this.flattenList(item);\n }\n }\n}\n</code></pre>\n\n<p>Though I'm really not sure what you mean by IEnumerable nested in an IEnumerable...whats within that? How many levels of nesting? Whats the final type? obviously my code isn't correct, but I hope it gets you thinking.</p>\n" }, { "answer_id": 141528, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>Hmm... I'm not sure <em>exactly</em> what you want here, but here's a \"one level\" option:</p>\n\n<pre><code>public static IEnumerable&lt;TElement&gt; Flatten&lt;TElement,TSequence&gt; (this IEnumerable&lt;TSequence&gt; sequences)\n where TSequence : IEnumerable&lt;TElement&gt; \n{\n foreach (TSequence sequence in sequences)\n {\n foreach(TElement element in sequence)\n {\n yield return element;\n }\n }\n}\n</code></pre>\n\n<p>If that's not what you want, could you provide the signature of what you do want? If you don't need a generic form, and you just want to do the kind of thing that LINQ to XML constructors do, that's reasonably simple - although the recursive use of iterator blocks is relatively inefficient. Something like:</p>\n\n<pre><code>static IEnumerable Flatten(params object[] objects)\n{\n // Can't easily get varargs behaviour with IEnumerable\n return Flatten((IEnumerable) objects);\n}\n\nstatic IEnumerable Flatten(IEnumerable enumerable)\n{\n foreach (object element in enumerable)\n {\n IEnumerable candidate = element as IEnumerable;\n if (candidate != null)\n {\n foreach (object nested in candidate)\n {\n yield return nested;\n }\n }\n else\n {\n yield return element;\n }\n }\n}\n</code></pre>\n\n<p>Note that that will treat a string as a sequence of chars, however - you may want to special-case strings to be individual elements instead of flattening them, depending on your use case.</p>\n\n<p>Does that help?</p>\n" }, { "answer_id": 141539, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p>Isn't that what [SelectMany][1] is for?</p>\n\n<pre><code>enum1.SelectMany(\n a =&gt; a.SelectMany(\n b =&gt; b.SelectMany(\n c =&gt; c.Select(\n d =&gt; d.Name\n )\n )\n )\n);\n</code></pre>\n" }, { "answer_id": 229442, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Here's an extension that might help. It will traverse all nodes in your hierarchy of objects and pick out the ones that match a criteria. It assumes that each object in your hierarchy <strong>has a collection property</strong> that holds its child objects.</p>\n\n<h2>Here's the extension:</h2>\n\n<pre><code>/// Traverses an object hierarchy and return a flattened list of elements\n/// based on a predicate.\n/// \n/// TSource: The type of object in your collection.&lt;/typeparam&gt;\n/// source: The collection of your topmost TSource objects.&lt;/param&gt;\n/// selectorFunction: A predicate for choosing the objects you want.\n/// getChildrenFunction: A function that fetches the child collection from an object.\n/// returns: A flattened list of objects which meet the criteria in selectorFunction.\npublic static IEnumerable&lt;TSource&gt; Map&lt;TSource&gt;(\n this IEnumerable&lt;TSource&gt; source,\n Func&lt;TSource, bool&gt; selectorFunction,\n Func&lt;TSource, IEnumerable&lt;TSource&gt;&gt; getChildrenFunction)\n{\n // Add what we have to the stack\n var flattenedList = source.Where(selectorFunction);\n\n // Go through the input enumerable looking for children,\n // and add those if we have them\n foreach (TSource element in source)\n {\n flattenedList = flattenedList.Concat(\n getChildrenFunction(element).Map(selectorFunction,\n getChildrenFunction)\n );\n }\n return flattenedList;\n}\n</code></pre>\n\n<h2>Examples (Unit Tests):</h2>\n\n<p>First we need an object and a nested object hierarchy.</p>\n\n<p>A simple node class</p>\n\n<pre><code>class Node\n{\n public int NodeId { get; set; }\n public int LevelId { get; set; }\n public IEnumerable&lt;Node&gt; Children { get; set; }\n\n public override string ToString()\n {\n return String.Format(\"Node {0}, Level {1}\", this.NodeId, this.LevelId);\n }\n}\n</code></pre>\n\n<p>And a method to get a 3-level deep hierarchy of nodes</p>\n\n<pre><code>private IEnumerable&lt;Node&gt; GetNodes()\n{\n // Create a 3-level deep hierarchy of nodes\n Node[] nodes = new Node[]\n {\n new Node \n { \n NodeId = 1, \n LevelId = 1, \n Children = new Node[]\n {\n new Node { NodeId = 2, LevelId = 2, Children = new Node[] {} },\n new Node\n {\n NodeId = 3,\n LevelId = 2,\n Children = new Node[]\n {\n new Node { NodeId = 4, LevelId = 3, Children = new Node[] {} },\n new Node { NodeId = 5, LevelId = 3, Children = new Node[] {} }\n }\n }\n }\n },\n new Node { NodeId = 6, LevelId = 1, Children = new Node[] {} }\n };\n return nodes;\n}\n</code></pre>\n\n<p>First Test: flatten the hierarchy, no filtering</p>\n\n<pre><code>[Test]\npublic void Flatten_Nested_Heirachy()\n{\n IEnumerable&lt;Node&gt; nodes = GetNodes();\n var flattenedNodes = nodes.Map(\n p =&gt; true, \n (Node n) =&gt; { return n.Children; }\n );\n foreach (Node flatNode in flattenedNodes)\n {\n Console.WriteLine(flatNode.ToString());\n }\n\n // Make sure we only end up with 6 nodes\n Assert.AreEqual(6, flattenedNodes.Count());\n}\n</code></pre>\n\n<p>This will show:</p>\n\n<pre><code>Node 1, Level 1\nNode 6, Level 1\nNode 2, Level 2\nNode 3, Level 2\nNode 4, Level 3\nNode 5, Level 3\n</code></pre>\n\n<p>Second Test: Get a list of nodes that have an even-numbered NodeId</p>\n\n<pre><code>[Test]\npublic void Only_Return_Nodes_With_Even_Numbered_Node_IDs()\n{\n IEnumerable&lt;Node&gt; nodes = GetNodes();\n var flattenedNodes = nodes.Map(\n p =&gt; (p.NodeId % 2) == 0, \n (Node n) =&gt; { return n.Children; }\n );\n foreach (Node flatNode in flattenedNodes)\n {\n Console.WriteLine(flatNode.ToString());\n }\n // Make sure we only end up with 3 nodes\n Assert.AreEqual(3, flattenedNodes.Count());\n}\n</code></pre>\n\n<p>This will show:</p>\n\n<pre><code>Node 6, Level 1\nNode 2, Level 2\nNode 4, Level 3\n</code></pre>\n" }, { "answer_id": 229515, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx\" rel=\"nofollow noreferrer\"><code>SelectMany</code></a> extension method does this already.</p>\n\n<blockquote>\n <p>Projects each element of a sequence to\n an IEnumerable&lt;(Of &lt;(T>)>) and\n flattens the resulting sequences into\n one sequence.</p>\n</blockquote>\n" }, { "answer_id": 310188, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "<p>Here is a modified <a href=\"https://stackoverflow.com/questions/141467/recursive-list-flattening#141528\">Jon Skeet's answer</a> to allow more than \"one level\":</p>\n\n<pre><code>static IEnumerable Flatten(IEnumerable enumerable)\n{\n foreach (object element in enumerable)\n {\n IEnumerable candidate = element as IEnumerable;\n if (candidate != null)\n {\n foreach (object nested in Flatten(candidate))\n {\n yield return nested;\n }\n }\n else\n {\n yield return element;\n }\n }\n}\n</code></pre>\n\n<p>disclaimer: I don't know C#.</p>\n\n<p>The same in Python:</p>\n\n<pre><code>#!/usr/bin/env python\n\ndef flatten(iterable):\n for item in iterable:\n if hasattr(item, '__iter__'):\n for nested in flatten(item):\n yield nested\n else:\n yield item\n\nif __name__ == '__main__':\n for item in flatten([1,[2, 3, [[4], 5]], 6, [[[7]]], [8]]):\n print(item, end=\" \")\n</code></pre>\n\n<p>It prints:</p>\n\n<pre><code>1 2 3 4 5 6 7 8 \n</code></pre>\n" }, { "answer_id": 3738191, "author": "Richard Collette", "author_id": 107683, "author_profile": "https://Stackoverflow.com/users/107683", "pm_score": 1, "selected": false, "text": "<p>Since yield is not available in VB and LINQ provides both deferred execution and a concise syntax, you can also use.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>&lt;Extension()&gt;\nPublic Function Flatten(Of T)(ByVal objects As Generic.IEnumerable(Of T), ByVal selector As Func(Of T, Generic.IEnumerable(Of T))) As Generic.IEnumerable(Of T)\n If(objects.Any()) Then\n Return objects.Union(objects.Select(selector).Where(e =&gt; e != null).SelectMany(e =&gt; e)).Flatten(selector))\n Else\n Return objects \n End If\nEnd Function\n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class Extensions{\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this IEnumerable&lt;T&gt; objects, Func&lt;T, IEnumerable&lt;T&gt;&gt; selector) where T:Component{\n if(objects.Any()){\n return objects.Union(objects.Select(selector).Where(e =&gt; e != null).SelectMany(e =&gt; e).Flatten(selector));\n }\n return objects;\n }\n}\n</code></pre>\n<p><em>edited</em> to include:</p>\n<ul>\n<li>empty enumerable per <a href=\"https://stackoverflow.com/a/30325216/107683\">https://stackoverflow.com/a/30325216/107683</a>,</li>\n<li>null enumerable per <a href=\"https://stackoverflow.com/a/39338919/107683\">https://stackoverflow.com/a/39338919/107683</a></li>\n<li>C# implementation.</li>\n</ul>\n" }, { "answer_id": 17237709, "author": "marchewek", "author_id": 968745, "author_profile": "https://Stackoverflow.com/users/968745", "pm_score": 4, "selected": false, "text": "<p>I thought I'd share a complete example with error handling and a single-logic apporoach.</p>\n\n<p>Recursive flattening is as simple as:</p>\n\n<p><strong>LINQ version</strong>\n</p>\n\n<pre><code>public static class IEnumerableExtensions\n{\n public static IEnumerable&lt;T&gt; SelectManyRecursive&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, IEnumerable&lt;T&gt;&gt; selector)\n {\n if (source == null) throw new ArgumentNullException(\"source\");\n if (selector == null) throw new ArgumentNullException(\"selector\");\n\n return !source.Any() ? source :\n source.Concat(\n source\n .SelectMany(i =&gt; selector(i).EmptyIfNull())\n .SelectManyRecursive(selector)\n );\n }\n\n public static IEnumerable&lt;T&gt; EmptyIfNull&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n {\n return source ?? Enumerable.Empty&lt;T&gt;();\n }\n}\n</code></pre>\n\n<p><strong>Non-LINQ version</strong>\n</p>\n\n<pre><code>public static class IEnumerableExtensions\n{\n public static IEnumerable&lt;T&gt; SelectManyRecursive&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, IEnumerable&lt;T&gt;&gt; selector)\n {\n if (source == null) throw new ArgumentNullException(\"source\");\n if (selector == null) throw new ArgumentNullException(\"selector\");\n\n foreach (T item in source)\n {\n yield return item;\n\n var children = selector(item);\n if (children == null)\n continue;\n\n foreach (T descendant in children.SelectManyRecursive(selector))\n {\n yield return descendant;\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>Design decisions</strong></p>\n\n<p>I decided to:</p>\n\n<ul>\n<li>disallow flattening of a null <code>IEnumerable</code>, this can be changed by removing exception throwing and:\n<ul>\n<li>adding <code>source = source.EmptyIfNull();</code> before <code>return</code> in the 1st version</li>\n<li>adding <code>if (source != null)</code> before <code>foreach</code> in the 2nd version</li>\n</ul></li>\n<li>allow returning of a null collection by the selector - this way I'm removing responsibility from the caller to assure the children list isn't empty, this can be changed by:\n<ul>\n<li>removing <code>.EmptyIfNull()</code> in the first version - note that <code>SelectMany</code> will fail if null is returned by selector</li>\n<li>removing <code>if (children == null) continue;</code> in the second version - note that <code>foreach</code> will fail on a null <code>IEnumerable</code> parameter</li>\n</ul></li>\n<li>allow filtering children with <code>.Where</code> clause on the caller side or within the <em>children selector</em> rather than passing a <em>children filter selector</em> parameter:\n<ul>\n<li>it won't impact the efficiency because in both versions it is a deferred call</li>\n<li>it would be mixing another logic with the method and I prefer to keep the logic separated</li>\n</ul></li>\n</ul>\n\n<p><strong>Sample use</strong></p>\n\n<p>I'm using this extension method in LightSwitch to obtain all controls on the screen:\n</p>\n\n<pre><code>public static class ScreenObjectExtensions\n{\n public static IEnumerable&lt;IContentItemProxy&gt; FindControls(this IScreenObject screen)\n {\n var model = screen.Details.GetModel();\n\n return model.GetChildItems()\n .SelectManyRecursive(c =&gt; c.GetChildItems())\n .OfType&lt;IContentItemDefinition&gt;()\n .Select(c =&gt; screen.FindControl(c.Name));\n }\n}\n</code></pre>\n" }, { "answer_id": 24747394, "author": "Aidin", "author_id": 1084235, "author_profile": "https://Stackoverflow.com/users/1084235", "pm_score": 1, "selected": false, "text": "<p>I had to implement mine from scratch because all of the provided solutions would break in case there is a loop i.e. a child that points to its ancestor. If you have the same requirements as mine please take a look at this (also let me know if my solution would break in any special circumstances):</p>\n\n<p>How to use:</p>\n\n<pre><code>var flattenlist = rootItem.Flatten(obj =&gt; obj.ChildItems, obj =&gt; obj.Id)\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>public static class Extensions\n {\n /// &lt;summary&gt;\n /// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the\n /// items in the data structure regardless of the level of nesting.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of the recursive data structure&lt;/typeparam&gt;\n /// &lt;param name=\"source\"&gt;Source element&lt;/param&gt;\n /// &lt;param name=\"childrenSelector\"&gt;a function that returns the children of a given data element of type T&lt;/param&gt;\n /// &lt;param name=\"keySelector\"&gt;a function that returns a key value for each element&lt;/param&gt;\n /// &lt;returns&gt;a faltten list of all the items within recursive data structure of T&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this IEnumerable&lt;T&gt; source,\n Func&lt;T, IEnumerable&lt;T&gt;&gt; childrenSelector,\n Func&lt;T, object&gt; keySelector) where T : class\n {\n if (source == null)\n throw new ArgumentNullException(\"source\");\n if (childrenSelector == null)\n throw new ArgumentNullException(\"childrenSelector\");\n if (keySelector == null)\n throw new ArgumentNullException(\"keySelector\");\n var stack = new Stack&lt;T&gt;( source);\n var dictionary = new Dictionary&lt;object, T&gt;();\n while (stack.Any())\n {\n var currentItem = stack.Pop();\n var currentkey = keySelector(currentItem);\n if (dictionary.ContainsKey(currentkey) == false)\n {\n dictionary.Add(currentkey, currentItem);\n var children = childrenSelector(currentItem);\n if (children != null)\n {\n foreach (var child in children)\n {\n stack.Push(child);\n }\n }\n }\n yield return currentItem;\n }\n }\n\n /// &lt;summary&gt;\n /// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the\n /// items in the data structure regardless of the level of nesting.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Type of the recursive data structure&lt;/typeparam&gt;\n /// &lt;param name=\"source\"&gt;Source element&lt;/param&gt;\n /// &lt;param name=\"childrenSelector\"&gt;a function that returns the children of a given data element of type T&lt;/param&gt;\n /// &lt;param name=\"keySelector\"&gt;a function that returns a key value for each element&lt;/param&gt;\n /// &lt;returns&gt;a faltten list of all the items within recursive data structure of T&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this T source, \n Func&lt;T, IEnumerable&lt;T&gt;&gt; childrenSelector,\n Func&lt;T, object&gt; keySelector) where T: class\n {\n return Flatten(new [] {source}, childrenSelector, keySelector);\n }\n }\n</code></pre>\n" }, { "answer_id": 30325216, "author": "Yasin Kilicdere", "author_id": 410448, "author_profile": "https://Stackoverflow.com/users/410448", "pm_score": 2, "selected": false, "text": "<p>Function:</p>\n<pre><code>public static class MyExtentions\n{\n public static IEnumerable&lt;T&gt; RecursiveSelector&lt;T&gt;(this IEnumerable&lt;T&gt; nodes, Func&lt;T, IEnumerable&lt;T&gt;&gt; selector)\n {\n if(nodes.Any() == false)\n {\n return nodes; \n }\n\n var descendants = nodes\n .SelectMany(selector)\n .RecursiveSelector(selector);\n\n return nodes.Concat(descendants);\n } \n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>var ar = new[]\n{\n new Node\n {\n Name = &quot;1&quot;,\n Chilren = new[]\n {\n new Node\n {\n Name = &quot;11&quot;,\n Children = new[]\n {\n new Node\n {\n Name = &quot;111&quot;,\n \n }\n }\n }\n }\n }\n};\n\nvar flattened = ar.RecursiveSelector(x =&gt; x.Children).ToList();\n</code></pre>\n" }, { "answer_id": 49847583, "author": "Casey Plummer", "author_id": 704532, "author_profile": "https://Stackoverflow.com/users/704532", "pm_score": 2, "selected": false, "text": "<p>Okay here's another version which is combined from about 3 answers above.</p>\n\n<p>Recursive. Uses yield. Generic. Optional filter predicate. Optional selection function. About as concise as I could make it.</p>\n\n<pre><code> public static IEnumerable&lt;TNode&gt; Flatten&lt;TNode&gt;(\n this IEnumerable&lt;TNode&gt; nodes, \n Func&lt;TNode, bool&gt; filterBy = null,\n Func&lt;TNode, IEnumerable&lt;TNode&gt;&gt; selectChildren = null\n )\n {\n if (nodes == null) yield break;\n if (filterBy != null) nodes = nodes.Where(filterBy);\n\n foreach (var node in nodes)\n {\n yield return node;\n\n var children = (selectChildren == null)\n ? node as IEnumerable&lt;TNode&gt;\n : selectChildren(node);\n\n if (children == null) continue;\n\n foreach (var child in children.Flatten(filterBy, selectChildren))\n {\n yield return child;\n }\n }\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// With filter predicate, with selection function\nvar flatList = nodes.Flatten(n =&gt; n.IsDeleted == false, n =&gt; n.Children);\n</code></pre>\n" }, { "answer_id": 50152534, "author": "FindOutIslamNow", "author_id": 7429464, "author_profile": "https://Stackoverflow.com/users/7429464", "pm_score": 0, "selected": false, "text": "<pre><code>class PageViewModel { \n public IEnumerable&lt;PageViewModel&gt; ChildrenPages { get; set; } \n}\n\nFunc&lt;IEnumerable&lt;PageViewModel&gt;, IEnumerable&lt;PageViewModel&gt;&gt; concatAll = null;\nconcatAll = list =&gt; list.SelectMany(l =&gt; l.ChildrenPages.Any() ? \n concatAll(l.ChildrenPages).Union(new[] { l }) : new[] { l });\n\nvar allPages = concatAll(source).ToArray();\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ]
I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas? Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.
Hmm... I'm not sure *exactly* what you want here, but here's a "one level" option: ``` public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences) where TSequence : IEnumerable<TElement> { foreach (TSequence sequence in sequences) { foreach(TElement element in sequence) { yield return element; } } } ``` If that's not what you want, could you provide the signature of what you do want? If you don't need a generic form, and you just want to do the kind of thing that LINQ to XML constructors do, that's reasonably simple - although the recursive use of iterator blocks is relatively inefficient. Something like: ``` static IEnumerable Flatten(params object[] objects) { // Can't easily get varargs behaviour with IEnumerable return Flatten((IEnumerable) objects); } static IEnumerable Flatten(IEnumerable enumerable) { foreach (object element in enumerable) { IEnumerable candidate = element as IEnumerable; if (candidate != null) { foreach (object nested in candidate) { yield return nested; } } else { yield return element; } } } ``` Note that that will treat a string as a sequence of chars, however - you may want to special-case strings to be individual elements instead of flattening them, depending on your use case. Does that help?
141,484
<p>I'm looking to write a config file that allows for RESTful services in WCF, but I still want the ability to 'tap into' the membership provider for username/password authentication.</p> <p>The below is part of my current config using basicHttp binding or wsHttp w/out WS Security, how will this change w/ REST based services?</p> <pre><code> &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttp"&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport/&gt; &lt;message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;basicHttpBinding&gt; &lt;binding name="basicHttp"&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport/&gt; &lt;message clientCredentialType="UserName"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="NorthwindBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;serviceAuthorization principalPermissionMode="UseAspNetRoles"/&gt; &lt;serviceCredentials&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre>
[ { "answer_id": 143738, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 1, "selected": false, "text": "<p>Before you continue down this path of fighting to implement REST over WCF, I suggest you read <a href=\"http://www.pluralsight.com/community/blogs/tewald/archive/2007/08/26/48298.aspx\" rel=\"nofollow noreferrer\">this</a> post by Tim Ewald. I was especially impacted by the following statement:</p>\n\n<blockquote>\n <p>I'm not sure I want to build on a\n layer designed to factor HTTP in on\n top of a layer that was designed to\n factor it out.</p>\n</blockquote>\n\n<p>I've spent the last 12 months developing REST based stuff with WCF and that statement has proven itself to be so true over and over again. IMHO what WCF brings to the table is outweighed by the complexity it introduces for doing REST work.</p>\n" }, { "answer_id": 149155, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 2, "selected": false, "text": "<p>I agree with Darrel that complex REST scenarios over WCF are a bad idea. It just isn't pretty.</p>\n\n<p>However, Dominick Baier has some <a href=\"http://www.leastprivilege.com/HTTPBasicAuthenticationAgainstNonWindowsAccountsInIISASPNETPart3AddingWCFSupport.aspx\" rel=\"nofollow noreferrer\">good posts</a> about this on his least privilege blog.</p>\n\n<p>If you'd like to see WSSE authentication support with fallback to FormsAuthenticationTicket support on WCF, check out the <a href=\"http://codeplex.com/blogsvc\" rel=\"nofollow noreferrer\">source code of BlogService</a>.</p>\n" }, { "answer_id": 170430, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 2, "selected": false, "text": "<p>Here's a podcast on securing WCF REST services with the ASP.net membership provider:</p>\n\n<p><a href=\"http://channel9.msdn.com/posts/rojacobs/endpointtv-Securing-RESTful-services-with-ASPNET-Membership/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/posts/rojacobs/endpointtv-Securing-RESTful-services-with-ASPNET-Membership/</a></p>\n" }, { "answer_id": 329201, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 1, "selected": false, "text": "<p>Regardless if the community has opinions against REST on WCF <em>(I'm personally on the fence)</em> Microsoft has taken a swipe at it, <strong><a href=\"http://msdn.microsoft.com/en-us/netframework/cc950529.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/netframework/cc950529.aspx</a></strong></p>\n" }, { "answer_id": 412054, "author": "GONeale", "author_id": 41211, "author_profile": "https://Stackoverflow.com/users/41211", "pm_score": 1, "selected": false, "text": "<p>Yes agreed with Moto, a link off the WCF Starter Kit is the closest thing I saw to authentication of credentials using a custom HTTP header (<a href=\"http://msdn.microsoft.com/en-us/library/dd203052.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd203052.aspx</a>).</p>\n\n<p>However I could not get the example going.</p>\n" }, { "answer_id": 670773, "author": "Elijah Glover", "author_id": 53238, "author_profile": "https://Stackoverflow.com/users/53238", "pm_score": 1, "selected": false, "text": "<p>Try <a href=\"http://custombasicauth.codeplex.com/\" rel=\"nofollow noreferrer\">custombasicauth @ codeplex</a></p>\n" }, { "answer_id": 8981501, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 2, "selected": true, "text": "<p><strong>UPDATE 01/23/2012</strong></p>\n\n<p>Since I wrote this question I've seen a much better approach to securing REST like web services in the wild. It sounded complex when I first heard about it but the idea is simple and all over the web for both web services and other secure communication.</p>\n\n<p>It requires the use of public/private keys.</p>\n\n<p>1.) each user (customer) of the endpoint will need to register with your REST web service</p>\n\n<ul>\n<li>a.) you give this user a private key that should not be shared with\nanyone </li>\n<li>b.) you also generate a public key that can go over the wire\nin plain text if need be (this will also be used to identify the client)</li>\n</ul>\n\n<p>2.) each request from the user needs to generate a hash to sign the request</p>\n\n<ul>\n<li>a.) One example of this might look like: private key + a timestamp + encoded payload (if small enough like a simple user info to be updated for example)</li>\n<li>b.) you take these 3 (or whatever you decided on) and generate a 1 way hash (using hmac for example) </li>\n<li>c.) in the request being sent over the wire you include the public key (so the server side knows who is attempting to send this request), the hash that was generated w/ the private key, and the timestamp.</li>\n</ul>\n\n<p>3.) the server endpoint (your REST method) will need to generate a hash using the same inputs used on the client. This step will prove that both client and server knew a private key that matched the public key passed along with the request. (this in turn means that the user sending the request is legit as no one else could know the private key)</p>\n\n<ul>\n<li><p>a.) lookup the customers private key by the public key being passed along during the request </p></li>\n<li><p>b.) take the other params (timestamp and the encoded payload) along with the private key you found in the previous step and use the same algorithm to generate a 1 way hash (again hmac is what I've seen used in the real world) </p></li>\n<li>c.) the resulting 1 way hash needs to match the hash sent over the wire, if not send back a 400 (or whatever http code you deem to be a \"bad request\")</li>\n</ul>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
I'm looking to write a config file that allows for RESTful services in WCF, but I still want the ability to 'tap into' the membership provider for username/password authentication. The below is part of my current config using basicHttp binding or wsHttp w/out WS Security, how will this change w/ REST based services? ``` <bindings> <wsHttpBinding> <binding name="wsHttp"> <security mode="TransportWithMessageCredential"> <transport/> <message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false"/> </security> </binding> </wsHttpBinding> <basicHttpBinding> <binding name="basicHttp"> <security mode="TransportWithMessageCredential"> <transport/> <message clientCredentialType="UserName"/> </security> </binding> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="NorthwindBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceAuthorization principalPermissionMode="UseAspNetRoles"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> ```
**UPDATE 01/23/2012** Since I wrote this question I've seen a much better approach to securing REST like web services in the wild. It sounded complex when I first heard about it but the idea is simple and all over the web for both web services and other secure communication. It requires the use of public/private keys. 1.) each user (customer) of the endpoint will need to register with your REST web service * a.) you give this user a private key that should not be shared with anyone * b.) you also generate a public key that can go over the wire in plain text if need be (this will also be used to identify the client) 2.) each request from the user needs to generate a hash to sign the request * a.) One example of this might look like: private key + a timestamp + encoded payload (if small enough like a simple user info to be updated for example) * b.) you take these 3 (or whatever you decided on) and generate a 1 way hash (using hmac for example) * c.) in the request being sent over the wire you include the public key (so the server side knows who is attempting to send this request), the hash that was generated w/ the private key, and the timestamp. 3.) the server endpoint (your REST method) will need to generate a hash using the same inputs used on the client. This step will prove that both client and server knew a private key that matched the public key passed along with the request. (this in turn means that the user sending the request is legit as no one else could know the private key) * a.) lookup the customers private key by the public key being passed along during the request * b.) take the other params (timestamp and the encoded payload) along with the private key you found in the previous step and use the same algorithm to generate a 1 way hash (again hmac is what I've seen used in the real world) * c.) the resulting 1 way hash needs to match the hash sent over the wire, if not send back a 400 (or whatever http code you deem to be a "bad request")
141,487
<pre><code>class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() </code></pre> <p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
[ { "answer_id": 141505, "author": "Nick Sergeant", "author_id": 22468, "author_profile": "https://Stackoverflow.com/users/22468", "pm_score": 2, "selected": false, "text": "<p>For pre-1.0:</p>\n\n<pre><code>slug = models.SlugField(prepopulate_from=('title',))\n</code></pre>\n\n<p>should work just fine</p>\n\n<p>For 1.0, use <a href=\"https://stackoverflow.com/questions/141487/is-there-an-easy-way-to-populate-slugfield-from-charfield#141554\">camflan's</a></p>\n" }, { "answer_id": 141554, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 7, "selected": true, "text": "<p>for Admin in Django 1.0 and up, you'd need to use</p>\n\n<pre><code>prepopulated_fields = {'slug': ('title',), }\n</code></pre>\n\n<p>in your admin.py</p>\n\n<p>Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.</p>\n\n<p>Outside of admin, you can use the <code>slugify</code> function in your views. In templates, you can use the <code>|slugify</code> filter.</p>\n\n<p>There is also this package which will take care of this automatically: <a href=\"https://pypi.python.org/pypi/django-autoslug\" rel=\"noreferrer\">https://pypi.python.org/pypi/django-autoslug</a></p>\n" }, { "answer_id": 141947, "author": "AdamKG", "author_id": 16361, "author_profile": "https://Stackoverflow.com/users/16361", "pm_score": 3, "selected": false, "text": "<p>Outside the admin, see <a href=\"http://www.djangosnippets.org/snippets/690/\" rel=\"noreferrer\">this django snippet</a>. Put it in your <code>.save()</code>, and it'll work with objects created programmatically. Inside the admin, as the others have said, use <code>prepopulated_fields</code>.</p>\n" }, { "answer_id": 153028, "author": "carefulweb", "author_id": 12683, "author_profile": "https://Stackoverflow.com/users/12683", "pm_score": 2, "selected": false, "text": "<p>You can also use pre_save django signal to populate slug outside of django admin code.\nSee <a href=\"http://docs.djangoproject.com/en/dev/ref/signals/\" rel=\"nofollow noreferrer\">Django signals documentation</a>.</p>\n\n<p>Ajax slug uniqueness validation will be useful too, see <a href=\"http://lethain.com/entry/2008/sep/26/as-you-type-slug-uniqueness-validation/\" rel=\"nofollow noreferrer\">As-You-Type Slug Uniqueness Validation @ Irrational Exuberance</a></p>\n" }, { "answer_id": 7470874, "author": "Jon Lemmon", "author_id": 307438, "author_profile": "https://Stackoverflow.com/users/307438", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://bitbucket.org/neithere/django-autoslug\" rel=\"nofollow\">autoslug</a> has worked quite well for me in the past. Although I've never tried using it with the admin app.</p>\n" }, { "answer_id": 55772264, "author": "Andreas Bergström", "author_id": 1202214, "author_profile": "https://Stackoverflow.com/users/1202214", "pm_score": 3, "selected": false, "text": "<p>Thought I would add a complete and up-to-date answer with gotchas mentioned:</p>\n<h2>1. Auto-populate forms in Django Admin</h2>\n<p>If you are only concerned about adding and updating data in the admin, you could simply use the <a href=\"https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields\" rel=\"nofollow noreferrer\">prepopulated_fields</a> attribute</p>\n<pre><code>class ArticleAdmin(admin.ModelAdmin):\n prepopulated_fields = {&quot;slug&quot;: (&quot;title&quot;,)}\n\nadmin.site.register(Article, ArticleAdmin)\n</code></pre>\n<h2>2. Auto-populate custom forms in templates</h2>\n<p>If you have built your own server-rendered interface with forms, you could auto-populate the fields by using either the <a href=\"https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#slugify\" rel=\"nofollow noreferrer\">|slugify</a> tamplate filter or the <a href=\"https://docs.djangoproject.com/en/2.2/ref/utils/#django.utils.text.slugify\" rel=\"nofollow noreferrer\">slugify</a> utility when saving the form (is_valid).</p>\n<h2>3. Auto-populating slugfields at model-level with django-autoslug</h2>\n<p>The above solutions will only auto-populate the slugfield (or any field) when data is manipulated through those interfaces (the admin or a custom form). If you have an API, management commands or anything else that also manipulates the data you need to drop down to model-level.</p>\n<p><a href=\"https://pypi.org/project/django-autoslug/\" rel=\"nofollow noreferrer\">django-autoslug</a> provides the AutoSlugField-fields which extends SlugField and allows you to set which field it should slugify neatly:</p>\n<pre><code>class Article(Model):\n title = CharField(max_length=200)\n slug = AutoSlugField(populate_from='title')\n</code></pre>\n<p><strong>The field uses pre_save and post_save signals to achieve its functionality so please see the gotcha text at the bottom of this answer.</strong></p>\n<h2>4. Auto-populating slugfields at model-level by overriding save()</h2>\n<p>The last option is to implement this yourself, which involves overriding the default save() method:</p>\n<pre><code>class Article(Model):\n title = CharField(max_length=200)\n slug = SlugField()\n\n def save(self, *args, **kwargs):\n self.slug = slugify(self.title)\n super().save(*args, **kwargs)\n</code></pre>\n<h3>NOTE: Bulk-updates will bypass your code (including signals)</h3>\n<p>This is a common miss-understanding by beginners to Django. First you should know that the pre_save and post_save signals are directly related to the save()-method. Secondly the different ways to do bulk-updates in Django all circumvent the save()-method to achieve high performance, by operating directly on the SQL-layer. This means that for the example model used in solution 3 or 4 above:</p>\n<ul>\n<li>Article.objects.all().update(title='New post') will <strong>NOT</strong> update the slug of any article</li>\n<li>Using <a href=\"https://docs.djangoproject.com/en/2.2/ref/models/querysets/#bulk-create\" rel=\"nofollow noreferrer\">bulk_create</a> or <a href=\"https://docs.djangoproject.com/en/2.2/ref/models/querysets/#bulk-update\" rel=\"nofollow noreferrer\">bulk_update</a> on the Article model will <strong>NOT</strong> update the slug of any article.</li>\n<li>Since the save()-method is not called, <strong>no pre_save or post_save signals will be emitted</strong>.</li>\n</ul>\n<p>To do bulk updates and still utilize code-level constraints the only solution is to iterate objects one by one and call its save()-method, which has drastically less performance than SQL-level bulk operations. You could of course use triggers in your database, though that is a totally different topic.</p>\n" }, { "answer_id": 71843695, "author": "Iasmini Gomes", "author_id": 2638015, "author_profile": "https://Stackoverflow.com/users/2638015", "pm_score": 1, "selected": false, "text": "<p><strong>Auto-populating slugfields at model-level with the built-in django slugify:</strong></p>\n<p><strong>models.py</strong></p>\n<pre><code>from django.db import models\n\n\nclass Place:\n name = models.CharField(max_length=50)\n slug_name = models.SlugField(max_length=50)\n</code></pre>\n<p><strong>signals.py</strong></p>\n<pre><code>from django.db.models.signals import pre_save\nfrom django.dispatch import receiver\nfrom django.template.defaultfilters import slugify as django_slugify\n\nfrom v1 import models\n\n\n@receiver(pre_save, sender=models.Place)\ndef validate_slug_name(sender, instance: models.Place, **kwargs):\n instance.slug_name = django_slugify(instance.name)\n</code></pre>\n<p>Credits to: <a href=\"https://github.com/justinmayer/django-autoslug/blob/9e3992296544a4fd7417a833a9866112021daa82/autoslug/utils.py#L18\" rel=\"nofollow noreferrer\">https://github.com/justinmayer/django-autoslug/blob/9e3992296544a4fd7417a833a9866112021daa82/autoslug/utils.py#L18</a></p>\n" }, { "answer_id": 72656749, "author": "Epsilon36170", "author_id": 16734290, "author_profile": "https://Stackoverflow.com/users/16734290", "pm_score": 0, "selected": false, "text": "<pre><code>prepopulated_fields = {'slug': ('title',), }\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ]
``` class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() ``` Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
for Admin in Django 1.0 and up, you'd need to use ``` prepopulated_fields = {'slug': ('title',), } ``` in your admin.py Your key in the prepopulated\_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated. Outside of admin, you can use the `slugify` function in your views. In templates, you can use the `|slugify` filter. There is also this package which will take care of this automatically: <https://pypi.python.org/pypi/django-autoslug>
141,519
<p>We have a pair of applications. One is written in C# and uses something like:</p> <pre><code> string s = "alpha\r\nbeta\r\ngamma\r\ndelta"; // Actually there's wrapper code here to make sure this works. System.Windows.Forms.Clipboard.SetDataObject(s, true); </code></pre> <p>To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.)</p> <p>In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs.</p> <p>Just <em>one</em> user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy.</p> <p>Ideas?</p>
[ { "answer_id": 141516, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": false, "text": "<p>I use <code>print_r()</code> because I like the pretty array structure... but <code>var_dump</code> does give you a bit more information (like types)</p>\n\n<pre><code>$obj = (object) array(1, 2, 3);\n\n// output of var_dump:\nobject(stdClass)#1 (3) {\n [0]=&gt;\n int(1)\n [1]=&gt;\n int(2)\n [2]=&gt;\n int(3)\n}\n\n// output of print_r\nstdClass Object\n(\n [0] =&gt; 1\n [1] =&gt; 2\n [2] =&gt; 3\n) \n</code></pre>\n" }, { "answer_id": 141563, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>I use these custom functions depending on whether I'm dealing with an array or a single value:</p>\n\n<pre><code>function show($array)\n{\n echo '&lt;pre&gt;';\n print_r($array);\n echo '&lt;/pre&gt;';\n}\n\nfunction prn($var)\n{\n echo '&lt;br/&gt;' . $var . '&lt;br/&gt;';\n}\n</code></pre>\n\n<p>I find that these functions simplify troubleshooting because I generally end up needing to format the output so that I can go through it easily right on screen.</p>\n\n<p>For more complex troubleshooting, we use an extended version of the Exception class that will email a stack trace along with a specific error message. This gives me the functions that were involved, what files were involved and what line or lines were involved in the error as well as whatever custom message I created so that I know exactly what's going on. For an added layer of troubleshooting, we also log these errors in the database being accessed.</p>\n" }, { "answer_id": 141588, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>I just user print_r, along with a couple of wrapper functions to store the various DebugPrint I put in my code and one on the footer to dump the stack in the page (or in a file).</p>\n\n<p>I now try to use XDebug too... :-D</p>\n\n<p>OK, for the record, I give my little functions...</p>\n\n<pre><code>// Primitive debug message storage\n// $level = \"Info\", \"Warn\", \"Error\", \"Title\"\nfunction DebugPrint($toDump, $level = \"Info\") {\n global $debugMode, $debugDump, $debugCount;\n\n if ($debugMode != 'N') {\n $debugDump[$debugCount++] = \"&lt;div class='Dbg$level'&gt;\" . $toDump . \"&lt;/div&gt;\\n\";\n }\n}\n\n// Initialize debug information collection\n$debugMode = 'N'; // N=no, desactivated, P=dump to Web page, F=dump to file\n$debugSavePath = 'C:\\www\\App\\log_debug.txt'; // If mode F\n$debugDump = array();\n$debugCount = 0;\n\n// Primitive debug message dump\nfunction DebugDump() {\n global $debugMode, $debugSavePath, $debugDump, $debugCount;\n\n if ($debugMode == 'F') {\n $fp = fopen($debugSavePath, \"a\"); #open for writing\n }\n if ($debugCount &gt; 0) {\n switch ($debugMode) {\n case 'P':\n echo '&lt;div style=\"color: red; background: #8FC; font-size: 24px;\"&gt;Debug:&lt;br /&gt;\n';\n for ($i = 0; $i &lt; $debugCount; $i++) {\n echo $debugDump[$i];\n }\n echo '&lt;/div&gt;\n';\n break;\n case 'F':\n for ($i = 0; $i &lt; $debugCount; $i++) {\n fputs($fp, $debugDump[$i]);\n }\n break;\n//~ default:\n//~ echo \"debugMode = $debugMode&lt;br /&gt;\\n\";\n }\n }\n if ($fp != null) {\n fputs($fp, \"-----\\n\");\n fclose($fp);\n }\n}\n\n// Pre array dump\nfunction DebugArrayPrint($array) {\nglobal $debugMode;\n\n if ($debugMode != 'N') {\n return \"&lt;pre class='ArrayPrint'&gt;\" . print_r($array, true) . \"&lt;/pre&gt;\";\n } else return \"\"; // Gain some microseconds...\n}\n</code></pre>\n\n<p>The interest is to delay the output to the end of the page, avoiding to clutter the real page.</p>\n" }, { "answer_id": 141597, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 1, "selected": false, "text": "<p>If you want to avoid sending errors to the browser but want the advantage of var_dump and print_r then take a look at output buffering:</p>\n\n<pre><code>ob_start();\nvar_dump($this); echo $that; print_r($stuff);\n$out = ob_get_contents();\nob_end_clean();\n\nuser_error($out);\n</code></pre>\n\n<p>some good reading in <a href=\"http://www.php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/book.outcontrol.php</a></p>\n" }, { "answer_id": 141604, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>print_r() usually, but var_dump() provides better information for primitives.</p>\n\n<p>That being said, I do most of my <em>actual</em> debugging with the Zend Server Debugger.</p>\n" }, { "answer_id": 142258, "author": "Meisner", "author_id": 22827, "author_profile": "https://Stackoverflow.com/users/22827", "pm_score": 1, "selected": false, "text": "<p>There is something I find very useful that lacks from the standard PHP implementations of variable dump functions, i.e. the ability to just print part of an expression.</p>\n\n<p>Here is a function that solves this:</p>\n\n<pre><code>function dump($val) {\n echo '&lt;pre&gt;'.var_export($val,true).'&lt;/pre&gt;';\n return $val;\n}\n</code></pre>\n\n<p>Now I can just put a function call around the expression I need to know the value of without distrupting usual code execution flow like this:</p>\n\n<pre><code>$a=2+dump(2*2);\n</code></pre>\n\n<p>With use of less-known <em>var_export</em> I also eliminated the need to implement output buffering to post-process the result.</p>\n" }, { "answer_id": 143207, "author": "Shoan", "author_id": 17404, "author_profile": "https://Stackoverflow.com/users/17404", "pm_score": 3, "selected": true, "text": "<p>I always use the Xdebug extended var_dump. It gives out a lot of verbose output. </p>\n\n<p>See: <a href=\"http://xdebug.org/docs/display\" rel=\"nofollow noreferrer\">http://xdebug.org/docs/display</a> for more details.</p>\n" }, { "answer_id": 143276, "author": "user22960", "author_id": 22960, "author_profile": "https://Stackoverflow.com/users/22960", "pm_score": 1, "selected": false, "text": "<p>When you generate a binary answer (i.e. an image using GD library), then you can use a valid tuned header: </p>\n\n<blockquote>\n<code>header('X-eleg:'.serialize($yourstuff));</code>\n</blockquote>\n\n<p>and use the Http-header extension for Firefox to \"spy\" it.</p>\n" }, { "answer_id": 299692, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 0, "selected": false, "text": "<p>var_dump. With XDebug installed it formats and colors the output nicely (no having to put <code>&lt;pre&gt;</code> tags around it).</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ]
We have a pair of applications. One is written in C# and uses something like: ``` string s = "alpha\r\nbeta\r\ngamma\r\ndelta"; // Actually there's wrapper code here to make sure this works. System.Windows.Forms.Clipboard.SetDataObject(s, true); ``` To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.) In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs. Just *one* user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy. Ideas?
I always use the Xdebug extended var\_dump. It gives out a lot of verbose output. See: <http://xdebug.org/docs/display> for more details.
141,525
<p>I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...</p> <p>At a core level, what does bit-shifting (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>, <code>&gt;&gt;&gt;</code>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.</p>
[ { "answer_id": 141576, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": false, "text": "<p>Let's say we have a single byte:</p>\n\n<pre><code>0110110\n</code></pre>\n\n<p>Applying a single left bitshift gets us:</p>\n\n<pre><code>1101100\n</code></pre>\n\n<p>The leftmost zero was shifted out of the byte, and a new zero was appended to the right end of the byte.</p>\n\n<p>The bits don't rollover; they are discarded. That means if you left shift 1101100 and then right shift it, you won't get the same result back.</p>\n\n<p>Shifting left by N is equivalent to multiplying by 2<sup>N</sup>.</p>\n\n<p>Shifting right by N is (if you are using <a href=\"https://en.wikipedia.org/wiki/Ones%27_complement\" rel=\"noreferrer\">ones' complement</a>) is the equivalent of dividing by 2<sup>N</sup> and rounding to zero.</p>\n\n<p>Bitshifting can be used for insanely fast multiplication and division, provided you are working with a power of 2. Almost all low-level graphics routines use bitshifting.</p>\n\n<p>For example, way back in the olden days, we used mode 13h (320x200 256 colors) for games. In Mode 13h, the video memory was laid out sequentially per pixel. That meant to calculate the location for a pixel, you would use the following math:</p>\n\n<pre><code>memoryOffset = (row * 320) + column\n</code></pre>\n\n<p>Now, back in that day and age, speed was critical, so we would use bitshifts to do this operation.</p>\n\n<p>However, 320 is not a power of two, so to get around this we have to find out what is a power of two that added together makes 320:</p>\n\n<pre><code>(row * 320) = (row * 256) + (row * 64)\n</code></pre>\n\n<p>Now we can convert that into left shifts:</p>\n\n<pre><code>(row * 320) = (row &lt;&lt; 8) + (row &lt;&lt; 6)\n</code></pre>\n\n<p>For a final result of:</p>\n\n<pre><code>memoryOffset = ((row &lt;&lt; 8) + (row &lt;&lt; 6)) + column\n</code></pre>\n\n<p>Now we get the same offset as before, except instead of an expensive multiplication operation, we use the two bitshifts...in x86 it would be something like this (note, it's been forever since I've done assembly (editor's note: corrected a couple mistakes and added a 32-bit example)):</p>\n\n<pre><code>mov ax, 320; 2 cycles\nmul word [row]; 22 CPU Cycles\nmov di,ax; 2 cycles\nadd di, [column]; 2 cycles\n; di = [row]*320 + [column]\n\n; 16-bit addressing mode limitations:\n; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov\n</code></pre>\n\n<p>Total: 28 cycles on whatever ancient CPU had these timings.</p>\n\n<p>Vrs</p>\n\n<pre><code>mov ax, [row]; 2 cycles\nmov di, ax; 2\nshl ax, 6; 2\nshl di, 8; 2\nadd di, ax; 2 (320 = 256+64)\nadd di, [column]; 2\n; di = [row]*(256+64) + [column]\n</code></pre>\n\n<p>12 cycles on the same ancient CPU.</p>\n\n<p>Yes, we would work this hard to shave off 16 CPU cycles.</p>\n\n<p>In 32 or 64-bit mode, both versions get a lot shorter and faster. Modern out-of-order execution CPUs like Intel Skylake (see <a href=\"http://agner.org/optimize/\" rel=\"noreferrer\">http://agner.org/optimize/</a>) have very fast hardware multiply (low latency and high throughput), so the gain is much smaller. AMD Bulldozer-family is a bit slower, especially for 64-bit multiply. On Intel CPUs, and AMD Ryzen, two shifts are slightly lower latency but more instructions than a multiply (which may lead to lower throughput):</p>\n\n<pre><code>imul edi, [row], 320 ; 3 cycle latency from [row] being ready\nadd edi, [column] ; 1 cycle latency (from [column] and edi being ready).\n; edi = [row]*(256+64) + [column], in 4 cycles from [row] being ready.\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>mov edi, [row]\nshl edi, 6 ; row*64. 1 cycle latency\nlea edi, [edi + edi*4] ; row*(64 + 64*4). 1 cycle latency\nadd edi, [column] ; 1 cycle latency from edi and [column] both being ready\n; edi = [row]*(256+64) + [column], in 3 cycles from [row] being ready.\n</code></pre>\n\n<p>Compilers will do this for you: See how <a href=\"https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:&#39;int+idx(int+row,+int+col)+%7B%0A++return+320*row+%2B+col%3B%0A%7D&#39;),l:&#39;5&#39;,n:&#39;0&#39;,o:&#39;C%2B%2B+source+%231&#39;,t:&#39;0&#39;)),k:36.97169647716434,l:&#39;4&#39;,n:&#39;0&#39;,o:&#39;&#39;,s:0,t:&#39;0&#39;),(g:!((h:compiler,i:(compiler:g63,filters:(b:&#39;0&#39;,commentOnly:&#39;0&#39;,directives:&#39;0&#39;,intel:&#39;0&#39;),options:&#39;-O3+-std%3Dc%2B%2B11+-Wall&#39;,source:1),l:&#39;5&#39;,n:&#39;0&#39;,o:&#39;x86-64+gcc+6.3+(Editor+%231,+Compiler+%231)&#39;,t:&#39;0&#39;)),k:30.33026438926557,l:&#39;4&#39;,n:&#39;0&#39;,o:&#39;&#39;,s:0,t:&#39;0&#39;),(g:!((g:!((h:compiler,i:(compiler:clang400,filters:(b:&#39;0&#39;,commentOnly:&#39;0&#39;,directives:&#39;0&#39;,intel:&#39;0&#39;),options:&#39;-O3+-std%3Dc%2B%2B11+-Wall&#39;,source:1),l:&#39;5&#39;,n:&#39;0&#39;,o:&#39;x86-64+clang+4.0.0+(Editor+%231,+Compiler+%232)&#39;,t:&#39;0&#39;)),header:(),k:32.69803913357011,l:&#39;4&#39;,m:61.21344498970813,n:&#39;0&#39;,o:&#39;&#39;,s:0,t:&#39;0&#39;),(g:!((h:compiler,i:(compiler:cl19_64,filters:(b:&#39;0&#39;,commentOnly:&#39;0&#39;,directives:&#39;0&#39;,intel:&#39;0&#39;),options:&#39;-Ox&#39;,source:1),l:&#39;5&#39;,n:&#39;0&#39;,o:&#39;x86-64+CL+19+2017+RTW+(Editor+%231,+Compiler+%233)&#39;,t:&#39;0&#39;)),header:(),l:&#39;4&#39;,m:38.78655501029187,n:&#39;0&#39;,o:&#39;&#39;,s:0,t:&#39;0&#39;)),k:32.69803913357011,l:&#39;3&#39;,n:&#39;0&#39;,o:&#39;&#39;,t:&#39;0&#39;)),l:&#39;2&#39;,n:&#39;0&#39;,o:&#39;&#39;,t:&#39;0&#39;)),version:4\" rel=\"noreferrer\">GCC, Clang, and Microsoft Visual C++ all use shift+lea when optimizing <code>return 320*row + col;</code></a>.</p>\n\n<p>The most interesting thing to note here is that <a href=\"https://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction/7071164#7071164\">x86 has a shift-and-add instruction (<code>LEA</code>)</a> that can do small left shifts and add at the same time, with the performance as an <code>add</code> instruction. ARM is even more powerful: one operand of any instruction can be left or right shifted for free. So scaling by a compile-time-constant that's known to be a power-of-2 can be even more efficient than a multiply.</p>\n\n<hr>\n\n<p>OK, back in the modern days... something more useful now would be to use bitshifting to store two 8-bit values in a 16-bit integer. For example, in C#:</p>\n\n<pre><code>// Byte1: 11110000\n// Byte2: 00001111\n\nInt16 value = ((byte)(Byte1 &gt;&gt; 8) | Byte2));\n\n// value = 000011111110000;\n</code></pre>\n\n<p>In C++, compilers should do this for you if you used a <code>struct</code> with two 8-bit members, but in practice they don't always.</p>\n" }, { "answer_id": 141645, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 5, "selected": false, "text": "<p>One gotcha is that the following is implementation dependent (according to the ANSI standard): </p>\n\n<pre><code>char x = -1;\nx &gt;&gt; 1;\n</code></pre>\n\n<p>x can now be 127 (01111111) or still -1 (11111111).</p>\n\n<p>In practice, it's usually the latter.</p>\n" }, { "answer_id": 141873, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 12, "selected": true, "text": "<p>The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.</p>\n<h2>The Operators</h2>\n<ul>\n<li><code>&gt;&gt;</code> is the arithmetic (or signed) right shift operator.</li>\n<li><code>&gt;&gt;&gt;</code> is the logical (or unsigned) right shift operator.</li>\n<li><code>&lt;&lt;</code> is the left shift operator, and meets the needs of both logical and arithmetic shifts.</li>\n</ul>\n<p>All of these operators can be applied to integer values (<code>int</code>, <code>long</code>, possibly <code>short</code> and <code>byte</code> or <code>char</code>). In some languages, applying the shift operators to any datatype smaller than <code>int</code> automatically resizes the operand to be an <code>int</code>.</p>\n<p>Note that <code>&lt;&lt;&lt;</code> is not an operator, because it would be redundant.</p>\n<p>Also note that <strong>C and C++ do not distinguish between the right shift operators</strong>. They provide only the <code>&gt;&gt;</code> operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.</p>\n<p>(In all mainstream C and C++ implementations including GCC and Clang/LLVM, <code>&gt;&gt;</code> on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not <em>undefined</em>, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers <em>is</em> undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)</p>\n<hr />\n<h2>Left shift (&lt;&lt;)</h2>\n<p>Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit <code>int</code> would be:</p>\n<pre><code>00000000 00000000 00000000 00000110\n</code></pre>\n<p>Shifting this bit pattern to the left one position (<code>6 &lt;&lt; 1</code>) would result in the number 12:</p>\n<pre><code>00000000 00000000 00000000 00001100\n</code></pre>\n<p>As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So <code>6 &lt;&lt; 1</code> is equivalent to <code>6 * 2</code>, and <code>6 &lt;&lt; 3</code> is equivalent to <code>6 * 8</code>. A good optimizing compiler will replace multiplications with shifts when possible.</p>\n<h3>Non-circular shifting</h3>\n<p>Please note that these are <em>not</em> circular shifts. Shifting this value to the left by one position (<code>3,758,096,384 &lt;&lt; 1</code>):</p>\n<pre><code>11100000 00000000 00000000 00000000\n</code></pre>\n<p>results in 3,221,225,472:</p>\n<pre><code>11000000 00000000 00000000 00000000\n</code></pre>\n<p>The digit that gets shifted &quot;off the end&quot; is lost. It does not wrap around.</p>\n<hr />\n<h2>Logical right shift (&gt;&gt;&gt;)</h2>\n<p>A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:</p>\n<pre><code>00000000 00000000 00000000 00001100\n</code></pre>\n<p>to the right by one position (<code>12 &gt;&gt;&gt; 1</code>) will get back our original 6:</p>\n<pre><code>00000000 00000000 00000000 00000110\n</code></pre>\n<p>So we see that shifting to the right is equivalent to division by powers of 2.</p>\n<h3>Lost bits are gone</h3>\n<p>However, a shift cannot reclaim &quot;lost&quot; bits. For example, if we shift this pattern:</p>\n<pre><code>00111000 00000000 00000000 00000110\n</code></pre>\n<p>to the left 4 positions (<code>939,524,102 &lt;&lt; 4</code>), we get 2,147,483,744:</p>\n<pre><code>10000000 00000000 00000000 01100000\n</code></pre>\n<p>and then shifting back (<code>(939,524,102 &lt;&lt; 4) &gt;&gt;&gt; 4</code>) we get 134,217,734:</p>\n<pre><code>00001000 00000000 00000000 00000110\n</code></pre>\n<p>We cannot get back our original value once we have lost bits.</p>\n<hr />\n<h1>Arithmetic right shift (&gt;&gt;)</h1>\n<p>The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the <em>sign</em> bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.</p>\n<p>For example, if we interpret this bit pattern as a negative number:</p>\n<pre><code>10000000 00000000 00000000 01100000\n</code></pre>\n<p>we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 &gt;&gt; 4) would give us:</p>\n<pre><code>11111000 00000000 00000000 00000110\n</code></pre>\n<p>or the number -134,217,722.</p>\n<p>So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.</p>\n" }, { "answer_id": 142335, "author": "robottobor", "author_id": 10184, "author_profile": "https://Stackoverflow.com/users/10184", "pm_score": 7, "selected": false, "text": "<p>Bitwise operations, including bit shift, are fundamental to low-level hardware or embedded programming. If you read a specification for a device or even some binary file formats, you will see bytes, words, and dwords, broken up into non-byte aligned bitfields, which contain various values of interest. Accessing these bit-fields for reading/writing is the most common usage.</p>\n\n<p>A simple real example in graphics programming is that a 16-bit pixel is represented as follows:</p>\n\n<pre><code> bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n | Blue | Green | Red |\n</code></pre>\n\n<p>To get at the green value you would do this:</p>\n\n<pre><code> #define GREEN_MASK 0x7E0\n #define GREEN_OFFSET 5\n\n // Read green\n uint16_t green = (pixel &amp; GREEN_MASK) &gt;&gt; GREEN_OFFSET;\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p>In order to obtain the value of green ONLY, which starts at offset 5 and ends at 10 (i.e. 6-bits long), you need to use a (bit) mask, which when applied against the entire 16-bit pixel, will yield only the bits we are interested in.</p>\n\n<pre><code>#define GREEN_MASK 0x7E0\n</code></pre>\n\n<p>The appropriate mask is 0x7E0 which in binary is 0000011111100000 (which is 2016 in decimal).</p>\n\n<pre><code>uint16_t green = (pixel &amp; GREEN_MASK) ...;\n</code></pre>\n\n<p>To apply a mask, you use the AND operator (&amp;).</p>\n\n<pre><code>uint16_t green = (pixel &amp; GREEN_MASK) &gt;&gt; GREEN_OFFSET;\n</code></pre>\n\n<p>After applying the mask, you'll end up with a 16-bit number which is really just a 11-bit number since its MSB is in the 11th bit. Green is actually only 6-bits long, so we need to scale it down using a right shift (11 - 6 = 5), hence the use of 5 as offset (<code>#define GREEN_OFFSET 5</code>).</p>\n\n<p>Also common is using bit shifts for fast multiplication and division by powers of 2:</p>\n\n<pre><code> i &lt;&lt;= x; // i *= 2^x;\n i &gt;&gt;= y; // i /= 2^y;\n</code></pre>\n" }, { "answer_id": 29366874, "author": "Basti Funck", "author_id": 2043922, "author_profile": "https://Stackoverflow.com/users/2043922", "pm_score": 6, "selected": false, "text": "<h2>Bit Masking &amp; Shifting</h2>\n<p>Bit shifting is often used in low-level graphics programming. For example, a given pixel color value encoded in a 32-bit word.</p>\n<pre><code> Pixel-Color Value in Hex: B9B9B900\n Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000\n</code></pre>\n<p>For better understanding, the same binary value labeled with what sections represent what color part.</p>\n<pre><code> Red Green Blue Alpha\n Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000\n</code></pre>\n<p>Let's say for example we want to get the green value of this pixel's color. We can easily get that value by <em>masking</em> and <em>shifting</em>.</p>\n<p>Our mask:</p>\n<pre><code> Red Green Blue Alpha\n color : 10111001 10111001 10111001 00000000\n green_mask : 00000000 11111111 00000000 00000000\n\n masked_color = color &amp; green_mask\n\n masked_color: 00000000 10111001 00000000 00000000\n</code></pre>\n<p>The logical <code>&amp;</code> operator ensures that only the values where the mask is 1 are kept. The last thing we now have to do, is to get the correct integer value by shifting all those bits to the right by 16 places <em>(logical right shift)</em>.</p>\n<pre><code> green_value = masked_color &gt;&gt;&gt; 16\n</code></pre>\n<p>Et voilà, we have the integer representing the amount of green in the pixel's color:</p>\n<pre><code> Pixels-Green Value in Hex: 000000B9\n Pixels-Green Value in Binary: 00000000 00000000 00000000 10111001\n Pixels-Green Value in Decimal: 185\n</code></pre>\n<p>This is often used for encoding or decoding image formats like <code>jpg</code>, <code>png</code>, etc.</p>\n" }, { "answer_id": 32271993, "author": "Patrick Monkelban", "author_id": 4585281, "author_profile": "https://Stackoverflow.com/users/4585281", "pm_score": 3, "selected": false, "text": "<p>Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.</p>\n\n<p>For example:</p>\n\n<pre><code>(long) 4 &gt;&gt; 65\n</code></pre>\n\n<p>equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:</p>\n\n<pre><code>(long) 4 &gt;&gt; (65 % 64)\n</code></pre>\n\n<p>This is true for &lt;&lt;, >>, and >>>. I have not tried it out in other languages.</p>\n" }, { "answer_id": 33304845, "author": "lukyer", "author_id": 1977799, "author_profile": "https://Stackoverflow.com/users/1977799", "pm_score": -1, "selected": false, "text": "<p>Be aware of that only 32 bit version of PHP is available on the Windows platform.</p>\n\n<p>Then if you for instance shift &lt;&lt; or >> more than by 31 bits, results are unexpectable. Usually the original number instead of zeros will be returned, and it can be a really tricky bug.</p>\n\n<p>Of course if you use 64 bit version of PHP (Unix), you should avoid shifting by more than 63 bits. However, for instance, MySQL uses the 64-bit BIGINT, so there should not be any compatibility problems.</p>\n\n<p>UPDATE: From PHP 7 Windows, PHP builds are finally able to use full 64 bit integers:\n<em>The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.</em></p>\n" }, { "answer_id": 39987901, "author": "HoneyBeer", "author_id": 2050095, "author_profile": "https://Stackoverflow.com/users/2050095", "pm_score": 5, "selected": false, "text": "<p>I am writing tips and tricks only. It may be useful in tests and exams. </p>\n\n<ol>\n<li><code>n = n*2</code>: <code>n = n&lt;&lt;1</code></li>\n<li><code>n = n/2</code>: <code>n = n&gt;&gt;1</code></li>\n<li>Checking if n is power of 2 (1,2,4,8,...): check <code>!(n &amp; (n-1))</code></li>\n<li>Getting <em>x</em><sup>th</sup> bit of <code>n</code>: <code>n |= (1 &lt;&lt; x)</code></li>\n<li>Checking if x is even or odd: <code>x&amp;1 == 0</code> (even)</li>\n<li>Toggle the <em>n</em><sup>th</sup> bit of x: <code>x ^ (1&lt;&lt;n)</code></li>\n</ol>\n" }, { "answer_id": 55883733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Some useful bit operations/manipulations in Python.</p>\n\n<p>I implemented <a href=\"https://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work/39987901#39987901\">Ravi Prakash's answer</a> in Python.</p>\n\n<pre><code># Basic bit operations\n# Integer to binary\nprint(bin(10))\n\n# Binary to integer\nprint(int('1010', 2))\n\n# Multiplying x with 2 .... x**2 == x &lt;&lt; 1\nprint(200 &lt;&lt; 1)\n\n# Dividing x with 2 .... x/2 == x &gt;&gt; 1\nprint(200 &gt;&gt; 1)\n\n# Modulo x with 2 .... x % 2 == x &amp; 1\nif 20 &amp; 1 == 0:\n print(\"20 is a even number\")\n\n# Check if n is power of 2: check !(n &amp; (n-1))\nprint(not(33 &amp; (33-1)))\n\n# Getting xth bit of n: (n &gt;&gt; x) &amp; 1\nprint((10 &gt;&gt; 2) &amp; 1) # Bin of 10 == 1010 and second bit is 0\n\n# Toggle nth bit of x : x^(1 &lt;&lt; n)\n# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)\nprint(10^(1 &lt;&lt; 2))\n</code></pre>\n" }, { "answer_id": 62363693, "author": "Trishant Saxena", "author_id": 10304471, "author_profile": "https://Stackoverflow.com/users/10304471", "pm_score": 2, "selected": false, "text": "<p>The Bitwise operators are used to perform operations a bit-level or to manipulate bits in different ways. The bitwise operations are found to be much faster and are some times used to improve the efficiency of a program.\nBasically, Bitwise operators can be applied to the integer types: <strong>long</strong>, <strong>int</strong>, <strong>short</strong>, <strong>char</strong> and <strong>byte</strong>.</p>\n\n<h2>Bitwise Shift Operators</h2>\n\n<p>They are classified into two categories left shift and the right shift.</p>\n\n<ul>\n<li><strong>Left Shift(&lt;&lt;):</strong> The left shift operator, shifts all of the bits in value to the left a specified number of times. Syntax: value &lt;&lt; num. Here num specifies the number of position to left-shift the value in value. That is, the &lt;&lt; moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each shift left, the high-order bit is shifted out (and ignored/lost), and a zero is brought in on the right. This means that when a left shift is applied to 32-bit compiler, bits are lost once they are shifted past bit position 31. If the compiler is of 64-bit then bits are lost after bit position 63.</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/27o7v.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/27o7v.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Output: 6</strong>, Here the binary representation of 3 is 0...0011(considering 32-bit system) so when it shifted one time the leading zero is ignored/lost and all the rest 31 bits shifted to left. And zero is added at the end. So it became 0...0110, the decimal representation of this number is 6.</p>\n\n<ul>\n<li>In the case of a negative number:</li>\n</ul>\n\n<h2><a href=\"https://i.stack.imgur.com/qNbnd.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qNbnd.jpg\" alt=\"Code for Negative number.\"></a></h2>\n\n<p><strong>Output: -2</strong>, In java negative number, is represented by 2's complement. SO, -1 represent by 2^32-1 which is equivalent to 1....11(Considering 32-bit system). When shifted one time the leading bit is ignored/lost and the rest 31 bits shifted to left and zero is added at the last. So it becomes, 11...10 and its decimal equivalent is -2.\nSo, I think you get enough knowledge about the left shift and how its work.</p>\n\n<ul>\n<li><strong>Right Shift(>>):</strong> The right shift operator, shifts all of the bits in value to the right a specified of times. Syntax: value >> num, num specifies the number of positions to right-shift the value in value. That is, the >> moves/shift all of the bits in the specified value of the right the number of bit positions specified by num.\nThe following code fragment shifts the value 35 to the right by two positions:</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/q0x8v.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q0x8v.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Output: 8</strong>, As a binary representation of 35 in a 32-bit system is 00...00100011, so when we right shift it two times the first 30 leading bits are moved/shifts to the right side and the two low-order bits are lost/ignored and two zeros are added at the leading bits. So, it becomes 00....00001000, the decimal equivalent of this binary representation is 8.\nOr there is a <strong>simple mathematical trick</strong> to find out the output of this following code: To generalize this we can say that, x >> y = floor(x/pow(2,y)). Consider the above example, x=35 and y=2 so, 35/2^2 = 8.75 and if we take the floor value then the answer is 8.</p>\n\n<p><a href=\"https://i.stack.imgur.com/FM2nG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FM2nG.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cDTEe.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cDTEe.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>But remember one thing this trick is fine for small values of y if you take the large values of y it gives you incorrect output.</p>\n\n<ul>\n<li>In the case of a negative number:\nBecause of the negative numbers the Right shift operator works in two modes signed and unsigned. In signed right shift operator (>>), In case of a positive number, it fills the leading bits with 0. And In case of a negative number, it fills leading bits with 1. To keep the sign. This is called 'sign extension'. </li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/LpHwK.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LpHwK.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Output: -5</strong>, As I explained above the compiler stores the negative value as 2's complement. So, -10 is represented as 2^32-10 and in binary representation considering 32-bit system 11....0110. When we shift/ move one time the first 31 leading bits got shifted in the right side and the low-order bit got lost/ignored. So, it becomes 11...0011 and the decimal representation of this number is -5 (How I know the sign of number? because the leading bit is 1).\nIt is interesting to note that if you shift -1 right, the result always remains -1 since sign extension keeps bringing in more ones in the high-order bits.</p>\n\n<ul>\n<li><strong>Unsigned Right Shift(>>>):</strong> This operator also shifts bits to the right. The difference between signed and unsigned is the latter fills the leading bits with 1 if the number is negative and the former fills zero in either case. Now the question arises why we need unsigned right operation if we get the desired output by signed right shift operator. Understand this with an example, If you are shifting something that does not represent a numeric value, you may not want sign extension to take place. This situation is common when you are working with pixel-based values and graphics. In these cases, you will generally want to shift a zero into the high-order bit no matter what it's the initial value was.</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/0w3xZ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0w3xZ.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Output: 2147483647</strong>, Because -2 is represented as 11...10 in a 32-bit system. When we shift the bit by one, the first 31 leading bit is moved/shifts in right and the low-order bit is lost/ignored and the zero is added to the leading bit. So, it becomes 011...1111 (2^31-1) and its decimal equivalent is 2147483647.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)... At a core level, what does bit-shifting (`<<`, `>>`, `>>>`) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.
The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators. The Operators ------------- * `>>` is the arithmetic (or signed) right shift operator. * `>>>` is the logical (or unsigned) right shift operator. * `<<` is the left shift operator, and meets the needs of both logical and arithmetic shifts. All of these operators can be applied to integer values (`int`, `long`, possibly `short` and `byte` or `char`). In some languages, applying the shift operators to any datatype smaller than `int` automatically resizes the operand to be an `int`. Note that `<<<` is not an operator, because it would be redundant. Also note that **C and C++ do not distinguish between the right shift operators**. They provide only the `>>` operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators. (In all mainstream C and C++ implementations including GCC and Clang/LLVM, `>>` on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not *undefined*, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers *is* undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.) --- Left shift (<<) --------------- Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit `int` would be: ``` 00000000 00000000 00000000 00000110 ``` Shifting this bit pattern to the left one position (`6 << 1`) would result in the number 12: ``` 00000000 00000000 00000000 00001100 ``` As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So `6 << 1` is equivalent to `6 * 2`, and `6 << 3` is equivalent to `6 * 8`. A good optimizing compiler will replace multiplications with shifts when possible. ### Non-circular shifting Please note that these are *not* circular shifts. Shifting this value to the left by one position (`3,758,096,384 << 1`): ``` 11100000 00000000 00000000 00000000 ``` results in 3,221,225,472: ``` 11000000 00000000 00000000 00000000 ``` The digit that gets shifted "off the end" is lost. It does not wrap around. --- Logical right shift (>>>) ------------------------- A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12: ``` 00000000 00000000 00000000 00001100 ``` to the right by one position (`12 >>> 1`) will get back our original 6: ``` 00000000 00000000 00000000 00000110 ``` So we see that shifting to the right is equivalent to division by powers of 2. ### Lost bits are gone However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern: ``` 00111000 00000000 00000000 00000110 ``` to the left 4 positions (`939,524,102 << 4`), we get 2,147,483,744: ``` 10000000 00000000 00000000 01100000 ``` and then shifting back (`(939,524,102 << 4) >>> 4`) we get 134,217,734: ``` 00001000 00000000 00000000 00000110 ``` We cannot get back our original value once we have lost bits. --- Arithmetic right shift (>>) =========================== The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the *sign* bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving. For example, if we interpret this bit pattern as a negative number: ``` 10000000 00000000 00000000 01100000 ``` we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us: ``` 11111000 00000000 00000000 00000110 ``` or the number -134,217,722. So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.
141,545
<p>Let's say I have a class that has a member called data which is a list. </p> <p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p> <p>What's your technique for doing this?</p> <p>Do you just check the type by looking at <code>__class__</code>?</p> <p>Is there some trick I might be missing?</p> <p>I'm used to C++ where overloading by argument type is easy. </p>
[ { "answer_id": 141565, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:</p>\n\n<pre><code>def __init__ (self, filename):\n if isinstance (filename, basestring):\n # filename is a string\n else:\n # try to convert to a list\n self.path = list (filename)\n</code></pre>\n" }, { "answer_id": 141570, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "<p>You probably want the <code>isinstance</code> builtin function:</p>\n\n<pre><code>self.data = data if isinstance(data, list) else self.parse(data)\n</code></pre>\n" }, { "answer_id": 141571, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 2, "selected": false, "text": "<p>You should use isinstance</p>\n\n<pre><code>isinstance(...)\n isinstance(object, class-or-type-or-tuple) -&gt; bool\n\n Return whether an object is an instance of a class or of a subclass thereof.\n With a type as second argument, return whether that is the object's type.\n The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n isinstance(x, A) or isinstance(x, B) or ... (etc.).\n</code></pre>\n" }, { "answer_id": 141700, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": -1, "selected": false, "text": "<p>OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.</p>\n\n<pre><code>class MyData:\n def __init__(self, data):\n self.myList = []\n if isinstance(data, tuple):\n for i in data:\n self.myList.append(i)\n else:\n self.myList = data\n\n def GetData(self):\n print self.myList\n</code></pre>\n\n<p>a = [1,2]</p>\n\n<p>b = (2,3)</p>\n\n<p>c = MyData(a)</p>\n\n<p>d = MyData(b)</p>\n\n<p>c.GetData()</p>\n\n<p>d.GetData()</p>\n\n<p>[1, 2]</p>\n\n<p>[2, 3]</p>\n" }, { "answer_id": 141777, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 10, "selected": true, "text": "<p>A much neater way to get 'alternate constructors' is to use classmethods. For instance:</p>\n\n<pre><code>&gt;&gt;&gt; class MyData:\n... def __init__(self, data):\n... \"Initialize MyData from a sequence\"\n... self.data = data\n... \n... @classmethod\n... def fromfilename(cls, filename):\n... \"Initialize MyData from a file\"\n... data = open(filename).readlines()\n... return cls(data)\n... \n... @classmethod\n... def fromdict(cls, datadict):\n... \"Initialize MyData from a dict's items\"\n... return cls(datadict.items())\n... \n&gt;&gt;&gt; MyData([1, 2, 3]).data\n[1, 2, 3]\n&gt;&gt;&gt; MyData.fromfilename(\"/tmp/foobar\").data\n['foo\\n', 'bar\\n', 'baz\\n']\n&gt;&gt;&gt; MyData.fromdict({\"spam\": \"ham\"}).data\n[('spam', 'ham')]\n</code></pre>\n\n<p>The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with <code>isinstance(x, basestring)</code> is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.</p>\n" }, { "answer_id": 212130, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 5, "selected": false, "text": "<p>Excellent question. I've tackled this problem as well, and while I agree that \"factories\" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:</p>\n\n<p>Here's a sample (this is a <code>read</code> method and not a constructor, but the idea is the same):</p>\n\n<pre><code>def read(self, str=None, filename=None, addr=0):\n \"\"\" Read binary data and return a store object. The data\n store is also saved in the interal 'data' attribute.\n\n The data can either be taken from a string (str \n argument) or a file (provide a filename, which will \n be read in binary mode). If both are provided, the str \n will be used. If neither is provided, an ArgumentError \n is raised.\n \"\"\"\n if str is None:\n if filename is None:\n raise ArgumentError('Please supply a string or a filename')\n\n file = open(filename, 'rb')\n str = file.read()\n file.close()\n ...\n ... # rest of code\n</code></pre>\n\n<p>The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:</p>\n\n<pre><code>obj.read(filename=\"blob.txt\")\n</code></pre>\n\n<p>And to read it from a string, I say:</p>\n\n<pre><code>obj.read(str=\"\\x34\\x55\")\n</code></pre>\n\n<p>This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex</p>\n" }, { "answer_id": 10218436, "author": "Ben", "author_id": 1322906, "author_profile": "https://Stackoverflow.com/users/1322906", "pm_score": 4, "selected": false, "text": "<p>Quick and dirty fix</p>\n\n<pre><code>class MyData:\n def __init__(string=None,list=None):\n if string is not None:\n #do stuff\n elif list is not None:\n #do other stuff\n else:\n #make data empty\n</code></pre>\n\n<p>Then you can call it with</p>\n\n<pre><code>MyData(astring)\nMyData(None, alist)\nMyData()\n</code></pre>\n" }, { "answer_id": 23415425, "author": "ankostis", "author_id": 548792, "author_profile": "https://Stackoverflow.com/users/548792", "pm_score": -1, "selected": false, "text": "<p>Why don't you go even more pythonic?\n</p>\n\n<pre><code>class AutoList:\ndef __init__(self, inp):\n try: ## Assume an opened-file...\n self.data = inp.read()\n except AttributeError:\n try: ## Assume an existent filename...\n with open(inp, 'r') as fd:\n self.data = fd.read()\n except:\n self.data = inp ## Who cares what that might be?\n</code></pre>\n" }, { "answer_id": 26018762, "author": "Fydo", "author_id": 385025, "author_profile": "https://Stackoverflow.com/users/385025", "pm_score": -1, "selected": false, "text": "<p>My preferred solution is:</p>\n\n<pre><code>class MyClass:\n _data = []\n __init__(self,data=None):\n # do init stuff\n if not data: return\n self._data = list(data) # list() copies the list, instead of pointing to it.\n</code></pre>\n\n<p>Then invoke it with either <code>MyClass()</code> or <code>MyClass([1,2,3])</code>.</p>\n\n<p>Hope that helps. Happy Coding!</p>\n" }, { "answer_id": 49936625, "author": "carton.swing", "author_id": 5765458, "author_profile": "https://Stackoverflow.com/users/5765458", "pm_score": 5, "selected": false, "text": "<p>with python3, you can use <a href=\"https://github.com/dabeaz/python-cookbook/blob/master/src/9/multiple_dispatch_with_function_annotations/example1.py\" rel=\"noreferrer\">Implementing Multiple Dispatch with Function Annotations</a> as Python Cookbook wrote:</p>\n\n<pre><code>import time\n\n\nclass Date(metaclass=MultipleMeta):\n def __init__(self, year:int, month:int, day:int):\n self.year = year\n self.month = month\n self.day = day\n\n def __init__(self):\n t = time.localtime()\n self.__init__(t.tm_year, t.tm_mon, t.tm_mday)\n</code></pre>\n\n<p>and it works like:</p>\n\n<pre><code>&gt;&gt;&gt; d = Date(2012, 12, 21)\n&gt;&gt;&gt; d.year\n2012\n&gt;&gt;&gt; e = Date()\n&gt;&gt;&gt; e.year\n2018\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179/" ]
Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list. What's your technique for doing this? Do you just check the type by looking at `__class__`? Is there some trick I might be missing? I'm used to C++ where overloading by argument type is easy.
A much neater way to get 'alternate constructors' is to use classmethods. For instance: ``` >>> class MyData: ... def __init__(self, data): ... "Initialize MyData from a sequence" ... self.data = data ... ... @classmethod ... def fromfilename(cls, filename): ... "Initialize MyData from a file" ... data = open(filename).readlines() ... return cls(data) ... ... @classmethod ... def fromdict(cls, datadict): ... "Initialize MyData from a dict's items" ... return cls(datadict.items()) ... >>> MyData([1, 2, 3]).data [1, 2, 3] >>> MyData.fromfilename("/tmp/foobar").data ['foo\n', 'bar\n', 'baz\n'] >>> MyData.fromdict({"spam": "ham"}).data [('spam', 'ham')] ``` The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with `isinstance(x, basestring)` is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.
141,560
<p>I have a loop that looks something like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } </code></pre> <p>This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return <code>null</code> if there is an error, so I put the loop inside a <code>try...catch</code> block, like this:</p> <pre><code>try { for (int i = 0; i &lt; max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } </code></pre> <p>But then I also thought of putting the <code>try...catch</code> block inside the loop, like this:</p> <pre><code>for (int i = 0; i &lt; max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } </code></pre> <p>Is there any reason, performance or otherwise, to prefer one over the other?</p> <hr> <p><strong>Edit:</strong> The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?</p>
[ { "answer_id": 141577, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 2, "selected": false, "text": "<p>In your examples there is no functional difference. I find your first example more readable.</p>\n" }, { "answer_id": 141589, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 6, "selected": false, "text": "<p><strong>Performance</strong>: as <a href=\"https://stackoverflow.com/questions/141560#141652\">Jeffrey</a> said in his reply, in Java it doesn't make much difference.</p>\n\n<p><strong>Generally</strong>, for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not. </p>\n\n<p>In your example you returned upon catching an exception. In that case, I'd put the try/catch around the loop. If you simply want to catch a bad value but carry on processing, put it inside. </p>\n\n<p><strong>The third way</strong>: You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop. Making the exception handling isolated to the loop itself!</p>\n\n<pre><code>class Parsing\n{\n public static Float MyParseFloat(string inputValue)\n {\n try\n {\n return Float.parseFloat(inputValue);\n }\n catch ( NumberFormatException e )\n {\n return null;\n }\n }\n\n // .... your code\n for(int i = 0; i &lt; max; i++) \n {\n String myString = ...;\n Float myNum = Parsing.MyParseFloat(myString);\n if ( myNum == null ) return;\n myFloats[i] = (float) myNum;\n }\n}\n</code></pre>\n" }, { "answer_id": 141590, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "<p>You should prefer the outer version over the inner version. This is just a specific version of the rule, move anything outside the loop that you can move outside the loop. Depending on the IL compiler and JIT compiler your two versions may or may not end up with different performance characteristics.</p>\n\n<p>On another note you should probably look at float.TryParse or Convert.ToFloat.</p>\n" }, { "answer_id": 141592, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.</p>\n\n<hr>\n\n<p>Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory &amp; processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.</p>\n" }, { "answer_id": 141595, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.</p>\n" }, { "answer_id": 141608, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 2, "selected": false, "text": "<p>If its an all-or-nothing fail, then the first format makes sense. If you want to be able to process/return all the non-failing elements, you need to use the second form. Those would be my basic criteria for choosing between the methods. Personally, if it is all-or-nothing, I wouldn't use the second form.</p>\n" }, { "answer_id": 141618, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 1, "selected": false, "text": "<p>setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.</p>\n\n<p>depending on the number of iterations, performance difference will likely be negligible.</p>\n\n<p>However i agree with the others that having it outside the loop make the loop body look cleaner.</p>\n\n<p>If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.</p>\n" }, { "answer_id": 141652, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 7, "selected": false, "text": "<p>PERFORMANCE:</p>\n\n<p>There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.</p>\n\n<p>Here's a reference: <a href=\"http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html\" rel=\"noreferrer\">http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html</a></p>\n\n<p>The table is described about half-way down.</p>\n" }, { "answer_id": 142451, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>The whole point of exceptions is to encourage the first style: letting the error handling be consolidated and handled once, not immediately at every possible error site.</p>\n" }, { "answer_id": 149610, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 7, "selected": true, "text": "<p>All right, after <a href=\"https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141652\">Jeffrey L Whitledge said</a> that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:</p>\n\n<pre><code>public class Main {\n\n private static final int NUM_TESTS = 100;\n private static int ITERATIONS = 1000000;\n // time counters\n private static long inTime = 0L;\n private static long aroundTime = 0L;\n\n public static void main(String[] args) {\n for (int i = 0; i &lt; NUM_TESTS; i++) {\n test();\n ITERATIONS += 1; // so the tests don't always return the same number\n }\n System.out.println(\"Inside loop: \" + (inTime/1000000.0) + \" ms.\");\n System.out.println(\"Around loop: \" + (aroundTime/1000000.0) + \" ms.\");\n }\n public static void test() {\n aroundTime += testAround();\n inTime += testIn();\n }\n public static long testIn() {\n long start = System.nanoTime();\n Integer i = tryInLoop();\n long ret = System.nanoTime() - start;\n System.out.println(i); // don't optimize it away\n return ret;\n }\n public static long testAround() {\n long start = System.nanoTime();\n Integer i = tryAroundLoop();\n long ret = System.nanoTime() - start;\n System.out.println(i); // don't optimize it away\n return ret;\n }\n public static Integer tryInLoop() {\n int count = 0;\n for (int i = 0; i &lt; ITERATIONS; i++) {\n try {\n count = Integer.parseInt(Integer.toString(count)) + 1;\n } catch (NumberFormatException ex) {\n return null;\n }\n }\n return count;\n }\n public static Integer tryAroundLoop() {\n int count = 0;\n try {\n for (int i = 0; i &lt; ITERATIONS; i++) {\n count = Integer.parseInt(Integer.toString(count)) + 1;\n }\n return count;\n } catch (NumberFormatException ex) {\n return null;\n }\n }\n}\n</code></pre>\n\n<p>I checked the resulting bytecode using javap to make sure that nothing got inlined.</p>\n\n<p>The results showed that, assuming insignificant JIT optimizations, <strong>Jeffrey is correct</strong>; there is absolutely <strong>no performance difference on Java 6, Sun client VM</strong> (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.</p>\n\n<p>Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or <a href=\"https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141589\">Ray Hayes's way</a>.</p>\n" }, { "answer_id": 155000, "author": "Matt N", "author_id": 20605, "author_profile": "https://Stackoverflow.com/users/20605", "pm_score": 4, "selected": false, "text": "<p>I agree with all the performance and readability posts. However, there are cases where it really does matter. A couple other people mentioned this, but it might be easier to see with examples.</p>\n\n<p>Consider this slightly modified example:</p>\n\n<pre><code>public static void main(String[] args) {\n String[] myNumberStrings = new String[] {\"1.2345\", \"asdf\", \"2.3456\"};\n ArrayList asNumbers = parseAll(myNumberStrings);\n}\n\npublic static ArrayList parseAll(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n\n for(int i = 0; i &lt; numberStrings.length; i++){\n myFloats.add(new Float(numberStrings[i]));\n }\n return myFloats;\n}\n</code></pre>\n\n<p>If you want the parseAll() method to return null if there are any errors (like the original example), you'd put the try/catch on the outside like this:</p>\n\n<pre><code>public static ArrayList parseAll1(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n try{\n for(int i = 0; i &lt; numberStrings.length; i++){\n myFloats.add(new Float(numberStrings[i]));\n }\n } catch (NumberFormatException nfe){\n //fail on any error\n return null;\n }\n return myFloats;\n}\n</code></pre>\n\n<p>In reality, you should probably return an error here instead of null, and generally I don't like having multiple returns, but you get the idea.</p>\n\n<p>On the other hand, if you want it to just ignore the problems, and parse whatever Strings it can, you'd put the try/catch on the inside of the loop like this:</p>\n\n<pre><code>public static ArrayList parseAll2(String[] numberStrings){\n ArrayList myFloats = new ArrayList();\n\n for(int i = 0; i &lt; numberStrings.length; i++){\n try{\n myFloats.add(new Float(numberStrings[i]));\n } catch (NumberFormatException nfe){\n //don't add just this one\n }\n }\n\n return myFloats;\n}\n</code></pre>\n" }, { "answer_id": 156325, "author": "Kyle Dyer", "author_id": 24011, "author_profile": "https://Stackoverflow.com/users/24011", "pm_score": 1, "selected": false, "text": "<p>put it inside. You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw. Think about what would be interesting to you in the debugger at this point in the program. </p>\n\n<p>Consider: </p>\n\n<pre><code>try {\n // parse\n} catch (NumberFormatException nfe){\n throw new RuntimeException(\"Could not parse as a Float: [\" + myString + \n \"] found at index: \" + i, nfe);\n} \n</code></pre>\n\n<p>In the time of need you will really appreciate an exception like this with as much information in it as possible.</p>\n" }, { "answer_id": 172153, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "<p>I's like to add my own <code>0.02c</code> about two competing considerations when looking at the general problem of where to position exception handling:</p>\n\n<ol>\n<li><p>The \"wider\" the responsibility of the <code>try-catch</code> block (i.e. outside the loop in your case) means that when changing the code at some later point, you may mistakenly add a line which is handled by your existing <code>catch</code> block; possibly unintentionally. In your case, this is less likely because you are explicitly catching a <code>NumberFormatException</code></p></li>\n<li><p>The \"narrower\" the responsibility of the <code>try-catch</code> block, the more difficult refactoring becomes. Particularly when (as in your case) you are executing a \"non-local\" instruction from within the <code>catch</code> block (the <code>return null</code> statement). </p></li>\n</ol>\n" }, { "answer_id": 177556, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 1, "selected": false, "text": "<p>That depends on the failure handling. If you just want to skip the error elements, try inside:</p>\n\n<pre><code>for(int i = 0; i &lt; max; i++) {\n String myString = ...;\n try {\n float myNum = Float.parseFloat(myString);\n myFloats[i] = myNum;\n } catch (NumberFormatException ex) {\n --i;\n }\n}\n</code></pre>\n\n<p>In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.</p>\n" }, { "answer_id": 188076, "author": "Ogre Psalm33", "author_id": 13140, "author_profile": "https://Stackoverflow.com/users/13140", "pm_score": 1, "selected": false, "text": "<p>I'll put my $0.02 in. Sometimes you wind up needing to add a \"finally\" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:</p>\n\n<pre><code>try {\n for(int i = 0; i &lt; max; i++) {\n String myString = ...;\n float myNum = Float.parseFloat(myString);\n dbConnection.update(\"MY_FLOATS\",\"INDEX\",i,\"VALUE\",myNum);\n }\n} catch (NumberFormatException ex) {\n return null;\n} finally {\n dbConnection.release(); // Always release DB connection, even if transaction fails.\n}\n</code></pre>\n\n<p>Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.</p>\n" }, { "answer_id": 544351, "author": "user19810", "author_id": 19810, "author_profile": "https://Stackoverflow.com/users/19810", "pm_score": 3, "selected": false, "text": "<p>As already mentioned, the performance is the same. However, user experience isn't necessarily identical. In the first case, you'll fail fast (i.e. after the first error), however if you put the try/catch block inside the loop, you can capture all the errors that would be created for a given call to the method. When parsing an array of values from strings where you expect some formatting errors, there are definitely cases where you'd like to be able to present all the errors to the user so that they don't need to try and fix them one by one.</p>\n" }, { "answer_id": 2427868, "author": "Jeff Hill", "author_id": 291801, "author_profile": "https://Stackoverflow.com/users/291801", "pm_score": 1, "selected": false, "text": "<p>Another aspect not mentioned in the above is the fact that every try-catch has <em>some</em> impact on the stack, which can have implications for recursive methods.</p>\n\n<p>If method \"outer()\" calls method \"inner()\" (which may call itself recursively), try to locate the try-catch in method \"outer()\" if possible. A simple \"stack crash\" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.</p>\n\n<p>In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.</p>\n" }, { "answer_id": 12212219, "author": "Gunnar Forsgren - Mobimation", "author_id": 345759, "author_profile": "https://Stackoverflow.com/users/345759", "pm_score": 2, "selected": false, "text": "<p>As long as you are aware of what you need to accomplish in the loop you could put the try catch outside the loop. But it is important to understand that the loop will then end as soon as the exception occurs and that may not always be what you want. This is actually a very common error in Java based software. People need to process a number of items, such as emptying a queue, and falsely rely on an outer try/catch statement handling all possible exceptions. They could also be handling only a specific exception inside the loop and not expect any other exception to occur.\nThen if an exception occurs that is not handled inside the loop then the loop will be \"preemted\", it ends possibly prematurely and the outer catch statement handles the exception.</p>\n\n<p>If the loop had as its role in life to empty a queue then that loop very likely could end before that queue was really emptied. Very common fault.</p>\n" }, { "answer_id": 33435986, "author": "seBaka28", "author_id": 4252577, "author_profile": "https://Stackoverflow.com/users/4252577", "pm_score": 4, "selected": false, "text": "<p>While performance might be the same and what \"looks\" better is very subjective, there is still a pretty big difference in functionality. Take the following example:</p>\n\n<pre><code>Integer j = 0;\n try {\n while (true) {\n ++j;\n\n if (j == 20) { throw new Exception(); }\n if (j%4 == 0) { System.out.println(j); }\n if (j == 40) { break; }\n }\n } catch (Exception e) {\n System.out.println(\"in catch block\");\n }\n</code></pre>\n\n<p>The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.</p>\n\n<p>Before any details, here the other example:</p>\n\n<pre><code>Integer i = 0;\n while (true) {\n try {\n ++i;\n\n if (i == 20) { throw new Exception(); }\n if (i%4 == 0) { System.out.println(i); }\n if (i == 40) { break; }\n\n } catch (Exception e) { System.out.println(\"in catch block\"); }\n }\n</code></pre>\n\n<p>Same logic as above, only difference is that the try/catch block is now inside the while loop. </p>\n\n<p>Here comes the output (while in try/catch):</p>\n\n<pre><code>4\n8\n12 \n16\nin catch block\n</code></pre>\n\n<p>And the other output (try/catch in while):</p>\n\n<pre><code>4\n8\n12\n16\nin catch block\n24\n28\n32\n36\n40\n</code></pre>\n\n<p>There you have quite a significant difference: </p>\n\n<p>while in try/catch breaks out of the loop</p>\n\n<p>try/catch in while keeps the loop active</p>\n" }, { "answer_id": 53904627, "author": "Junaid Pathan", "author_id": 8304176, "author_profile": "https://Stackoverflow.com/users/8304176", "pm_score": 2, "selected": false, "text": "<p>If you want to catch Exception for each iteration, or check at what iteration Exception is thrown and catch every Exceptions in an iteration, place try...catch inside the loop. This will not break the loop if Exception occurs and you can catch every Exception in each iteration throughout the loop.</p>\n<p>If you want to break the loop and examine the Exception whenever thrown, use try...catch out of the loop. This will break the loop and execute statements after catch (if any).</p>\n<p>It all depends on your need. I prefer using try...catch inside the loop while deploying as, if Exception occurs, the results aren't ambiguous and loop will not break and execute completely.</p>\n" }, { "answer_id": 54680065, "author": "surendrapanday", "author_id": 9851598, "author_profile": "https://Stackoverflow.com/users/9851598", "pm_score": 2, "selected": false, "text": "<p>My perspective would be try/catch blocks are necessary to insure proper exception handling, but creating such blocks has performance implications. Since, Loops contain intensive repetitive computations, it is not recommended to put try/catch blocks inside loops. Additionally, it seems where this condition occurs, it is often \"Exception\" or \"RuntimeException\" which is caught. RuntimeException being caught in code should be avoided. Again, if if you work in a big company it's essential to log that exception properly, or stop runtime exception to happen. Whole point of this description is <code>PLEASE AVOID USING TRY-CATCH BLOCKS IN LOOPS</code></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13531/" ]
I have a loop that looks something like this: ``` for (int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } ``` This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return `null` if there is an error, so I put the loop inside a `try...catch` block, like this: ``` try { for (int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } ``` But then I also thought of putting the `try...catch` block inside the loop, like this: ``` for (int i = 0; i < max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } ``` Is there any reason, performance or otherwise, to prefer one over the other? --- **Edit:** The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?
All right, after [Jeffrey L Whitledge said](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141652) that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark: ``` public class Main { private static final int NUM_TESTS = 100; private static int ITERATIONS = 1000000; // time counters private static long inTime = 0L; private static long aroundTime = 0L; public static void main(String[] args) { for (int i = 0; i < NUM_TESTS; i++) { test(); ITERATIONS += 1; // so the tests don't always return the same number } System.out.println("Inside loop: " + (inTime/1000000.0) + " ms."); System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms."); } public static void test() { aroundTime += testAround(); inTime += testIn(); } public static long testIn() { long start = System.nanoTime(); Integer i = tryInLoop(); long ret = System.nanoTime() - start; System.out.println(i); // don't optimize it away return ret; } public static long testAround() { long start = System.nanoTime(); Integer i = tryAroundLoop(); long ret = System.nanoTime() - start; System.out.println(i); // don't optimize it away return ret; } public static Integer tryInLoop() { int count = 0; for (int i = 0; i < ITERATIONS; i++) { try { count = Integer.parseInt(Integer.toString(count)) + 1; } catch (NumberFormatException ex) { return null; } } return count; } public static Integer tryAroundLoop() { int count = 0; try { for (int i = 0; i < ITERATIONS; i++) { count = Integer.parseInt(Integer.toString(count)) + 1; } return count; } catch (NumberFormatException ex) { return null; } } } ``` I checked the resulting bytecode using javap to make sure that nothing got inlined. The results showed that, assuming insignificant JIT optimizations, **Jeffrey is correct**; there is absolutely **no performance difference on Java 6, Sun client VM** (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test. Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or [Ray Hayes's way](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141589).
141,562
<p>I can select all the distinct values in a column in the following ways:</p> <ul> <li><code>SELECT DISTINCT column_name FROM table_name;</code></li> <li><code>SELECT column_name FROM table_name GROUP BY column_name;</code></li> </ul> <p>But how do I get the row count from that query? Is a subquery required?</p>
[ { "answer_id": 141573, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": false, "text": "<pre><code>select Count(distinct columnName) as columnNameCount from tableName \n</code></pre>\n" }, { "answer_id": 141574, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 10, "selected": true, "text": "<p>You can use the <code>DISTINCT</code> keyword within the <a href=\"http://technet.microsoft.com/en-us/library/ms175997%28v=sql.90%29.aspx\" rel=\"noreferrer\"><code>COUNT</code></a> aggregate function:</p>\n\n<pre><code>SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name\n</code></pre>\n\n<p>This will count only the distinct values for that column.</p>\n" }, { "answer_id": 141579, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;\n</code></pre>\n\n<p>you've got to count that distinct col, then give it an alias.</p>\n" }, { "answer_id": 142111, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 5, "selected": false, "text": "<p>Be aware that Count() ignores null values, so if you need to allow for null as its own distinct value you can do something tricky like:</p>\n\n<pre><code>select count(distinct my_col)\n + count(distinct Case when my_col is null then 1 else null end)\nfrom my_table\n/\n</code></pre>\n" }, { "answer_id": 261344, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>select count(*) from \n(\nSELECT distinct column1,column2,column3,column4 FROM abcd\n) T\n</code></pre>\n\n<p>This will give count of distinct group of columns.</p>\n" }, { "answer_id": 13101647, "author": "Paul James", "author_id": 1779496, "author_profile": "https://Stackoverflow.com/users/1779496", "pm_score": 8, "selected": false, "text": "<p>This will give you BOTH the distinct column values and the count of each value. I usually find that I want to know both pieces of information.</p>\n\n<pre><code>SELECT [columnName], count([columnName]) AS CountOf\nFROM [tableName]\nGROUP BY [columnName]\n</code></pre>\n" }, { "answer_id": 27538172, "author": "Paul Pena", "author_id": 4372574, "author_profile": "https://Stackoverflow.com/users/4372574", "pm_score": -1, "selected": false, "text": "<p>Count(distinct({fieldname})) is redundant</p>\n\n<p>Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]</p>\n" }, { "answer_id": 30338143, "author": "xchiltonx", "author_id": 1422486, "author_profile": "https://Stackoverflow.com/users/1422486", "pm_score": 5, "selected": false, "text": "<p>An sql sum of column_name's unique values and sorted by the frequency:</p>\n\n<pre><code>SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY 2 DESC;\n</code></pre>\n" }, { "answer_id": 53926812, "author": "Nilesh Shinde", "author_id": 6260075, "author_profile": "https://Stackoverflow.com/users/6260075", "pm_score": 1, "selected": false, "text": "<p>Using following SQL we can get the <strong>distinct column value count</strong> in Oracle 11g.</p>\n<pre><code>select count(distinct(Column_Name)) from TableName\n</code></pre>\n" }, { "answer_id": 56459021, "author": "Nitika Chopra", "author_id": 7534013, "author_profile": "https://Stackoverflow.com/users/7534013", "pm_score": 0, "selected": false, "text": "<pre><code>select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true\n</code></pre>\n<p>You can use this query, to count different/distinct data.</p>\n" }, { "answer_id": 60293936, "author": "Alper", "author_id": 12829409, "author_profile": "https://Stackoverflow.com/users/12829409", "pm_score": 1, "selected": false, "text": "<p>After MS SQL Server 2012, you can use window function too.</p>\n<pre><code>SELECT column_name, COUNT(column_name) OVER (PARTITION BY column_name) \nFROM table_name\nGROUP BY column_name\n</code></pre>\n" }, { "answer_id": 67828388, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 1, "selected": false, "text": "<p>To do this in <a href=\"https://prestodb.io/docs/0.217/functions/window.html\" rel=\"nofollow noreferrer\">Presto using <code>OVER</code></a>:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT DISTINCT my_col,\n count(*) OVER (PARTITION BY my_col\n ORDER BY my_col) AS num_rows\nFROM my_tbl\n</code></pre>\n<p>Using this <code>OVER</code> based approach is of course optional. In the above SQL, I found specifying <code>DISTINCT</code> and <code>ORDER BY</code> to be necessary.</p>\n<p>Caution: As per the <a href=\"https://docs.aws.amazon.com/athena/latest/ug/performance-tuning.html#performance-tuning-use-more-efficient-functions\" rel=\"nofollow noreferrer\">docs</a>, using <code>GROUP BY</code> may be more efficient.</p>\n" }, { "answer_id": 72966995, "author": "Deva44", "author_id": 6766414, "author_profile": "https://Stackoverflow.com/users/6766414", "pm_score": 0, "selected": false, "text": "<p>Without using DISTINCT this is how we could do it-</p>\n<pre><code>SELECT COUNT(C)\nFROM (SELECT COUNT(column_name) as C\nFROM table_name\nGROUP BY column_name)\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3757/" ]
I can select all the distinct values in a column in the following ways: * `SELECT DISTINCT column_name FROM table_name;` * `SELECT column_name FROM table_name GROUP BY column_name;` But how do I get the row count from that query? Is a subquery required?
You can use the `DISTINCT` keyword within the [`COUNT`](http://technet.microsoft.com/en-us/library/ms175997%28v=sql.90%29.aspx) aggregate function: ``` SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name ``` This will count only the distinct values for that column.
141,598
<p>I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: <code>School</code>, <code>Course</code>, and <code>Student</code>, which are defined as follows:</p> <pre><code>class School { List&lt;Course&gt; Courses; List&lt;Student&gt; Students; } class Course { string Number; string Description; } class Student { string Name; List&lt;Course&gt; EnrolledIn; } </code></pre> <p>I would store such a data structure in XML like so:</p> <pre><code>&lt;School&gt; &lt;Courses&gt; &lt;Course Number="ENGL 101" Description="English I" /&gt; &lt;Course Number="CHEM 102" Description="General Inorganic Chemistry" /&gt; &lt;Course Number="MATH 103" Description="Trigonometry" /&gt; &lt;/Courses&gt; &lt;Students&gt; &lt;Student Name="Jack"&gt; &lt;EnrolledIn&gt; &lt;Course Number="CHEM 102" /&gt; &lt;Course Number="MATH 103" /&gt; &lt;/EnrolledIn&gt; &lt;/Student&gt; &lt;Student Name="Jill"&gt; &lt;EnrolledIn&gt; &lt;Course Number="ENGL 101" /&gt; &lt;Course Number="MATH 103" /&gt; &lt;/EnrolledIn&gt; &lt;/Student&gt; &lt;/Students&gt; &lt;/School&gt; </code></pre> <p>With the XML ordered this way, I can parse <code>Courses</code> first. Then, when I parse <code>Students</code>, I can look up each <code>Course</code> listed in <code>EnrolledIn</code> (by its <code>Number</code>) in the <code>School.Courses</code> list. This will give me an object reference to add to the <code>EnrolledIn</code> list in <code>Student</code>. If <code>Students</code>, however, comes <em>before</em> <code>Courses</code>, such a lookup to get a object reference is not possible. (Since <code>School.Courses</code> has not yet been populated.)</p> <p>So what are the best practices for storing relational data in XML? - Should I enforce that <code>Courses</code> must always come before <code>Students</code>? - Should I tolerate any ordering and create a stub <code>Course</code> object whenever I encounter one I have not yet seen? (To be expanded when the definition of the <code>Course</code> is eventually reached later.) - Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing <code>Save</code> and <code>Load</code> methods on all my business objects and doing all this manually using <code>System.Xml.XmlDocument</code> and its associated classes.)</p> <p>I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.</p>
[ { "answer_id": 141624, "author": "Instantsoup", "author_id": 9861, "author_profile": "https://Stackoverflow.com/users/9861", "pm_score": 0, "selected": false, "text": "<p>From experience, XML isn't the best to store relational data. Have you investigated <a href=\"http://www.yaml.org/\" rel=\"nofollow noreferrer\" title=\"YAML\">YAML</a>? Do you have the option?</p>\n\n<p>If you don't, a safe way would be to have a strict DTD for the XML and enforce that way. You could also, as you suggest, keep a hash of objects created. That way if a Student creates a Course you keep that Course around for future updating when the tag is hit.</p>\n\n<p>Also remember you can use XPath queries to access specific nodes directly, so you can enforce parsing of courses first regardless of position in the XML document. (making a more complete answer, thanks to dacracot)</p>\n" }, { "answer_id": 141638, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>While you can specify order of child elements using a &lt;xsd:sequence>, by requiring child objects to come in specific order you make your system less flexible (i.e., harder to update using notepad).</p>\n\n<p>Best thing to do is to parse out all your data, then perform what actions you need to do. Don't act during the parse.</p>\n\n<hr>\n\n<p>Obviously, the design of the XML and the data behind it precludes serializing a single POCO to XML. You need to control the serialization and deserialization logic in order to unhook and re-hook objects together.</p>\n\n<p>I'd suggest creating a custom serializer that builds the xml representation of this object graph. It can thereby control not only the order of serialization, but also handle situations where nodes aren't in the expected order. You could do other things such as adding custom attributes to use for linking objects together which don't exist as public properties on the objects being serialized.</p>\n\n<p>Creating the xml would be as simple as iterating over your objects a few times, building up collections of XElements with the expected representation of the objects as xml. When you're done you can stitch them together into an XDocument and grab the xml from it. You can make multiple passes over the xml on the reverse side to re-create your object graph and restore all references.</p>\n" }, { "answer_id": 141665, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "<p>The order is not usually important in XML. In this case the <code>Courses</code> could come after <code>Students</code>. You parse the XML and then you make your queries on the entire data.</p>\n" }, { "answer_id": 141677, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 0, "selected": false, "text": "<p>XML is definitely not a friendly place for relational data.</p>\n\n<p>If you absolutely need to do this, then I'd recommend a funky inverted kind of logic.</p>\n\n<p>In your example, you've got Schools, which offers many courses, taken by many students.</p>\n\n<p>Your XML might follow as such:</p>\n\n<pre><code>&lt;School&gt;\n &lt;Students&gt;\n &lt;Student Name=\"Jack\"&gt;\n &lt;EnrolledIn&gt;\n &lt;Course Number=\"CHEM 102\" Description=\"General Inorganic Chemistry\" /&gt;\n &lt;Course Number=\"MATH 103\" Description=\"Trigonometry\" /&gt;\n &lt;/EnrolledIn&gt;\n &lt;/Student&gt;\n &lt;Student Name=\"Jill\"&gt;\n &lt;EnrolledIn&gt;\n &lt;Course Number=\"ENGL 101\" Description=\"English I\" /&gt;\n &lt;Course Number=\"MATH 103\" Description=\"Trigonometry\" /&gt;\n &lt;/EnrolledIn&gt;\n &lt;/Student&gt;\n &lt;/Students&gt;\n&lt;/School&gt;\n</code></pre>\n\n<p>This obviously isn't the least repetitive way to do this (it's relational data!), but it's easily parse-able.</p>\n" }, { "answer_id": 141687, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 3, "selected": true, "text": "<p>Don't think in SQL or relational when working with XML, because there are no order constraints. </p>\n\n<p>You can however query using XPath to any portion of the XML document at any time. You want the courses first, then \"//Courses/Course\". You want the students enrollments next, then \"//Students/Student/EnrolledIn/Course\".</p>\n\n<p>The bottom line being... just because XML is stored in a file, don't get caught thinking all your accesses are serial.</p>\n\n<hr>\n\n<p>I posted a separate question, <a href=\"https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml\">\"Can XPath do a foreign key lookup across two subtrees of an XML?\"</a>, in order to clarify my position. The solution shows how you can use XPath to make relational queries against XML data.</p>\n" }, { "answer_id": 141723, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>Node ordering is only important if you need to do forward-only processing of the data, e.g. using an XmlReader or a SAX parser. If you're going to read the XML into a DOM before processing it (which you are if you're using XmlDocument), node order doesn't really matter. What matters more is that the XML be structured so that you can query it with XPath efficiently, i.e. without having to use \"//\".</p>\n\n<p>If you take a look at the schema that the DataSetGenerator produces, you'll see that there's no ordering associated with the DataTable-level elements. It may be that ADO processes elements in some sequence not represented in the schema (e.g. one DataTable at a time), or it may be that ADO does forward-only processing and doesn't enforce relational constraints until the DataSet is fully read. I don't know. But it's clear that ADO doesn't couple the processing order to the document order.</p>\n\n<p>(And yes, you can specify the order of child elements in an XML schema; that's what xs:sequence does. If you don't want node order to be enforced, you use an unbounded xs:choice.)</p>\n" }, { "answer_id": 141746, "author": "Jim C", "author_id": 21706, "author_profile": "https://Stackoverflow.com/users/21706", "pm_score": 0, "selected": false, "text": "<p>You could also use two XML files, one for courses and a second for students. Open and parse the first before you do the second.</p>\n" }, { "answer_id": 141874, "author": "Nerdfest", "author_id": 7855, "author_profile": "https://Stackoverflow.com/users/7855", "pm_score": 0, "selected": false, "text": "<p>I's been a while, but I seem to remember doing a base collection of 'things' in one part of an xml file, and referring to them in another using the schema features <em>keyref</em> and <em>refer</em>. I found a few examples <a href=\"http://www.datypic.com/books/defxmlschema/chapter17.html\" rel=\"nofollow noreferrer\">here</a>. My apologies if this is not what you're looking for.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: `School`, `Course`, and `Student`, which are defined as follows: ``` class School { List<Course> Courses; List<Student> Students; } class Course { string Number; string Description; } class Student { string Name; List<Course> EnrolledIn; } ``` I would store such a data structure in XML like so: ``` <School> <Courses> <Course Number="ENGL 101" Description="English I" /> <Course Number="CHEM 102" Description="General Inorganic Chemistry" /> <Course Number="MATH 103" Description="Trigonometry" /> </Courses> <Students> <Student Name="Jack"> <EnrolledIn> <Course Number="CHEM 102" /> <Course Number="MATH 103" /> </EnrolledIn> </Student> <Student Name="Jill"> <EnrolledIn> <Course Number="ENGL 101" /> <Course Number="MATH 103" /> </EnrolledIn> </Student> </Students> </School> ``` With the XML ordered this way, I can parse `Courses` first. Then, when I parse `Students`, I can look up each `Course` listed in `EnrolledIn` (by its `Number`) in the `School.Courses` list. This will give me an object reference to add to the `EnrolledIn` list in `Student`. If `Students`, however, comes *before* `Courses`, such a lookup to get a object reference is not possible. (Since `School.Courses` has not yet been populated.) So what are the best practices for storing relational data in XML? - Should I enforce that `Courses` must always come before `Students`? - Should I tolerate any ordering and create a stub `Course` object whenever I encounter one I have not yet seen? (To be expanded when the definition of the `Course` is eventually reached later.) - Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing `Save` and `Load` methods on all my business objects and doing all this manually using `System.Xml.XmlDocument` and its associated classes.) I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.
Don't think in SQL or relational when working with XML, because there are no order constraints. You can however query using XPath to any portion of the XML document at any time. You want the courses first, then "//Courses/Course". You want the students enrollments next, then "//Students/Student/EnrolledIn/Course". The bottom line being... just because XML is stored in a file, don't get caught thinking all your accesses are serial. --- I posted a separate question, ["Can XPath do a foreign key lookup across two subtrees of an XML?"](https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml), in order to clarify my position. The solution shows how you can use XPath to make relational queries against XML data.
141,599
<p>What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. </p> <p>Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?</p> <p>Example:</p> <pre><code>svn -v log -d 2008-9-23:2008-9:24 &gt; report.txt </code></pre>
[ { "answer_id": 141619, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 7, "selected": true, "text": "<p>Very first hit by google for \"svn log date range\": <a href=\"http://svn.haxx.se/users/archive-2006-08/0737.shtml\" rel=\"noreferrer\">http://svn.haxx.se/users/archive-2006-08/0737.shtml</a></p>\n\n<blockquote>\n <p>So <code>svn log &lt;url&gt; -r\n {2008-09-19}:{2008-09-26}</code> will get\n all changes for the past week,\n including today.</p>\n</blockquote>\n\n<p>And if you want to generate reports for a repo, there's a solution: <a href=\"http://statsvn.org/index.html\" rel=\"noreferrer\">Statsvn</a>.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 141631, "author": "Rob", "author_id": 22832, "author_profile": "https://Stackoverflow.com/users/22832", "pm_score": 4, "selected": false, "text": "<p>You can use dates the same as you can use revision numbers. The syntax is {yyyy-mm-dd}. So, for all changes between 12:00am on September 23 and 12am on September 24, do:</p>\n\n<pre><code>svn log -v -r {2008-09-23}:{2008-09-24} &gt; report.txt\n</code></pre>\n" }, { "answer_id": 141653, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 3, "selected": false, "text": "<p>You can do this:</p>\n\n<pre><code>svn log -r{2008-9-23}:{2008-9-24} &gt; report.txt\n</code></pre>\n\n<p>Add a <code>--xml</code> before the <code>-r</code> if you want ot get the output in xml format for \"easier\" post processing. </p>\n" }, { "answer_id": 9633372, "author": "MikeBeaton", "author_id": 795690, "author_profile": "https://Stackoverflow.com/users/795690", "pm_score": 3, "selected": false, "text": "<p>The -v is important if you want to see a list of the actual changes (over and above the log messages... if any! ;) )</p>\n" }, { "answer_id": 18710975, "author": "Harikrushna", "author_id": 1587594, "author_profile": "https://Stackoverflow.com/users/1587594", "pm_score": 3, "selected": false, "text": "<pre><code>svn log -r '{2013-9-23}:{2013-9-24}'\n</code></pre>\n\n<p>This is might be the correct syntex.<br>\nQuotes are required to get the correct results.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp? Example: ``` svn -v log -d 2008-9-23:2008-9:24 > report.txt ```
Very first hit by google for "svn log date range": <http://svn.haxx.se/users/archive-2006-08/0737.shtml> > > So `svn log <url> -r > {2008-09-19}:{2008-09-26}` will get > all changes for the past week, > including today. > > > And if you want to generate reports for a repo, there's a solution: [Statsvn](http://statsvn.org/index.html). HTH
141,606
<p>Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material.</p> <p>Here's an example:</p> <blockquote> <p><strong>Using The Best Product in the World to Create World Peace</strong></p> <p><em>Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.</em></p> <p> The Best Product in the World ... </p> </blockquote> <p>Now, I don't want the note to show up in <strike>Google</strike> search engine results, only the title and the content that follows the note. Is there any way I can achieve this?</p> <p>Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like <a href="http://www.wordpress.com" rel="nofollow noreferrer">Wordpress.com</a>?</p> <p><strong>Update</strong></p> <p>Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly.</p>
[ { "answer_id": 141613, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 0, "selected": false, "text": "<p>I just came to think of something. I guess I could render the note with JavaScript once the page is loaded?</p>\n" }, { "answer_id": 141615, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 2, "selected": false, "text": "<p>Javascript. If you add your content to the site using javascript, it won't be picked up by the search engines. It's even appropriate, because you're enhancing the site, not providing additional content. Any other method of performing this will stick the content into the page. Even if you hide it using styling, it will still be in the text. Depending on your page structure, that might not be possible anyway.</p>\n" }, { "answer_id": 141616, "author": "Paul Mrozowski", "author_id": 3656, "author_profile": "https://Stackoverflow.com/users/3656", "pm_score": 3, "selected": true, "text": "<p>You can build that portion of the content dynamically using Javascript. </p>\n\n<p>For example:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n &lt;div id=\"dynContent\"&gt;\n &lt;/div&gt;\n Rest of the content here.\n&lt;/body&gt;\n&lt;script language='javascript' type='text/javascript'&gt;\n var dyn = document.getElementById('dynContent');\n dyn.innerHTML = \"Put the dynamic content here\";\n&lt;/script&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>If you're really stuck, you can just go old school and reference an image that has your text as part of it. It's not particularly \"accessibility-friendly\" though.</p>\n" }, { "answer_id": 141617, "author": "apandit", "author_id": 6128, "author_profile": "https://Stackoverflow.com/users/6128", "pm_score": 0, "selected": false, "text": "<p>Hmm... maybe you can create a &lt;div&gt; with position: absolute; z-index: 99 (should be greater than 1); top: 0px; -- this should put the note at the top of the page but you could place the actual code near the bottom... search engines go linearly through the source and not by position I'd assume.</p>\n\n<p>Edit: And this is fail if you decide you want it located somewhere else since this is an absolute location-- it'll just break down.. :\\. go with the javascript</p>\n" }, { "answer_id": 141636, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 0, "selected": false, "text": "<p>Any attempt to hide content is going to have side-effects regarding accessibility and compatibility. It seems that all you are attempting to do is control the snippet that search engines display, in which case <a href=\"http://googlewebmastercentral.blogspot.com/2007/09/improve-snippets-with-meta-description.html\" rel=\"nofollow noreferrer\">you are better off providing an appropriate meta element description</a>.</p>\n" }, { "answer_id": 141794, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 1, "selected": false, "text": "<p>You can try to improve the text that's shown on the search results page by providing a <a href=\"http://en.wikipedia.org/wiki/Meta_tag#The_description_attribute\" rel=\"nofollow noreferrer\">meta description tag</a>. However, It's the search engine's prerogative to display whatever it chooses, which is not necessarily the first 'n' words on the page.</p>\n" }, { "answer_id": 141817, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": 0, "selected": false, "text": "<p>I'm familiar with how WordPress.com works, but if you can put in stuff like Digg, Delicious badges on your blog as a third part added stuff.. then you might have a chance to do the same trick these badges uses, they inject dynamic content in your page , and you can figure how they are doing it and do the same with your custom content</p>\n" }, { "answer_id": 142222, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 2, "selected": false, "text": "<p>If you can use an iframe, then place the content on a static html page and use the meta tag in it's head to tell the search engines to ignore it. Since it's a seperate page, google etc.. should ignore it.</p>\n\n<p>meta tag:</p>\n\n<pre><code>&lt;meta name=\"robots\" content=\"noindex, nofollow\"&gt;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material. Here's an example: > > **Using The Best Product in the World to Create World Peace** > > > *Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.* > > > > The Best Product in the World ... > > > > Now, I don't want the note to show up in Google search engine results, only the title and the content that follows the note. Is there any way I can achieve this? Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like [Wordpress.com](http://www.wordpress.com)? **Update** Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly.
You can build that portion of the content dynamically using Javascript. For example: ``` <html> <body> <div id="dynContent"> </div> Rest of the content here. </body> <script language='javascript' type='text/javascript'> var dyn = document.getElementById('dynContent'); dyn.innerHTML = "Put the dynamic content here"; </script> </html> ``` If you're really stuck, you can just go old school and reference an image that has your text as part of it. It's not particularly "accessibility-friendly" though.
141,611
<p>I have an Enum like this</p> <pre><code>package com.example; public enum CoverageEnum { COUNTRY, REGIONAL, COUNTY } </code></pre> <p>I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:</p> <pre><code>&lt;c:forEach var="type" items="&lt;%= com.example.CoverageEnum.values() %&gt;"&gt; ${type} &lt;/c:forEach&gt; </code></pre> <p>But can I achieve the same thing without scriptlets?</p> <p>Cheers, Don</p>
[ { "answer_id": 141658, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "<p>If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:</p>\n\n<pre><code>&lt;c:forEach var=\"type\" items=\"${myprefix:getValues()}\"&gt;\n</code></pre>\n\n<p>EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:</p>\n\n<pre><code>public static &lt;T extends Enum&lt;T&gt;&gt; Enum&lt;T&gt;[] getValues(Class&lt;T&gt; klass) {\n try { \n Method m = klass.getMethod(\"values\", null);\n Object obj = m.invoke(null, null);\n return (Enum&lt;T&gt;[])obj;\n } catch(Exception ex) {\n //shouldn't happen...\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 3857480, "author": "Ted Pennings", "author_id": 134583, "author_profile": "https://Stackoverflow.com/users/134583", "pm_score": 3, "selected": false, "text": "<p>If you're using Spring MVC, you can accomplish your goal with the following syntactic blessing:</p>\n\n<pre><code> &lt;form:form method=\"post\" modelAttribute=\"cluster\" cssClass=\"form\" enctype=\"multipart/form-data\"&gt;\n &lt;form:label path=\"clusterType\"&gt;Cluster Type\n &lt;form:errors path=\"clusterType\" cssClass=\"error\" /&gt;\n &lt;/form:label&gt;\n &lt;form:select items=\"${clusterTypes}\" var=\"type\" path=\"clusterType\"/&gt;\n &lt;/form:form&gt;\n</code></pre>\n\n<p>where your model attribute (ie, bean/data entity to populate) is named cluster and you have already populated the model with an enum array of values named clusterTypes. The <code>&lt;form:error&gt;</code> part is very much optional. </p>\n\n<p>In Spring MVC land, you can also auto-populate <code>clusterTypes</code> into your model like this</p>\n\n<pre><code>@ModelAttribute(\"clusterTypes\")\npublic MyClusterType[] populateClusterTypes() {\n return MyClusterType.values();\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have an Enum like this ``` package com.example; public enum CoverageEnum { COUNTRY, REGIONAL, COUNTY } ``` I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this: ``` <c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>"> ${type} </c:forEach> ``` But can I achieve the same thing without scriptlets? Cheers, Don
If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become: ``` <c:forEach var="type" items="${myprefix:getValues()}"> ``` EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this: ``` public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) { try { Method m = klass.getMethod("values", null); Object obj = m.invoke(null, null); return (Enum<T>[])obj; } catch(Exception ex) { //shouldn't happen... return null; } } ```
141,612
<p>I'm working on database designs for a project management system as personal project and I've hit a snag.</p> <p>I want to implement a ticket system and I want the tickets to look like the <a href="http://trac.edgewall.org/ticket/6436" rel="noreferrer">tickets in Trac</a>. What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)</p> <p>Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. </p> <p><strong>Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.</strong> </p>
[ { "answer_id": 141621, "author": "Pete Karl II", "author_id": 22491, "author_profile": "https://Stackoverflow.com/users/22491", "pm_score": 1, "selected": false, "text": "<p>I'd say create some kind of event listening class that you ping every time something happens within your system &amp; places a description of the event in a database.</p>\n\n<p>It should store basic who/what/where/when/what info.</p>\n\n<p>sorting through that project-events table should get you the info you want.</p>\n" }, { "answer_id": 141634, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<p>Are you after a database mechanism like this?</p>\n\n<pre><code> CREATE OR REPLACE TRIGGER history$yourTable\n BEFORE UPDATE ON yourTable\n FOR EACH ROW\n BEGIN\n INSERT INTO\n history\n VALUES\n (\n :old.field1,\n :old.field2,\n :old.field3,\n :old.field4,\n :old.field5,\n :old.field6\n );\n END;\n /\n SHOW ERRORS TRIGGER history$yourTable\n</code></pre>\n" }, { "answer_id": 141651, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 5, "selected": true, "text": "<p>I have implemented pure record change data using a \"thin\" design:</p>\n\n<pre><code>RecordID Table Column OldValue NewValue\n-------- ----- ------ -------- --------\n</code></pre>\n\n<p>You may not want to use \"Table\" and \"Column\", but rather \"Object\" and \"Property\", and so forth, depending on your design.</p>\n\n<p>This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the \"Table\" and \"Column\" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter.</p>\n\n<p><strong>EDIT</strong>: several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a \"Transaction\" table with a datetime, user and other info, and a \"TransactionID\" column, so the design would look like this:</p>\n\n<pre><code>CHANGE LOG TABLE:\nRecordID Table Column OldValue NewValue TransactionID\n-------- ----- ------ -------- -------- -------------\n\nTRANSACTION LOG TABLE:\nTransactionID UserID TransactionDate\n------------- ------ ---------------\n</code></pre>\n" }, { "answer_id": 141657, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 0, "selected": false, "text": "<p>One possible solution is storing a copy of the ticket in a history table with the user that made the change. </p>\n\n<p>However, this will store alot of extra data and require alot of processing to create the view that Trac shows.</p>\n" }, { "answer_id": 141664, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 2, "selected": false, "text": "<p>As far as not storing a lot of extra data, I can't think of any good ways to do that. You have to store every revision in order to see changes.</p>\n\n<p>Here is one solution I have seen, although I'm not sure if it's the best one. Have a primary key, say <code>id</code> which points to a particular revision. also have <code>ticket_number</code> and <code>revision_date</code> fields. <code>ticket_number</code> does not change when you revise a ticket, but <code>id</code> and <code>revision_date</code> do. Then, depending on the context, you can get a particular revision, or the latest revision of a particular ticket, using <a href=\"http://jan.kneschke.de/projects/mysql/groupwise-max\" rel=\"nofollow noreferrer\">groupwise max</a>.</p>\n" }, { "answer_id": 141812, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 2, "selected": false, "text": "<p>I did something like this. I have a table called LoggableEntity that contains: ID (PK).</p>\n<p>Then I have EntityLog table that contains information about changes made to a loggableentity (record): ID (PK), EntityID (FK to LoggableEntity.ID), ChangedBy (username who made a change), ChangedAt (smalldatetime when the change happened), Type (enum: Create, Delete, Update), Details (memo field containing what has changed - might be an XML with serialized details).</p>\n<p>Now every table (entity) that I want to be tracked is &quot;derived&quot; from the LoggableEntity table - what it means that for example Customer has FK to LoggableEntity table.</p>\n<p>Now my DAL code takes care of populating EntityLog table everytime there is a change made to a customer record. Everytime when it sees that entity class is a loggableentity then it adds new change record into entitylog table.</p>\n<p>So here is my table structure:</p>\n<pre class=\"lang-text prettyprint-override\"><code>┌──────────────────┐ ┌──────────────────┐\n│ LoggableEntity │ │ EntityLog │\n│ ──────────────── │ │ ──────────────── │\n│ (PK) ID │ ◀──┐ │ (PK) ID │\n└──────────────────┘ └───── │ (FK) LoggableID │\n ▲ │ ... │\n │ └──────────────────┘\n┌──────────────────┐\n│ Customer │\n│ ──────────────── │\n│ (PK) ID │\n│ (FK) LoggableID │\n│ ... │\n└──────────────────┘\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
I'm working on database designs for a project management system as personal project and I've hit a snag. I want to implement a ticket system and I want the tickets to look like the [tickets in Trac](http://trac.edgewall.org/ticket/6436). What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing) Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. **Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.**
I have implemented pure record change data using a "thin" design: ``` RecordID Table Column OldValue NewValue -------- ----- ------ -------- -------- ``` You may not want to use "Table" and "Column", but rather "Object" and "Property", and so forth, depending on your design. This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the "Table" and "Column" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter. **EDIT**: several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a "Transaction" table with a datetime, user and other info, and a "TransactionID" column, so the design would look like this: ``` CHANGE LOG TABLE: RecordID Table Column OldValue NewValue TransactionID -------- ----- ------ -------- -------- ------------- TRANSACTION LOG TABLE: TransactionID UserID TransactionDate ------------- ------ --------------- ```
141,620
<p>i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.</p> <p>i have this code in the application.rb:</p> <p>def check_role @user = session[:user]</p> <p>if @user.role.can_access_admin.nil? || [email protected]_access_admin render :text => "your current role does not allow access to the administration area." return end end</p> <p>and then i have this code inside one of the admin controllers:</p> <p>class Admin::BlogsController &lt; ApplicationController before_filter :check_role</p> <p>def list @blogList = Blog.find(:all) end end</p> <p>and when i try to view the list action i get this error:</p> <p>undefined method 'role' for user...</p> <p>anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)</p>
[ { "answer_id": 141721, "author": "MatthewFord", "author_id": 21596, "author_profile": "https://Stackoverflow.com/users/21596", "pm_score": 4, "selected": true, "text": "<p>just a guess but it seems that your session[:user] is just storing the id, you need to do:</p>\n\n<pre><code>@user = User.find(session[:user])\n</code></pre>\n\n<p>or something along those lines to fetch the user from the database (along with its associations). </p>\n\n<p>It's good to do the above in a before filter too.</p>\n" }, { "answer_id": 141728, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 1, "selected": false, "text": "<p>Is session[:user] holding the user? or the user_id? You may need a lookup before you call .role.</p>\n" }, { "answer_id": 142365, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 1, "selected": false, "text": "<p>Also, if you're using ActsAsAuthenticated or RestfulAuthentication or their brethren you can also use the <code>current_user</code> method they supply.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before\_filter to check that the user of the user in the session has a 'can\_access\_admin' flag. i have this code in the application.rb: def check\_role @user = session[:user] if @user.role.can\_access\_admin.nil? || [email protected]\_access\_admin render :text => "your current role does not allow access to the administration area." return end end and then i have this code inside one of the admin controllers: class Admin::BlogsController < ApplicationController before\_filter :check\_role def list @blogList = Blog.find(:all) end end and when i try to view the list action i get this error: undefined method 'role' for user... anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)
just a guess but it seems that your session[:user] is just storing the id, you need to do: ``` @user = User.find(session[:user]) ``` or something along those lines to fetch the user from the database (along with its associations). It's good to do the above in a before filter too.
141,626
<p>I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it?</p> <p>The old win32 browser control had a Before_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control.</p>
[ { "answer_id": 144354, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 4, "selected": true, "text": "<p>That functionality isn't exposed by the .NET WebBrowser control. Fortunately, that control is mostly a wrapper around the 'old' control. This means you can subscribe to the BeforeNavigate2 event you know and love(?) using something like the following (after adding a reference to SHDocVw to your project):</p>\n\n<pre><code>Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer)\nAddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2\n</code></pre>\n\n<p>...and do whatever you want to the PostData inside that event:</p>\n\n<pre><code>Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _\n ByRef Flags As Object, ByRef TargetFrameName As Object, _\n ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean)\n Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData)\nEnd Sub\n</code></pre>\n\n<p>One important caveat: the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserbase.activexinstance.aspx\" rel=\"noreferrer\">documentation for the WebBrowser.ActiveXInstance property</a> states that \"This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.\". In other words: your use of the property may break your app at any point in the future, for example when the Framework people decide to implement their own browser component, instead of wrapping the existing SHDocVw COM one.</p>\n\n<p>So, you'll not want to put this code in anything you ship to a lot of people and/or anything that should remain working for many Framework versions to come...</p>\n" }, { "answer_id": 12002267, "author": "Vadim Zin4uk", "author_id": 1329308, "author_profile": "https://Stackoverflow.com/users/1329308", "pm_score": 3, "selected": false, "text": "<h2>C# version</h2>\n\n<pre><code> /// &lt;summary&gt;\n /// Fires before navigation occurs in the given object (on either a window or frameset element).\n /// &lt;/summary&gt;\n /// &lt;param name=\"pDisp\"&gt;Object that evaluates to the top level or frame WebBrowser object corresponding to the navigation.&lt;/param&gt;\n /// &lt;param name=\"url\"&gt;String expression that evaluates to the URL to which the browser is navigating.&lt;/param&gt;\n /// &lt;param name=\"Flags\"&gt;Reserved. Set to zero.&lt;/param&gt;\n /// &lt;param name=\"TargetFrameName\"&gt;String expression that evaluates to the name of the frame in which the resource will be displayed, or Null if no named frame is targeted for the resource.&lt;/param&gt;\n /// &lt;param name=\"PostData\"&gt;Data to send to the server if the HTTP POST transaction is being used.&lt;/param&gt;\n /// &lt;param name=\"Headers\"&gt;Value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code.&lt;/param&gt;\n /// &lt;param name=\"Cancel\"&gt;Boolean value that the container can set to True to cancel the navigation operation, or to False to allow it to proceed.&lt;/param&gt;\n private delegate void BeforeNavigate2(object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel);\n\n private void Form1_Load(object sender, EventArgs e)\n {\n dynamic d = webBrowser1.ActiveXInstance;\n\n d.BeforeNavigate2 += new BeforeNavigate2((object pDisp,\n ref dynamic url,\n ref dynamic Flags,\n ref dynamic TargetFrameName,\n ref dynamic PostData,\n ref dynamic Headers,\n ref bool Cancel) =&gt; {\n\n // Do something with PostData\n });\n }\n</code></pre>\n\n<p><br></p>\n\n<h2>C# WPF version</h2>\n\n<p>Keep the above, but replace:</p>\n\n<pre><code> dynamic d = webBrowser1.ActiveXInstance;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code> using System.Reflection;\n ...\n PropertyInfo prop = typeof(System.Windows.Controls.WebBrowser).GetProperty(\"ActiveXInstance\", BindingFlags.NonPublic | BindingFlags.Instance);\n MethodInfo getter = prop.GetGetMethod(true);\n dynamic d = getter.Invoke(webBrowser1, null);\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it? The old win32 browser control had a Before\_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control.
That functionality isn't exposed by the .NET WebBrowser control. Fortunately, that control is mostly a wrapper around the 'old' control. This means you can subscribe to the BeforeNavigate2 event you know and love(?) using something like the following (after adding a reference to SHDocVw to your project): ``` Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer) AddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2 ``` ...and do whatever you want to the PostData inside that event: ``` Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _ ByRef Flags As Object, ByRef TargetFrameName As Object, _ ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean) Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData) End Sub ``` One important caveat: the [documentation for the WebBrowser.ActiveXInstance property](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserbase.activexinstance.aspx) states that "This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.". In other words: your use of the property may break your app at any point in the future, for example when the Framework people decide to implement their own browser component, instead of wrapping the existing SHDocVw COM one. So, you'll not want to put this code in anything you ship to a lot of people and/or anything that should remain working for many Framework versions to come...
141,630
<p>If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this:</p> <pre><code>Version:0.9 StartHTML:00000147 EndHTML:00000516 StartFragment:00000181 EndFragment:00000480 SourceURL:http://en.wikipedia.org/wiki/Herodotus &lt;html&gt;&lt;body&gt; &lt;!--StartFragment--&gt;Additional details have been garnered from the &lt;i&gt;&lt;a href="http://en.wikipedia.org/wiki/Suda" title="Suda"&gt;Suda&lt;/a&gt;&lt;/i&gt;, an 11th-century encyclopaedia of the &lt;a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium"&gt;Byzantium&lt;/a&gt; which likely took its information from traditional accounts.&lt;!--EndFragment--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format" rel="nofollow noreferrer">According to MSDN</a>, this is "CF_HTML" formatted clipboard data. Is it the same on OS X and Linux systems? </p> <p>Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application?</p>
[ { "answer_id": 141727, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>It is Microsoft specific, don't expect to see the same information in other OSes.<br>\nNote that you get the same format when you copy a fragment from IE.</p>\n\n<p>I am not sure what you mean by \"webpage-to-webpage drag and drop operation\". To drop where? A textarea?</p>\n\n<p>I don't know C#, but in C/C++ applications, you have to use OpenClipboard and related Win32 APIs to get this info. In particular, GetClipboardData(CF_HTML) allows you to get this info (can be obtained in plain text too, for example, or Unicode data, etc.).</p>\n" }, { "answer_id": 141854, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>A WinForms app can use <a href=\"http://msdn.microsoft.com/en-us/library/944ft9kf.aspx\" rel=\"nofollow noreferrer\">Clipboard.GetText</a> to get it. I don't think there is a way to do it in a webpage, however.</p>\n" }, { "answer_id": 57678502, "author": "Markus", "author_id": 1332129, "author_profile": "https://Stackoverflow.com/users/1332129", "pm_score": 2, "selected": false, "text": "<p>For completeness, here is the P/Invoke Win32 API code to get RAW clipboard data</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n//--------------------------------------------------------------------------------\nhttp://metadataconsulting.blogspot.com/2019/06/How-to-get-HTML-from-the-Windows-system-clipboard-directly-using-PInvoke-Win32-Native-methods-avoiding-bad-funny-characters.html\n//--------------------------------------------------------------------------------\n\npublic class ClipboardHelper\n{\n #region Win32 Native PInvoke\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n private static extern uint RegisterClipboardFormat(string lpszFormat);\n //or specifically - private static extern uint RegisterClipboardFormatA(string lpszFormat);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool IsClipboardFormatAvailable(uint format);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n private static extern IntPtr GetClipboardData(uint uFormat);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseClipboard();\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n private static extern IntPtr GlobalLock(IntPtr hMem);\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool GlobalUnlock(IntPtr hMem);\n\n [DllImport(\"Kernel32.dll\", SetLastError = true)]\n private static extern int GlobalSize(IntPtr hMem);\n\n #endregion\n\n public static string GetHTMLWin32Native()\n {\n\n string strHTMLUTF8 = string.Empty; \n uint CF_HTML = RegisterClipboardFormatA(\"HTML Format\");\n if (CF_HTML != null || CF_HTML == 0)\n return null;\n\n if (!IsClipboardFormatAvailable(CF_HTML))\n return null;\n\n try\n {\n if (!OpenClipboard(IntPtr.Zero))\n return null;\n\n IntPtr handle = GetClipboardData(CF_HTML);\n if (handle == IntPtr.Zero)\n return null;\n\n IntPtr pointer = IntPtr.Zero;\n\n try\n {\n pointer = GlobalLock(handle);\n if (pointer == IntPtr.Zero)\n return null;\n\n uint size = GlobalSize(handle);\n byte[] buff = new byte[size];\n\n Marshal.Copy(pointer, buff, 0, (int)size);\n\n strHTMLUTF8 = System.Text.Encoding.UTF8.GetString(buff);\n }\n finally\n {\n if (pointer != IntPtr.Zero)\n GlobalUnlock(handle);\n }\n }\n finally\n {\n CloseClipboard();\n }\n\n return strHTMLUTF8; \n }\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965/" ]
If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this: ``` Version:0.9 StartHTML:00000147 EndHTML:00000516 StartFragment:00000181 EndFragment:00000480 SourceURL:http://en.wikipedia.org/wiki/Herodotus <html><body> <!--StartFragment-->Additional details have been garnered from the <i><a href="http://en.wikipedia.org/wiki/Suda" title="Suda">Suda</a></i>, an 11th-century encyclopaedia of the <a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium">Byzantium</a> which likely took its information from traditional accounts.<!--EndFragment--> </body> </html> ``` [According to MSDN](https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format), this is "CF\_HTML" formatted clipboard data. Is it the same on OS X and Linux systems? Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application?
For completeness, here is the P/Invoke Win32 API code to get RAW clipboard data ``` using System; using System.Runtime.InteropServices; using System.Text; //-------------------------------------------------------------------------------- http://metadataconsulting.blogspot.com/2019/06/How-to-get-HTML-from-the-Windows-system-clipboard-directly-using-PInvoke-Win32-Native-methods-avoiding-bad-funny-characters.html //-------------------------------------------------------------------------------- public class ClipboardHelper { #region Win32 Native PInvoke [DllImport("User32.dll", SetLastError = true)] private static extern uint RegisterClipboardFormat(string lpszFormat); //or specifically - private static extern uint RegisterClipboardFormatA(string lpszFormat); [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsClipboardFormatAvailable(uint format); [DllImport("User32.dll", SetLastError = true)] private static extern IntPtr GetClipboardData(uint uFormat); [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseClipboard(); [DllImport("Kernel32.dll", SetLastError = true)] private static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("Kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalUnlock(IntPtr hMem); [DllImport("Kernel32.dll", SetLastError = true)] private static extern int GlobalSize(IntPtr hMem); #endregion public static string GetHTMLWin32Native() { string strHTMLUTF8 = string.Empty; uint CF_HTML = RegisterClipboardFormatA("HTML Format"); if (CF_HTML != null || CF_HTML == 0) return null; if (!IsClipboardFormatAvailable(CF_HTML)) return null; try { if (!OpenClipboard(IntPtr.Zero)) return null; IntPtr handle = GetClipboardData(CF_HTML); if (handle == IntPtr.Zero) return null; IntPtr pointer = IntPtr.Zero; try { pointer = GlobalLock(handle); if (pointer == IntPtr.Zero) return null; uint size = GlobalSize(handle); byte[] buff = new byte[size]; Marshal.Copy(pointer, buff, 0, (int)size); strHTMLUTF8 = System.Text.Encoding.UTF8.GetString(buff); } finally { if (pointer != IntPtr.Zero) GlobalUnlock(handle); } } finally { CloseClipboard(); } return strHTMLUTF8; } } ```
141,637
<p>I have this code:</p> <pre><code>@PersistenceContext(name="persistence/monkey", unitName="deltaflow-pu") ... @Stateless public class GahBean implements GahRemote { </code></pre> <p>But when I use this:</p> <pre><code>try{ InitialContext ic = new InitialContext(); System.out.println("Pissing me off * " + ic.lookup("java:comp/env/persistent/monkey")); Iterator e = ic.getEnvironment().values().iterator(); while ( e.hasNext() ) System.out.println("rem - " + e.next()); }catch(Exception a){ a.printStackTrace();} </code></pre> <p>I get this exception:</p> <pre><code>javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistent/monkey </code></pre> <p>If I remove the lookup the iterator doesn't have anything close to it either. What could be the problem?</p>
[ { "answer_id": 141706, "author": "arinte", "author_id": 22763, "author_profile": "https://Stackoverflow.com/users/22763", "pm_score": 0, "selected": false, "text": "<p>If I inject it by the way it works fine, but everywhere I read about that they say it isn't threadsafe to do it that way.</p>\n" }, { "answer_id": 141709, "author": "Sam Martin", "author_id": 19088, "author_profile": "https://Stackoverflow.com/users/19088", "pm_score": 1, "selected": false, "text": "<p>This could be my ignorance about JPA showing, but you appear to have \"persistence\" in some places and \"persistent\" in others. I'd start by making sure the names match.</p>\n" }, { "answer_id": 14050275, "author": "Shobith", "author_id": 1931358, "author_profile": "https://Stackoverflow.com/users/1931358", "pm_score": 0, "selected": false, "text": "<p>Check whether you have configured the data source on the server with the name persistence/monkey and check whether the name is matched in persistance.xml\nThe name is case sensitive.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
I have this code: ``` @PersistenceContext(name="persistence/monkey", unitName="deltaflow-pu") ... @Stateless public class GahBean implements GahRemote { ``` But when I use this: ``` try{ InitialContext ic = new InitialContext(); System.out.println("Pissing me off * " + ic.lookup("java:comp/env/persistent/monkey")); Iterator e = ic.getEnvironment().values().iterator(); while ( e.hasNext() ) System.out.println("rem - " + e.next()); }catch(Exception a){ a.printStackTrace();} ``` I get this exception: ``` javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistent/monkey ``` If I remove the lookup the iterator doesn't have anything close to it either. What could be the problem?
This could be my ignorance about JPA showing, but you appear to have "persistence" in some places and "persistent" in others. I'd start by making sure the names match.
141,642
<p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p> <p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html" rel="noreferrer">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p> <p>Seeing a code example for a concrete limitation would be great.</p> <p><strong>Related questions</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li> <li><a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a ‘Closure’?</a></li> <li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li> </ul>
[ { "answer_id": 141670, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:</p>\n\n<pre><code>def outer ():\n x = 1\n def inner ():\n print x\n x = 2\n return inner\nouter () ()\n</code></pre>\n\n<p>Usually just pointing out that a function has its own local variables is enough to deter such silliness.</p>\n" }, { "answer_id": 141710, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 7, "selected": true, "text": "<p>The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:</p>\n\n<pre><code>&gt;&gt;&gt; def outer(x): \n... def inner_reads():\n... # Will return outer's 'x'.\n... return x\n... def inner_writes(y):\n... # Will assign to a local 'x', not the outer 'x'\n... x = y\n... def inner_error(y):\n... # Will produce an error: 'x' is local because of the assignment,\n... # but we use it before it is assigned to.\n... tmp = x\n... x = y\n... return tmp\n... return inner_reads, inner_writes, inner_error\n... \n&gt;&gt;&gt; inner_reads, inner_writes, inner_error = outer(5)\n&gt;&gt;&gt; inner_reads()\n5\n&gt;&gt;&gt; inner_writes(10)\n&gt;&gt;&gt; inner_reads()\n5\n&gt;&gt;&gt; inner_error(10)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"&lt;stdin&gt;\", line 11, in inner_error\nUnboundLocalError: local variable 'x' referenced before assignment\n</code></pre>\n\n<p>A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that.</p>\n\n<p>You can work around this limitation in the mean time by using a mutable container type:</p>\n\n<pre><code>&gt;&gt;&gt; def outer(x):\n... x = [x]\n... def inner_reads():\n... # Will return outer's x's first (and only) element.\n... return x[0]\n... def inner_writes(y):\n... # Will look up outer's x, then mutate it. \n... x[0] = y\n... def inner_error(y):\n... # Will now work, because 'x' is not assigned to, just referenced.\n... tmp = x[0]\n... x[0] = y\n... return tmp\n... return inner_reads, inner_writes, inner_error\n... \n&gt;&gt;&gt; inner_reads, inner_writes, inner_error = outer(5)\n&gt;&gt;&gt; inner_reads()\n5\n&gt;&gt;&gt; inner_writes(10)\n&gt;&gt;&gt; inner_reads()\n10\n&gt;&gt;&gt; inner_error(15)\n10\n&gt;&gt;&gt; inner_reads()\n15\n</code></pre>\n" }, { "answer_id": 141744, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p>@John Millikin</p>\n\n<pre><code>def outer():\n x = 1 # local to `outer()`\n\n def inner():\n x = 2 # local to `inner()`\n print(x)\n x = 3\n return x\n\n def inner2():\n nonlocal x\n print(x) # local to `outer()`\n x = 4 # change `x`, it is not local to `inner2()`\n return x\n\n x = 5 # local to `outer()`\n return (inner, inner2)\n\nfor inner in outer():\n print(inner()) \n\n# -&gt; 2 3 5 4\n</code></pre>\n" }, { "answer_id": 141767, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 3, "selected": false, "text": "<p>Fixed in Python 3 via the <a href=\"https://docs.python.org/3/reference/simple_stmts.html?#nonlocal\" rel=\"nofollow noreferrer\"><code>nonlocal</code></a> statement:</p>\n\n<blockquote>\n <p>The <code>nonlocal</code> statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.</p>\n</blockquote>\n" }, { "answer_id": 141881, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<p><sub>comment for <a href=\"https://stackoverflow.com/a/141767/4279\">@Kevin Little's answer</a> to include the code example</sub></p>\n\n<p><code>nonlocal</code> does not solve completely this problem on python3.0:</p>\n\n<pre><code>x = 0 # global x\ndef outer():\n x = 1 # local to `outer`\n def inner():\n global x\n x = 2 # change global\n print(x) \n x = 3 # change global\n return x\n def inner2():\n## nonlocal x # can't use `nonlocal` here\n print(x) # prints global\n## x = 4 # can't change `x` here\n return x\n x = 5\n return (inner, inner2)\n\nfor inner in outer():\n print(inner())\n# -&gt; 2 3 3 3\n</code></pre>\n\n<p>On the other hand:</p>\n\n<pre><code>x = 0\ndef outer():\n x = 1 # local to `outer`\n def inner():\n## global x\n x = 2\n print(x) # local to `inner` \n x = 3 \n return x\n def inner2():\n nonlocal x\n print(x)\n x = 4 # local to `outer`\n return x\n x = 5\n return (inner, inner2)\n\nfor inner in outer():\n print(inner())\n# -&gt; 2 3 5 4\n</code></pre>\n\n<p>it works on python3.1-3.3</p>\n" }, { "answer_id": 989166, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>The better workaround until 3.0 is to include the variable as a defaulted parameter in the enclosed function definition:</p>\n\n<pre>\ndef f()\n x = 5\n def g(y, z, x=x):\n x = x + 1\n</pre>\n" }, { "answer_id": 6990028, "author": "mykhal", "author_id": 234248, "author_profile": "https://Stackoverflow.com/users/234248", "pm_score": 3, "selected": false, "text": "<p>A limitation (or \"limitation\") of Python closures, comparing to Javascript closures, is that it <strong>cannot</strong> be used for effective <strong>data hiding</strong></p>\n\n<h3>Javascript</h3>\n\n<pre><code>var mksecretmaker = function(){\n var secrets = [];\n var mksecret = function() {\n secrets.push(Math.random())\n }\n return mksecret\n}\nvar secretmaker = mksecretmaker();\nsecretmaker(); secretmaker()\n// privately generated secret number list\n// is practically inaccessible\n</code></pre>\n\n<h3>Python</h3>\n\n<pre><code>import random\ndef mksecretmaker():\n secrets = []\n def mksecret():\n secrets.append(random.random())\n return mksecret\n\nsecretmaker = mksecretmaker()\nsecretmaker(); secretmaker()\n# \"secrets\" are easily accessible,\n# it's difficult to hide something in Python:\nsecretmaker.__closure__[0].cell_contents # -&gt; e.g. [0.680752847190161, 0.9068475951742101]\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. Some limitations are mentioned in the [Closures in Python](http://ivan.truemesh.com/archives/000411.html) (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more. Seeing a code example for a concrete limitation would be great. **Related questions**: * [Can you explain closures (as they relate to Python)?](https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python) * [What is a ‘Closure’?](https://stackoverflow.com/questions/36636/what-is-a-closure) * [How does a javascript closure work ?](https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work)
The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only: ``` >>> def outer(x): ... def inner_reads(): ... # Will return outer's 'x'. ... return x ... def inner_writes(y): ... # Will assign to a local 'x', not the outer 'x' ... x = y ... def inner_error(y): ... # Will produce an error: 'x' is local because of the assignment, ... # but we use it before it is assigned to. ... tmp = x ... x = y ... return tmp ... return inner_reads, inner_writes, inner_error ... >>> inner_reads, inner_writes, inner_error = outer(5) >>> inner_reads() 5 >>> inner_writes(10) >>> inner_reads() 5 >>> inner_error(10) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 11, in inner_error UnboundLocalError: local variable 'x' referenced before assignment ``` A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that. You can work around this limitation in the mean time by using a mutable container type: ``` >>> def outer(x): ... x = [x] ... def inner_reads(): ... # Will return outer's x's first (and only) element. ... return x[0] ... def inner_writes(y): ... # Will look up outer's x, then mutate it. ... x[0] = y ... def inner_error(y): ... # Will now work, because 'x' is not assigned to, just referenced. ... tmp = x[0] ... x[0] = y ... return tmp ... return inner_reads, inner_writes, inner_error ... >>> inner_reads, inner_writes, inner_error = outer(5) >>> inner_reads() 5 >>> inner_writes(10) >>> inner_reads() 10 >>> inner_error(15) 10 >>> inner_reads() 15 ```
141,650
<p>I've seen <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function">the other post about this</a>, but is there a clean way of doing this in Haskell?</p> <p>As a 2nd part, can it also be done without making the function monadic?</p>
[ { "answer_id": 142269, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 1, "selected": false, "text": "<p>If your arguments are going to be natural numbers, you can do simply:</p>\n\n<pre><code>memo f = let values = map f [0..]\n in \\n -&gt; values !! n\n</code></pre>\n\n<p>However, that doesn't really help you with the stack overflowing, and it doesn't work with recursive calls. You can see some fancier solutions at <a href=\"http://www.haskell.org/haskellwiki/Memoization\" rel=\"nofollow noreferrer\">http://www.haskell.org/haskellwiki/Memoization</a>.</p>\n" }, { "answer_id": 142280, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 2, "selected": false, "text": "<p>Doing a direct translation from the more imperative languages, I came up with this.</p>\n\n<pre><code>memoize :: Ord a =&gt; (a -&gt; IO b) -&gt; IO (a -&gt; IO b)\nmemoize f =\n do r &lt;- newIORef Map.empty\n return $ \\x -&gt; do m &lt;- readIORef r\n case Map.lookup x m of\n Just y -&gt; return y\n Nothing -&gt; do y &lt;- f x\n writeIORef r (Map.insert x y m)\n return y\n</code></pre>\n\n<p>But this is somehow unsatisfactory. Also, <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/containers/Data-Map.html\" rel=\"nofollow noreferrer\">Data.Map</a> constrains the parameter to be an instance of <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Ord.html\" rel=\"nofollow noreferrer\">Ord</a>.</p>\n" }, { "answer_id": 169031, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 4, "selected": true, "text": "<p>This largely follows <a href=\"http://www.haskell.org/haskellwiki/Memoization\" rel=\"noreferrer\">http://www.haskell.org/haskellwiki/Memoization</a>.</p>\n\n<p>You want a function of type (a -> b). If it doesn't call itself, then\nyou can just write a simple wrapper that caches the return values. The \nbest way to store this mapping depends on what properties of a you can\nexploit. Ordering is pretty much a minimum. With integers \nyou can construct an infinite lazy list or tree holding the values.</p>\n\n<pre><code>type Cacher a b = (a -&gt; b) -&gt; a -&gt; b\n\npositive_list_cacher :: Cacher Int b\npositive_list_cacher f n = (map f [0..]) !! n\n</code></pre>\n\n<p>or</p>\n\n<pre><code>integer_list_cacher :: Cacher Int b\ninteger_list_cacher f n = (map f (interleave [0..] [-1, -2, ..]) !!\n index n where\n index n | n &lt; 0 = 2*abs(n) - 1\n index n | n &gt;= 0 = 2 * n\n</code></pre>\n\n<p>So, suppose it is recursive. Then you need it to call not itself, but\nthe memoized version, so you pass that in instead:</p>\n\n<pre><code>f_with_memo :: (a -&gt; b) -&gt; a -&gt; b\nf_with_memo memoed base = base_answer\nf_with_memo memoed arg = calc (memoed (simpler arg))\n</code></pre>\n\n<p>The memoized version is, of course, what we're trying to define.</p>\n\n<p>But we can start by creating a function that caches its inputs:</p>\n\n<p>We could construct one level by passing in a function that creates a \nstructure that caches values. Except we need to create the version of f\nthat <em>already has</em> the cached function passed in.</p>\n\n<p>Thanks to laziness, this is no problem:</p>\n\n<pre><code>memoize cacher f = cached where\n cached = cacher (f cached)\n</code></pre>\n\n<p>then all we need is to use it: </p>\n\n<pre><code>exposed_f = memoize cacher_for_f f\n</code></pre>\n\n<p>The article gives hints as to how to use a type class selecting on the \ninput to the function to do the above, rather than choosing an explicit \ncaching function. This can be really nice -- rather than explicitly \nconstructing a cache for each combination of input types, we can implicitly\ncombine caches for types a and b into a cache for a function taking a and b.</p>\n\n<p>One final caveat: using this lazy technique means the cache never shrinks,\nit only grows. If you instead use the IO monad, you can manage this, but\ndoing it wisely depends on usage patterns.</p>\n" }, { "answer_id": 308594, "author": "luqui", "author_id": 33796, "author_profile": "https://Stackoverflow.com/users/33796", "pm_score": 4, "selected": false, "text": "<p>The package data-memocombinators on hackage provides lots of reusable memoization routines. The basic idea is:</p>\n\n<pre><code>type Memo a = forall r. (a -&gt; r) -&gt; (a -&gt; r)\n</code></pre>\n\n<p>I.e. it can memoize any function from a. The module then provides some primitives (like <code>unit :: Memo ()</code> and <code>integral :: Memo Int</code>), and combinators for building more complex memo tables (like <code>pair :: Memo a -&gt; Memo b -&gt; Memo (a,b)</code> and <code>list :: Memo a -&gt; Memo [a]</code>).</p>\n" }, { "answer_id": 4236284, "author": "martin lütke", "author_id": 514872, "author_profile": "https://Stackoverflow.com/users/514872", "pm_score": 4, "selected": false, "text": "<p>You can modify Jonathan´s solution with unsafePerformIO to create a \"pure\" memoizing version of your function.</p>\n\n<pre><code>import qualified Data.Map as Map\nimport Data.IORef\nimport System.IO.Unsafe\n\nmemoize :: Ord a =&gt; (a -&gt; b) -&gt; (a -&gt; b)\nmemoize f = unsafePerformIO $ do \n r &lt;- newIORef Map.empty\n return $ \\ x -&gt; unsafePerformIO $ do \n m &lt;- readIORef r\n case Map.lookup x m of\n Just y -&gt; return y\n Nothing -&gt; do \n let y = f x\n writeIORef r (Map.insert x y m)\n return y\n</code></pre>\n\n<p>This will work with recursive functions:</p>\n\n<pre><code>fib :: Int -&gt; Integer\nfib 0 = 1\nfib 1 = 1\nfib n = fib_memo (n-1) + fib_memo (n-2)\n\nfib_memo :: Int -&gt; Integer\nfib_memo = memoize fib\n</code></pre>\n\n<p>Altough this example is a function with one integer parameter, the type of memoize tells us that it can be used with any function that takes a comparable type. If you have a function with more than one parameter just group them in a tuple before applying memoize. F.i.:</p>\n\n<pre><code>f :: String -&gt; [Int] -&gt; Float\nf ...\n\nf_memo = curry (memoize (uncurry f))\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12887/" ]
I've seen [the other post about this](https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function), but is there a clean way of doing this in Haskell? As a 2nd part, can it also be done without making the function monadic?
This largely follows <http://www.haskell.org/haskellwiki/Memoization>. You want a function of type (a -> b). If it doesn't call itself, then you can just write a simple wrapper that caches the return values. The best way to store this mapping depends on what properties of a you can exploit. Ordering is pretty much a minimum. With integers you can construct an infinite lazy list or tree holding the values. ``` type Cacher a b = (a -> b) -> a -> b positive_list_cacher :: Cacher Int b positive_list_cacher f n = (map f [0..]) !! n ``` or ``` integer_list_cacher :: Cacher Int b integer_list_cacher f n = (map f (interleave [0..] [-1, -2, ..]) !! index n where index n | n < 0 = 2*abs(n) - 1 index n | n >= 0 = 2 * n ``` So, suppose it is recursive. Then you need it to call not itself, but the memoized version, so you pass that in instead: ``` f_with_memo :: (a -> b) -> a -> b f_with_memo memoed base = base_answer f_with_memo memoed arg = calc (memoed (simpler arg)) ``` The memoized version is, of course, what we're trying to define. But we can start by creating a function that caches its inputs: We could construct one level by passing in a function that creates a structure that caches values. Except we need to create the version of f that *already has* the cached function passed in. Thanks to laziness, this is no problem: ``` memoize cacher f = cached where cached = cacher (f cached) ``` then all we need is to use it: ``` exposed_f = memoize cacher_for_f f ``` The article gives hints as to how to use a type class selecting on the input to the function to do the above, rather than choosing an explicit caching function. This can be really nice -- rather than explicitly constructing a cache for each combination of input types, we can implicitly combine caches for types a and b into a cache for a function taking a and b. One final caveat: using this lazy technique means the cache never shrinks, it only grows. If you instead use the IO monad, you can manage this, but doing it wisely depends on usage patterns.
141,682
<p>I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION_SCHEMA.</p> <p>I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere.</p> <p>Are they not there? (I'm using MS SQL Server 2000).</p> <p>EDIT: I'm looking to get by the name of the constraint.</p>
[ { "answer_id": 141825, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 2, "selected": false, "text": "<p>Is the COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS what you are looking for?</p>\n" }, { "answer_id": 142082, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>I don't think it's in the INFORMATION_SCHEMA - you'll probably have to use sysobjects or related deprecated tables/views.</p>\n\n<p>You would think there would be a type for this in INFORMATION_SCHEMA.TABLE_CONSTRAINTS, but I don't see one.</p>\n" }, { "answer_id": 142229, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 0, "selected": false, "text": "<p>Probably because on some of the other SQL DBMSs the \"default constraint\" is not really a constraint, you'll not find its name in \"INFORMATION_SCHEMA.TABLE_CONSTRAINTS\", so your best bet is \"INFORMATION_SCHEMA.COLUMNS\" as others have mentioned already.</p>\n\n<p>(SQLServer-ignoramus here)</p>\n\n<p>The only a reason I can think of when you have to know the \"default constraint\"'s name is if SQLServer doesn't support <code>\"ALTER TABLE xxx ALTER COLUMN yyy SET DEFAULT...\"</code> command. But then you are already in a non-standard zone and you have to use the product-specific ways to get what you need.</p>\n" }, { "answer_id": 142625, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 5, "selected": false, "text": "<p>There seems to be no Default Constraint names in the <code>Information_Schema</code> views.</p>\n\n<p>use <code>SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name</code>\nto find a default constraint by name</p>\n" }, { "answer_id": 541757, "author": "Tim Lentine", "author_id": 2833, "author_profile": "https://Stackoverflow.com/users/2833", "pm_score": 6, "selected": false, "text": "<p>You can use the following to narrow the results even more by specifying the Table Name and Column Name that the Default Constraint correlates to:</p>\n\n<pre><code>select * from sysobjects o \ninner join syscolumns c\non o.id = c.cdefault\ninner join sysobjects t\non c.id = t.id\nwhere o.xtype = 'D'\nand c.name = 'Column_Name'\nand t.name = 'Table_Name'\n</code></pre>\n" }, { "answer_id": 912764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:</p>\n\n<pre><code> select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name\n from information_schema.columns columns\n inner join information_schema.constraint_column_usage usage on \n columns.column_name = usage.column_name and columns.table_name = usage.table_name\n inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name\n where columns.column_default is not null\n</code></pre>\n" }, { "answer_id": 1538651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-sql prettyprint-override\"><code>select c.name, col.name from sys.default_constraints c\n inner join sys.columns col on col.default_object_id = c.object_id\n inner join sys.objects o on o.object_id = c.parent_object_id\n inner join sys.schemas s on s.schema_id = o.schema_id\nwhere s.name = @SchemaName and o.name = @TableName and col.name = @ColumnName\n</code></pre>\n" }, { "answer_id": 6328669, "author": "Johan Badenhorst", "author_id": 318229, "author_profile": "https://Stackoverflow.com/users/318229", "pm_score": 4, "selected": false, "text": "<p>The script below lists all the default constraints and the default values for the user tables in the database in which it is being run:</p>\n\n<pre><code>SELECT \n b.name AS TABLE_NAME,\n d.name AS COLUMN_NAME,\n a.name AS CONSTRAINT_NAME,\n c.text AS DEFAULT_VALUE\nFROM sys.sysobjects a INNER JOIN\n (SELECT name, id\n FROM sys.sysobjects \n WHERE xtype = 'U') b on (a.parent_obj = b.id)\n INNER JOIN sys.syscomments c ON (a.id = c.id)\n INNER JOIN sys.syscolumns d ON (d.cdefault = a.id) \n WHERE a.xtype = 'D' \n ORDER BY b.name, a.name\n</code></pre>\n" }, { "answer_id": 9721492, "author": "Robert Calhoun", "author_id": 198374, "author_profile": "https://Stackoverflow.com/users/198374", "pm_score": 8, "selected": true, "text": "<p>As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION_SCHEMA. INFORMATION_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.*) instead of system table views, which are deprecated in SQL Server 2005 and later.</p>\n\n<p>Below is pretty much the same as @user186476's answer. It returns the name of the default value constraint for a given column. (For non-SQL Server users, you need the name of the default in order to drop it, and if you don't name the default constraint yourself, SQL Server creates some crazy name like \"DF_TableN_Colum_95AFE4B5\". To make it easier to change your schema in the future, always explicitly name your constraints!)</p>\n\n<pre><code>-- returns name of a column's default value constraint \nSELECT\n default_constraints.name\nFROM \n sys.all_columns\n\n INNER JOIN\n sys.tables\n ON all_columns.object_id = tables.object_id\n\n INNER JOIN \n sys.schemas\n ON tables.schema_id = schemas.schema_id\n\n INNER JOIN\n sys.default_constraints\n ON all_columns.default_object_id = default_constraints.object_id\n\nWHERE \n schemas.name = 'dbo'\n AND tables.name = 'tablename'\n AND all_columns.name = 'columnname'\n</code></pre>\n" }, { "answer_id": 32750390, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 3, "selected": false, "text": "<p>If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to <strong>\"test if a given default constraint exists ... by the name of the constraint\"</strong>, then there's a much easier way.</p>\n\n<p>Here's a future-proof answer that doesn't use the <code>sysobjects</code> or other <code>sys</code> tables at all:</p>\n\n<pre><code>IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN\n -- constraint exists, work with it.\nEND\n</code></pre>\n" }, { "answer_id": 35912249, "author": "Mirec", "author_id": 6043907, "author_profile": "https://Stackoverflow.com/users/6043907", "pm_score": 0, "selected": false, "text": "<p>I am using folllowing script to retreive all defaults (sp_binddefaults) and all default constraint with following scripts:</p>\n\n<pre><code>SELECT \n t.name AS TableName, c.name AS ColumnName, SC.COLUMN_DEFAULT AS DefaultValue, dc.name AS DefaultConstraintName\nFROM \n sys.all_columns c\n JOIN sys.tables t ON c.object_id = t.object_id\n JOIN sys.schemas s ON t.schema_id = s.schema_id\n LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id\n LEFT JOIN INFORMATION_SCHEMA.COLUMNS SC ON (SC.TABLE_NAME = t.name AND SC.COLUMN_NAME = c.name)\nWHERE \n SC.COLUMN_DEFAULT IS NOT NULL\n --WHERE t.name = '' and c.name = ''\n</code></pre>\n" }, { "answer_id": 46459428, "author": "user3059720", "author_id": 3059720, "author_profile": "https://Stackoverflow.com/users/3059720", "pm_score": 1, "selected": false, "text": "<pre><code>WHILE EXISTS( \n SELECT * FROM sys.all_columns \n INNER JOIN sys.tables ST ON all_columns.object_id = ST.object_id\n INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id\n INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id\n WHERE \n schemas.name = 'dbo'\n AND ST.name = 'MyTable'\n)\nBEGIN \nDECLARE @SQL NVARCHAR(MAX) = N'';\n\nSET @SQL = ( SELECT TOP 1\n 'ALTER TABLE ['+ schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'\n FROM \n sys.all_columns\n\n INNER JOIN\n sys.tables ST\n ON all_columns.object_id = ST.object_id\n\n INNER JOIN \n sys.schemas\n ON ST.schema_id = schemas.schema_id\n\n INNER JOIN\n sys.default_constraints\n ON all_columns.default_object_id = default_constraints.object_id\n\n WHERE \n schemas.name = 'dbo'\n AND ST.name = 'MyTable'\n )\n PRINT @SQL\n EXECUTE sp_executesql @SQL \n\n --End if Error \n IF @@ERROR &lt;&gt; 0 \n BREAK\nEND \n</code></pre>\n" }, { "answer_id": 47053361, "author": "eigenharsha", "author_id": 4089958, "author_profile": "https://Stackoverflow.com/users/4089958", "pm_score": 0, "selected": false, "text": "<p><strong>Object Catalog View</strong> : sys.default_constraints</p>\n\n<p>The information schema views <code>INFORMATION_SCHEMA</code> are ANSI-compliant, but the default constraints aren't a part of ISO standard. Microsoft SQL Server provides system catalog views for getting information about SQL Server object metadata.</p>\n\n<p><code>sys.default_constraints</code> system catalog view used to getting the information about default constraints.</p>\n\n<pre><code>SELECT so.object_id TableName,\n ss.name AS TableSchema,\n cc.name AS Name,\n cc.object_id AS ObjectID, \n sc.name AS ColumnName,\n cc.parent_column_id AS ColumnID,\n cc.definition AS Defination,\n CONVERT(BIT,\n CASE cc.is_system_named\n WHEN 1\n THEN 1\n ELSE 0\n END) AS IsSystemNamed,\n cc.create_date AS CreationDate,\n cc.modify_date AS LastModifiednDate\nFROM sys.default_constraints cc WITH (NOLOCK)\n INNER JOIN sys.objects so WITH (NOLOCK) ON so.object_id = cc.parent_object_id\n LEFT JOIN sys.schemas ss WITH (NOLOCK) ON ss.schema_id = so.schema_id\n LEFT JOIN sys.columns sc WITH (NOLOCK) ON sc.column_id = cc.parent_column_id\n AND sc.object_id = cc.parent_object_id\nORDER BY so.name,\n cc.name;\n</code></pre>\n" }, { "answer_id": 57622699, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>Necromancing. <br />\nIf you only need to check if a default-constraint exists <br />\n(default-constraint(s) may have different name in poorly-managed DBs), <br />\nuse INFORMATION_SCHEMA.COLUMNS (column_default): </p>\n\n<pre><code>IF NOT EXISTS(\n SELECT * FROM INFORMATION_SCHEMA.COLUMNS\n WHERE (1=1) \n AND TABLE_SCHEMA = 'dbo' \n AND TABLE_NAME = 'T_VWS_PdfBibliothek' \n AND COLUMN_NAME = 'PB_Text'\n AND COLUMN_DEFAULT IS NOT NULL \n)\nBEGIN \n EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek \n ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; \n '); \nEND \n</code></pre>\n\n<p>If you want to check by the constraint-name only: </p>\n\n<pre><code>-- Alternative way: \nIF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL \nBEGIN\n -- constraint exists, deal with it.\nEND \n</code></pre>\n\n<p>And last but not least, you can just create a view called <br />INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS: </p>\n\n<pre><code>CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS \nAS \nSELECT \n DB_NAME() AS CONSTRAINT_CATALOG \n ,csch.name AS CONSTRAINT_SCHEMA\n ,dc.name AS CONSTRAINT_NAME \n ,DB_NAME() AS TABLE_CATALOG \n ,sch.name AS TABLE_SCHEMA \n ,syst.name AS TABLE_NAME \n ,sysc.name AS COLUMN_NAME \n ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION \n ,dc.type_desc AS CONSTRAINT_TYPE \n ,dc.definition AS COLUMN_DEFAULT \n\n -- ,dc.create_date \n -- ,dc.modify_date \nFROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where \n-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where \n\nINNER JOIN sys.tables AS syst \n ON syst.object_id = sysc.object_id \n\nINNER JOIN sys.schemas AS sch\n ON sch.schema_id = syst.schema_id \n\nINNER JOIN sys.default_constraints AS dc \n ON sysc.default_object_id = dc.object_id\n\nINNER JOIN sys.schemas AS csch\n ON csch.schema_id = dc.schema_id \n\nWHERE (1=1) \nAND dc.is_ms_shipped = 0 \n\n/*\nWHERE (1=1) \nAND sch.name = 'dbo'\nAND syst.name = 'tablename'\nAND sysc.name = 'columnname'\n*/\n</code></pre>\n" }, { "answer_id": 65834870, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 0, "selected": false, "text": "<p>A bit of a cleaner way to do this:</p>\n<pre><code>SELECT DC.[name]\n FROM [sys].[default_constraints] AS DC\n WHERE DC.[parent_object_id] = OBJECT_ID('[Schema].[TableName]') \n</code></pre>\n" }, { "answer_id": 73573218, "author": "SAinCA", "author_id": 364795, "author_profile": "https://Stackoverflow.com/users/364795", "pm_score": 0, "selected": false, "text": "<p>If the target database has, say, over 1M objects, using <code>sys.default_constraints</code> can hit you with 90%+ taken on scanning <code>sys.syscolpars</code> followed by a Key Lookup for the <code>dflt</code> you likely don't care about. On my DB, it takes 1.129s to assemble just 4 rows from the 158 read of the <strong>residual I/O impaired</strong> 1.12MM rows actually scanned.</p>\n<p>Changing to using the current sys.% tables/views, using @Tim's query, the same 4 constraints are acquired in 2ms. Hope someone finds this as useful as I found Tim's:</p>\n<pre><code>SELECT ConstraintName = sdc.name\n , SchemaName = ssch.name\n , TableName = stab.name\n , ColumnName = scol.name\n FROM sys.objects sdc\n INNER JOIN sys.columns scol\n ON scol.default_object_id = sdc.object_id\n INNER JOIN sys.objects stab\n ON stab.object_id = scol.object_id\n INNER JOIN sys.schemas ssch\n ON ssch.schema_id = stab.schema_id;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9052/" ]
I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION\_SCHEMA. I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere. Are they not there? (I'm using MS SQL Server 2000). EDIT: I'm looking to get by the name of the constraint.
As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION\_SCHEMA. INFORMATION\_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.\*) instead of system table views, which are deprecated in SQL Server 2005 and later. Below is pretty much the same as @user186476's answer. It returns the name of the default value constraint for a given column. (For non-SQL Server users, you need the name of the default in order to drop it, and if you don't name the default constraint yourself, SQL Server creates some crazy name like "DF\_TableN\_Colum\_95AFE4B5". To make it easier to change your schema in the future, always explicitly name your constraints!) ``` -- returns name of a column's default value constraint SELECT default_constraints.name FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id WHERE schemas.name = 'dbo' AND tables.name = 'tablename' AND all_columns.name = 'columnname' ```
141,734
<p>If I do not specify the following in my web.xml file:</p> <pre><code>&lt;session-config&gt; &lt;session-timeout&gt;10&lt;/session-timeout&gt; &lt;/session-config&gt; </code></pre> <p>What will be my default session timeout? (I am running Tomcat 6.0)</p>
[ { "answer_id": 141742, "author": "JavadocMD", "author_id": 9304, "author_profile": "https://Stackoverflow.com/users/9304", "pm_score": 3, "selected": false, "text": "<p>I'm sure it depends on your container. Tomcat is 30 minutes.</p>\n" }, { "answer_id": 141755, "author": "Huuuze", "author_id": 10040, "author_profile": "https://Stackoverflow.com/users/10040", "pm_score": 6, "selected": true, "text": "<p>If you're using Tomcat, it's 30 minutes. You can read more about it <a href=\"http://forums.sun.com/thread.jspa?threadID=565341&amp;messageID=2788327\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 142372, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 3, "selected": false, "text": "<p>You can also set this in code, for a specific session using the <code>HttpSession</code> <a href=\"http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSession.html#setMaxInactiveInterval(int)\" rel=\"noreferrer\">setMaxInactiveInterval</a> API: </p>\n\n<blockquote>\n <p>Specifies the time, in seconds,\n between client requests before the\n servlet container will invalidate this\n session. A negative time indicates the\n session should never timeout.</p>\n</blockquote>\n\n<p>I mention this in case you see timeouts that are not 30 minutes, but you didn't specify another value (e.g. another developer on the project used this API).</p>\n\n<p>Another item to note is this timeout may not trigger on the exact second the session is eligible to expire. The Java EE server may have a polling thread that checks for expired sessions every minute. I don't have a reference for this, but have seen this behavior in the WebSphere 5.1 era.</p>\n" }, { "answer_id": 1936265, "author": "sharath", "author_id": 235544, "author_profile": "https://Stackoverflow.com/users/235544", "pm_score": 1, "selected": false, "text": "<p>Session Time out we can specify for that particular context in web.xml file as mentined below entry\n \n 60 \n </p>\n\n<p>Default Session time out is 30 mins</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
If I do not specify the following in my web.xml file: ``` <session-config> <session-timeout>10</session-timeout> </session-config> ``` What will be my default session timeout? (I am running Tomcat 6.0)
If you're using Tomcat, it's 30 minutes. You can read more about it [here](http://forums.sun.com/thread.jspa?threadID=565341&messageID=2788327).
141,752
<p>My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases.</p> <p>Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.</p> <p>For example:</p> <pre><code>LEFTPOS and SPACING are defined floating point values. float def_x; int xpos; def_x = LEFTPOS + (xpos * (SPACING / 2)); </code></pre> <p>The issue is in regards to the X360 compiler.</p>
[ { "answer_id": 141771, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 2, "selected": false, "text": "<p>It's not a bug. Any floating point uperation has a certain imprecision. In Release mode, optimization will change the order of the operations and you'll get a slightly different result. The difference should be small, though. If it's big you might have other problems.</p>\n" }, { "answer_id": 141772, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 5, "selected": true, "text": "<p>Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.</p>\n" }, { "answer_id": 141796, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 2, "selected": false, "text": "<p>I helped a co-worker find a compiler switch that was different in release vs. debug builds that was causing his differences.</p>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/e7s85ffb.aspx?ppud=4\" rel=\"nofollow noreferrer\">/fp (Specify Floating-Point Behavior)</a>.</p>\n" }, { "answer_id": 141797, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 1, "selected": false, "text": "<p>Not a bug. This type of difference is to be expected.</p>\n\n<p>For example, some platforms have float registers that use more bits than are stored in memory, so keeping a value in the register can yield a slightly different result compared to storing to memory and re-loading from memory.</p>\n" }, { "answer_id": 141804, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>This discrepancy may very well be caused by the compiler optimization, which is typically done in the release mode, but not in debug mode. For example, the compiler may reorder some of the operations to speed up execution, which can conceivably cause a slight difference in the floating point result.</p>\n\n<p>So, I would say most likely it is not a bug. If you are really worried about this, try turning on optimization in the Debug mode.</p>\n" }, { "answer_id": 141815, "author": "Luke Halliwell", "author_id": 3974, "author_profile": "https://Stackoverflow.com/users/3974", "pm_score": 2, "selected": false, "text": "<p>I know that on PC, floating point registers are 80 bits wide. So if a calculation is done entirely within the FPU, you get the benefit of 80 bits of precision. On the other hand, if an intermediate result is moved out into a normal register and back, it gets truncated to 32 bits, which gives different results.</p>\n\n<p>Now consider that a release build will have optimisations which keep intermediate results in FPU registers, whereas a debug build will probably naively copy intermediate results back and forward between memory and registers - and there you have your difference in behaviour.</p>\n\n<p>I don't know whether this happens on X360 too or not.</p>\n" }, { "answer_id": 142521, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 0, "selected": false, "text": "<p>Like others mentioned, floating point registers have higher precision than floats, so the accuracy of the final result depends on the register allocation.</p>\n\n<p>If you need consistent results, you can make the variables volatile, which will result in slower, less precise, but consistent results.</p>\n" }, { "answer_id": 142537, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 2, "selected": false, "text": "<p>In addition to the different floating-point modes others have pointed out, SSE or similiar vector optimizations may be turned on for release. Converting floating-point arithmetic from standard registers to vector registers can have an effect on the lower bits of your results, as the vector registers will generally be more narrow (fewer bits) than the standard floating-point registers.</p>\n" }, { "answer_id": 319015, "author": "Die in Sente", "author_id": 40756, "author_profile": "https://Stackoverflow.com/users/40756", "pm_score": 0, "selected": false, "text": "<p>If you set a compiler switch that allowed the compiler to reorder floating-point operations, -- e.g. /fp:fast -- then obviously it's not a bug.</p>\n\n<p>If you didn't set any such switch, then it's a bug -- the C and C++ standards don't allow the compilers to reorder operations without your permission. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases. Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug. For example: ``` LEFTPOS and SPACING are defined floating point values. float def_x; int xpos; def_x = LEFTPOS + (xpos * (SPACING / 2)); ``` The issue is in regards to the X360 compiler.
Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.
141,779
<p>The problem/comic in question: <a href="http://xkcd.com/287/" rel="nofollow noreferrer">http://xkcd.com/287/</a></p> <p><img src="https://imgs.xkcd.com/comics/np_complete.png" alt="General solutions get you a 50% tip"></p> <p>I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone.</p> <pre><code>&lt;cffunction name="testCombo" returntype="boolean"&gt; &lt;cfargument name="currentCombo" type="string" required="true" /&gt; &lt;cfargument name="currentTotal" type="numeric" required="true" /&gt; &lt;cfargument name="apps" type="array" required="true" /&gt; &lt;cfset var a = 0 /&gt; &lt;cfset var found = false /&gt; &lt;cfloop from="1" to="#arrayLen(arguments.apps)#" index="a"&gt; &lt;cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) /&gt; &lt;cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost /&gt; &lt;cfif arguments.currentTotal eq 15.05&gt; &lt;!--- print current combo ---&gt; &lt;cfoutput&gt;&lt;strong&gt;#arguments.currentCombo# = 15.05&lt;/strong&gt;&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfreturn true /&gt; &lt;cfelseif arguments.currentTotal gt 15.05&gt; &lt;cfoutput&gt;#arguments.currentCombo# &gt; 15.05 (aborting)&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfreturn false /&gt; &lt;cfelse&gt; &lt;!--- less than 15.05 ---&gt; &lt;cfoutput&gt;#arguments.currentCombo# &lt; 15.05 (traversing)&lt;/cfoutput&gt;&lt;br /&gt; &lt;cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) /&gt; &lt;/cfif&gt; &lt;/cfloop&gt; &lt;/cffunction&gt; &lt;cfset mf = {name="Mixed Fruit", cost=2.15} /&gt; &lt;cfset ff = {name="French Fries", cost=2.75} /&gt; &lt;cfset ss = {name="side salad", cost=3.35} /&gt; &lt;cfset hw = {name="hot wings", cost=3.55} /&gt; &lt;cfset ms = {name="moz sticks", cost=4.20} /&gt; &lt;cfset sp = {name="sampler plate", cost=5.80} /&gt; &lt;cfset apps = [ mf, ff, ss, hw, ms, sp ] /&gt; &lt;cfloop from="1" to="6" index="b"&gt; &lt;cfoutput&gt;#testCombo(apps[b].name, apps[b].cost, apps)#&lt;/cfoutput&gt; &lt;/cfloop&gt; </code></pre> <p>The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete.</p> <p>Is there a better algorithm to come to the correct solution? Did I come to the correct solution?</p>
[ { "answer_id": 141858, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>Read up on the <a href=\"http://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">Knapsack Problem</a>.</p>\n" }, { "answer_id": 141909, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 0, "selected": false, "text": "<p>Actually, I've refactored my algorithm some more. There were several correct combinations I was missing, and it was due to the fact that I was returning as soon as the cost went over 15.05 -- I wasn't bothering to check other (cheaper) items that I could add. Here's my new algorithm:</p>\n\n<pre><code>&lt;cffunction name=\"testCombo\" returntype=\"numeric\"&gt;\n &lt;cfargument name=\"currentCombo\" type=\"string\" required=\"true\" /&gt;\n &lt;cfargument name=\"currentTotal\" type=\"numeric\" required=\"true\" /&gt;\n &lt;cfargument name=\"apps\" type=\"array\" required=\"true\" /&gt;\n\n &lt;cfset var a = 0 /&gt;\n &lt;cfset var found = false /&gt; \n &lt;cfset var CC = \"\" /&gt;\n &lt;cfset var CT = 0 /&gt;\n\n &lt;cfset tries = tries + 1 /&gt;\n\n &lt;cfloop from=\"1\" to=\"#arrayLen(arguments.apps)#\" index=\"a\"&gt;\n &lt;cfset combos = combos + 1 /&gt;\n &lt;cfset CC = listAppend(arguments.currentCombo, arguments.apps[a].name) /&gt;\n &lt;cfset CT = arguments.currentTotal + arguments.apps[a].cost /&gt;\n &lt;cfif CT eq 15.05&gt;\n &lt;!--- print current combo ---&gt;\n &lt;cfoutput&gt;&lt;strong&gt;#CC# = 15.05&lt;/strong&gt;&lt;/cfoutput&gt;&lt;br /&gt;\n &lt;cfreturn true /&gt;\n &lt;cfelseif CT gt 15.05&gt;\n &lt;!--&lt;cfoutput&gt;#arguments.currentCombo# &gt; 15.05 (aborting)&lt;/cfoutput&gt;&lt;br /&gt;--&gt;\n &lt;cfelse&gt;\n &lt;!--- less than 15.50 ---&gt;\n &lt;!--&lt;cfoutput&gt;#arguments.currentCombo# &lt; 15.05 (traversing)&lt;/cfoutput&gt;&lt;br /&gt;--&gt;\n &lt;cfset found = testCombo(CC, CT, arguments.apps) /&gt;\n &lt;/cfif&gt;\n &lt;/cfloop&gt;\n &lt;cfreturn found /&gt;\n&lt;/cffunction&gt;\n\n&lt;cfset mf = {name=\"Mixed Fruit\", cost=2.15} /&gt;\n&lt;cfset ff = {name=\"French Fries\", cost=2.75} /&gt;\n&lt;cfset ss = {name=\"side salad\", cost=3.35} /&gt;\n&lt;cfset hw = {name=\"hot wings\", cost=3.55} /&gt;\n&lt;cfset ms = {name=\"moz sticks\", cost=4.20} /&gt;\n&lt;cfset sp = {name=\"sampler plate\", cost=5.80} /&gt;\n&lt;cfset apps = [ mf, ff, ss, hw, ms, sp ] /&gt;\n\n&lt;cfset tries = 0 /&gt;\n&lt;cfset combos = 0 /&gt;\n\n&lt;cfoutput&gt;\n &lt;cfloop from=\"1\" to=\"6\" index=\"b\"&gt;\n #testCombo(apps[b].name, apps[b].cost, apps)#\n &lt;/cfloop&gt;\n &lt;br /&gt;\n tries: #tries#&lt;br /&gt;\n combos: #combos#\n&lt;/cfoutput&gt;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit = 15.05\nMixed Fruit,hot wings,hot wings,sampler plate = 15.05\nMixed Fruit,hot wings,sampler plate,hot wings = 15.05\nMixed Fruit,sampler plate,hot wings,hot wings = 15.05\nfalse false false hot wings,Mixed Fruit,hot wings,sampler plate = 15.05\nhot wings,Mixed Fruit,sampler plate,hot wings = 15.05\nhot wings,hot wings,Mixed Fruit,sampler plate = 15.05\nhot wings,sampler plate,Mixed Fruit,hot wings = 15.05\nfalse false sampler plate,Mixed Fruit,hot wings,hot wings = 15.05\nsampler plate,hot wings,Mixed Fruit,hot wings = 15.05\nfalse\ntries: 2014\ncombos: 12067\n</code></pre>\n\n<p>I think this may have all of the correct combinations, but my question still stands: Is there a better algorithm?</p>\n" }, { "answer_id": 141949, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 2, "selected": false, "text": "<p>You've got all the correct combinations now, but you're still checking many more than you need to (as evidenced by the many permutations your result shows). Also, you're omitting the last item that hits the 15.05 mark.</p>\n\n<p>I have a PHP version that does 209 iterations of the recursive call (it does 2012 if I get all permutations). You can reduce your count if right before the end of your loop, you pull out the item you just checked.</p>\n\n<p>I don't know CF syntax, but it will be something like this:</p>\n\n<pre><code> &lt;cfelse&gt;\n &lt;!--- less than 15.50 ---&gt;\n &lt;!--&lt;cfoutput&gt;#arguments.currentCombo# &lt; 15.05 (traversing)&lt;/cfoutput&gt;&lt;br /&gt;--&gt;\n &lt;cfset found = testCombo(CC, CT, arguments.apps) /&gt;\n ------- remove the item from the apps array that was just checked here ------\n &lt;/cfif&gt;\n&lt;/cfloop&gt;\n</code></pre>\n\n<p>EDIT: For reference, here's my PHP version:</p>\n\n<pre><code>&lt;?\n function rc($total, $string, $m) {\n global $c;\n\n $m2 = $m;\n $c++;\n\n foreach($m as $i=&gt;$p) {\n if ($total-$p == 0) {\n print \"$string $i\\n\";\n return;\n }\n if ($total-$p &gt; 0) {\n rc($total-$p, $string . \" \" . $i, $m2);\n }\n unset($m2[$i]);\n }\n }\n\n $c = 0;\n\n $m = array(\"mf\"=&gt;215, \"ff\"=&gt;275, \"ss\"=&gt;335, \"hw\"=&gt;355, \"ms\"=&gt;420, \"sp\"=&gt;580);\n rc(1505, \"\", $m);\n print $c;\n?&gt;\n</code></pre>\n\n<p>Output</p>\n\n<pre><code> mf mf mf mf mf mf mf\n mf hw hw sp\n209\n</code></pre>\n\n<p>EDIT 2:</p>\n\n<p>Since explaining why you can remove the elements will take a little more than I could fit in a comment, I'm adding it here.</p>\n\n<p>Basically, each recursion will find all combinations that include the currently search element (e.g., the first step will find everything including at least one mixed fruit). The easiest way to understand it is to trace the execution, but since that will take a lot of space, I'll do it as if the target was 6.45.</p>\n\n<pre><code>MF (2.15)\n MF (4.30)\n MF (6.45) *\n FF (7.05) X\n SS (7.65) X\n ...\n [MF removed for depth 2]\n FF (4.90)\n [checking MF now would be redundant since we checked MF/MF/FF previously]\n FF (7.65) X\n ...\n [FF removed for depth 2]\n SS (5.50)\n ...\n[MF removed for depth 1]\n</code></pre>\n\n<p>At this point, we've checked every combination that includes any mixed fruit, so there's no need to check for mixed fruit again. You can use the same logic to prune the array at each of the deeper recursions as well.</p>\n\n<p>Tracing through it like this actually suggested another slight time saver -- knowing the prices are sorted from low to high means that we don't need to keep checking items once we go over the target.</p>\n" }, { "answer_id": 143213, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<p>Here's a solution with F#:</p>\n\n<pre><code>#light\n\ntype Appetizer = { name : string; cost : int }\n\nlet menu = [\n {name=\"fruit\"; cost=215}\n {name=\"fries\"; cost=275}\n {name=\"salad\"; cost=335}\n {name=\"wings\"; cost=355}\n {name=\"moz sticks\"; cost=420}\n {name=\"sampler\"; cost=580}\n ] \n\n// Choose: list&lt;Appetizer&gt; -&gt; list&lt;Appetizer&gt; -&gt; int -&gt; list&lt;list&lt;Appetizer&gt;&gt;\nlet rec Choose allowedMenu pickedSoFar remainingMoney =\n if remainingMoney = 0 then\n // solved it, return this solution\n [ pickedSoFar ]\n else\n // there's more to spend\n [match allowedMenu with\n | [] -&gt; yield! [] // no more items to choose, no solutions this branch\n | item :: rest -&gt; \n if item.cost &lt;= remainingMoney then\n // if first allowed is within budget, pick it and recurse\n yield! Choose allowedMenu (item :: pickedSoFar) (remainingMoney - item.cost)\n // regardless, also skip ever picking more of that first item and recurse\n yield! Choose rest pickedSoFar remainingMoney]\n\nlet solutions = Choose menu [] 1505\n\nprintfn \"%d solutions:\" solutions.Length \nsolutions |&gt; List.iter (fun solution -&gt;\n solution |&gt; List.iter (fun item -&gt; printf \"%s, \" item.name)\n printfn \"\"\n)\n\n(*\n2 solutions:\nfruit, fruit, fruit, fruit, fruit, fruit, fruit,\nsampler, wings, wings, fruit,\n*)\n</code></pre>\n" }, { "answer_id": 143261, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "<p>Isn't it more elegant with recursion (in Perl)?</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy @weights = (2.15, 2.75, 3.35, 3.55, 4.20, 5.80);\n\nmy $total = 0;\nmy @order = ();\n\niterate($total, @order);\n\nsub iterate\n{\n my ($total, @order) = @_;\n foreach my $w (@weights)\n {\n if ($total+$w == 15.05)\n {\n print join (', ', (@order, $w)), \"\\n\";\n }\n if ($total+$w &lt; 15.05)\n {\n iterate($total+$w, (@order, $w));\n }\n }\n}\n</code></pre>\n\n<p>Output</p>\n\n<p><code>marco@unimatrix-01:~$ ./xkcd-knapsack.pl<br>\n2.15, 2.15, 2.15, 2.15, 2.15, 2.15, 2.15<br>\n2.15, 3.55, 3.55, 5.8<br>\n2.15, 3.55, 5.8, 3.55<br>\n2.15, 5.8, 3.55, 3.55<br>\n3.55, 2.15, 3.55, 5.8<br>\n3.55, 2.15, 5.8, 3.55<br>\n3.55, 3.55, 2.15, 5.8<br>\n3.55, 5.8, 2.15, 3.55<br>\n5.8, 2.15, 3.55, 3.55<br>\n5.8, 3.55, 2.15, 3.55\n</code></p>\n" }, { "answer_id": 143288, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 6, "selected": true, "text": "<p>The point about an NP-complete problem is not that it's tricky on a small data set, but that the amount of work to solve it grows at a rate greater than polynomial, i.e. there is no O(n^x) algorithm. </p>\n\n<p>If the time complexity is O(n!), as in (I believe) the two problems mentioned above, that is in NP. </p>\n" }, { "answer_id": 168059, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 0, "selected": false, "text": "<p>Learning from <a href=\"https://stackoverflow.com/questions/141779/solving-the-np-complete-problem-in-xkcd#141949\">@rcar's answer</a>, and another refactoring later, I've got the following.</p>\n\n<p>As with so many things I code, I've refactored from CFML to CFScript, but the code is basically the same.</p>\n\n<p>I added in his suggestion of a dynamic start point in the array (instead of passing the array by value and changing its value for future recursions), which brought me to the same stats he gets (209 recursions, 571 combination price checks (loop iterations)), and then improved on that by assuming that the array will be sorted by cost -- because it is -- and breaking as soon as we go over the target price. With the break, we're down to 209 recursions and 376 loop iterations.</p>\n\n<p>What other improvements could be made to the algorithm?</p>\n\n<pre><code>function testCombo(minIndex, currentCombo, currentTotal){\n var a = 0;\n var CC = \"\";\n var CT = 0;\n var found = false;\n\n tries += 1;\n for (a=arguments.minIndex; a &lt;= arrayLen(apps); a++){\n combos += 1;\n CC = listAppend(arguments.currentCombo, apps[a].name);\n CT = arguments.currentTotal + apps[a].cost;\n if (CT eq 15.05){\n //print current combo\n WriteOutput(\"&lt;strong&gt;#CC# = 15.05&lt;/strong&gt;&lt;br /&gt;\");\n return(true);\n }else if (CT gt 15.05){\n //since we know the array is sorted by cost (asc),\n //and we've already gone over the price limit,\n //we can ignore anything else in the array\n break; \n }else{\n //less than 15.50, try adding something else\n found = testCombo(a, CC, CT);\n }\n }\n return(found);\n}\n\nmf = {name=\"mixed fruit\", cost=2.15};\nff = {name=\"french fries\", cost=2.75};\nss = {name=\"side salad\", cost=3.35};\nhw = {name=\"hot wings\", cost=3.55};\nms = {name=\"mozarella sticks\", cost=4.20};\nsp = {name=\"sampler plate\", cost=5.80};\napps = [ mf, ff, ss, hw, ms, sp ];\n\ntries = 0;\ncombos = 0;\n\ntestCombo(1, \"\", 0);\n\nWriteOutput(\"&lt;br /&gt;tries: #tries#&lt;br /&gt;combos: #combos#\");\n</code></pre>\n" }, { "answer_id": 228522, "author": "Ying Xiao", "author_id": 30202, "author_profile": "https://Stackoverflow.com/users/30202", "pm_score": 3, "selected": false, "text": "<p>Even though knapsack is NP Complete, it is a very special problem: the usual dynamic program for it is in fact excellent (<a href=\"http://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Knapsack_problem</a>)</p>\n\n<p>And if you do the correct analysis, it turns out that it is O(nW), n being the # of items, and W being the target number. The problem is when you have to DP over a large W, that's when we get the NP behaviour. But for the most part, knapsack is reasonably well behaved and you can solve really large instances of it with no problems. As far as NP complete problems go, knapsack is one of the easiest.</p>\n" }, { "answer_id": 228810, "author": "Toby", "author_id": 291137, "author_profile": "https://Stackoverflow.com/users/291137", "pm_score": 5, "selected": false, "text": "<p>It gives all the permutations of the solutions, but I think I'm beating everyone else for code size.</p>\n\n<pre><code>item(X) :- member(X,[215, 275, 335, 355, 420, 580]).\nsolution([X|Y], Z) :- item(X), plus(S, X, Z), Z &gt;= 0, solution(Y, S).\nsolution([], 0).\n</code></pre>\n\n<p>Solution with swiprolog:</p>\n\n<pre><code>?- solution(X, 1505).\n\nX = [215, 215, 215, 215, 215, 215, 215] ;\n\nX = [215, 355, 355, 580] ;\n\nX = [215, 355, 580, 355] ;\n\nX = [215, 580, 355, 355] ;\n\nX = [355, 215, 355, 580] ;\n\nX = [355, 215, 580, 355] ;\n\nX = [355, 355, 215, 580] ;\n\nX = [355, 355, 580, 215] ;\n\nX = [355, 580, 215, 355] ;\n\nX = [355, 580, 355, 215] ;\n\nX = [580, 215, 355, 355] ;\n\nX = [580, 355, 215, 355] ;\n\nX = [580, 355, 355, 215] ;\n\nNo\n</code></pre>\n" }, { "answer_id": 390629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is the solution using constraint.py</p>\n\n<pre><code>&gt;&gt;&gt; from constraint import *\n&gt;&gt;&gt; problem = Problem()\n&gt;&gt;&gt; menu = {'mixed-fruit': 2.15,\n... 'french-fries': 2.75,\n... 'side-salad': 3.35,\n... 'hot-wings': 3.55,\n... 'mozarella-sticks': 4.20,\n... 'sampler-plate': 5.80}\n&gt;&gt;&gt; for appetizer in menu:\n... problem.addVariable( appetizer, [ menu[appetizer] * i for i in range( 8 )] )\n&gt;&gt;&gt; problem.addConstraint(ExactSumConstraint(15.05))\n&gt;&gt;&gt; problem.getSolutions()\n[{'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 5.7999999999999998, 'mixed-fruit': 2.1499999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 7.0999999999999996},\n {'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 0.0, 'mixed-fruit': 15.049999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 0.0}]\n</code></pre>\n\n<p>So the solution is to order a sampler plate, a mixed fruit, and 2 orders of hot wings, or order 7 mixed-fruits.</p>\n" }, { "answer_id": 398109, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 2, "selected": false, "text": "<p>I would make one suggestion about the design of the algorithm itself (which is how I interpreted the intent of your original question). Here is a <em>fragment</em> of the solution I wrote:</p>\n\n<pre><code>....\n\nprivate void findAndReportSolutions(\n int target, // goal to be achieved\n int balance, // amount of goal remaining\n int index // menu item to try next\n) {\n ++calls;\n if (balance == 0) {\n reportSolution(target);\n return; // no addition to perfect order is possible\n }\n if (index == items.length) {\n ++falls;\n return; // ran out of menu items without finding solution\n }\n final int price = items[index].price;\n if (balance &lt; price) {\n return; // all remaining items cost too much\n }\n int maxCount = balance / price; // max uses for this item\n for (int n = maxCount; 0 &lt;= n; --n) { // loop for this item, recur for others\n ++loops;\n counts[index] = n;\n findAndReportSolutions(\n target, balance - n * price, index + 1\n );\n }\n}\n\npublic void reportSolutionsFor(int target) {\n counts = new int[items.length];\n calls = loops = falls = 0;\n findAndReportSolutions(target, target, 0);\n ps.printf(\"%d calls, %d loops, %d falls%n\", calls, loops, falls);\n}\n\npublic static void main(String[] args) {\n MenuItem[] items = {\n new MenuItem(\"mixed fruit\", 215),\n new MenuItem(\"french fries\", 275),\n new MenuItem(\"side salad\", 335),\n new MenuItem(\"hot wings\", 355),\n new MenuItem(\"mozzarella sticks\", 420),\n new MenuItem(\"sampler plate\", 580),\n };\n Solver solver = new Solver(items);\n solver.reportSolutionsFor(1505);\n}\n\n...\n</code></pre>\n\n<p>(Note that the constructor <em>does</em> sort the menu items by increasing price, to enable the constant-time early termination when the remaining balance is smaller than any remaining menu item.)</p>\n\n<p>The output for a sample run is:</p>\n\n<pre><code>7 mixed fruit (1505) = 1505\n1 mixed fruit (215) + 2 hot wings (710) + 1 sampler plate (580) = 1505\n348 calls, 347 loops, 79 falls\n</code></pre>\n\n<p>The design suggestion I want to highlight is that in the above code, each nested (recursive) call of <code>findAndReportSolution(...)</code> deals with the quantity of exactly one menu item, identified by the <code>index</code> argument. In other words, the recursive nesting parallels the behavior of an in-line set of nested loops; the outermost counts possible uses of the first menu item, the next in counts the uses of the second menu item, etc. (Except, of course, the use of recursion liberates the code from dependence on a specific number of menu items!)</p>\n\n<p>I suggest that this makes it easier to design the code, and easier to understand what each invocation is doing (accounting for all possible uses of a specific item, delegating the remainder of the menu to subordinate calls). It also avoids the combinatorial explosion of producing all arrangements of a multiple-item solution (as in the second line of the above output, which only occurs once, instead of repeatedly with different orderings of the items).</p>\n\n<p>I try to maximize the \"obviousness\" of the code, rather than trying to minimize the number of calls of some specific method. For example, the above design lets a delegated call determine if a solution has been reached, rather than wrapping that check around the point of the call, which would reduce the number of calls at the expense of cluttering up the code.</p>\n" }, { "answer_id": 699148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Hmm, you know what's weird. The solution is seven of the first item on the menu.</p>\n\n<p>Since this was obviously meant to be solved by paper and pencil in a short time frame, why not divide the order total by the price of each item to see if by some chance they ordered multiples of one item?</p>\n\n<p>For example, </p>\n\n<p>15.05/2.15 = 7 mixed fruits\n15.05/2.75 = 5.5 french fries.</p>\n\n<p>And then move on to simple combinations...</p>\n\n<p>15 / (2.15 + 2.75) = 3.06122449 mixed fruits with french fries.</p>\n\n<p>In other words, assume that the solution is supposed to be simple and solvable by a human without access to a computer. Then test if the simplest, most obvious (and therefore hidden in plain sight) solution(s) work(s).</p>\n\n<p>I swear I'm pulling this at the local coney this weekend when I order $4.77 worth of appetizers (including tax) at 4:30 AM after the club closes.</p>\n" }, { "answer_id": 936743, "author": "kinghajj", "author_id": 76721, "author_profile": "https://Stackoverflow.com/users/76721", "pm_score": 0, "selected": false, "text": "<p>Here's concurrent implementation in Clojure. To calculate <code>(items-with-price 15.05)</code> takes about 14 combination-generation recursions, and about 10 possibility-checks. Took me about 6 minutes to calculate <code>(items-with-price 100)</code> on my Intel Q9300.</p>\n\n<p>This only gives the first found answer, or <code>nil</code> if there is none, as that's all the problem calls for. Why do more work that you've been told to do ;) ?</p>\n\n<pre><code>;; np-complete.clj\n;; A Clojure solution to XKCD #287 \"NP-Complete\"\n;; By Sam Fredrickson\n;;\n;; The function \"items-with-price\" returns a sequence of items whose sum price\n;; is equal to the given price, or nil.\n\n(defstruct item :name :price)\n\n(def *items* #{(struct item \"Mixed Fruit\" 2.15)\n (struct item \"French Fries\" 2.75)\n (struct item \"Side Salad\" 3.35)\n (struct item \"Hot Wings\" 3.55)\n (struct item \"Mozzarella Sticks\" 4.20)\n (struct item \"Sampler Plate\" 5.80)})\n\n(defn items-with-price [price]\n (let [check-count (atom 0)\n recur-count (atom 0)\n result (atom nil)\n checker (agent nil)\n ; gets the total price of a seq of items.\n items-price (fn [items] (apply + (map #(:price %) items)))\n ; checks if the price of the seq of items matches the sought price.\n ; if so, it changes the result atom. if the result atom is already\n ; non-nil, nothing is done.\n check-items (fn [unused items]\n (swap! check-count inc)\n (if (and (nil? @result)\n (= (items-price items) price))\n (reset! result items)))\n ; lazily generates a list of combinations of the given seq s.\n ; haven't tested well...\n combinations (fn combinations [cur s]\n (swap! recur-count inc)\n (if (or (empty? s)\n (&gt; (items-price cur) price))\n '()\n (cons cur\n (lazy-cat (combinations (cons (first s) cur) s)\n (combinations (cons (first s) cur) (rest s))\n (combinations cur (rest s))))))]\n ; loops through the combinations of items, checking each one in a thread\n ; pool until there are no more combinations or the result atom is non-nil.\n (loop [items-comb (combinations '() (seq *items*))]\n (if (and (nil? @result)\n (not-empty items-comb))\n (do (send checker check-items (first items-comb))\n (recur (rest items-comb)))))\n (await checker)\n (println \"No. of recursions:\" @recur-count)\n (println \"No. of checks:\" @check-count)\n @result))\n</code></pre>\n" }, { "answer_id": 959851, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 1, "selected": false, "text": "<p>In python.<br />\nI had some problems with \"global vars\" so I put the function as method of an object. It is recursive and it calls itself 29 times for the question in the comic, stopping at the first successful match</p>\n\n<pre><code>class Solver(object):\n def __init__(self):\n self.solved = False\n self.total = 0\n def solve(s, p, pl, curList = []):\n poss = [i for i in sorted(pl, reverse = True) if i &lt;= p]\n if len(poss) == 0 or s.solved:\n s.total += 1\n return curList\n if abs(poss[0]-p) &lt; 0.00001:\n s.solved = True # Solved it!!!\n s.total += 1\n return curList + [poss[0]]\n ml,md = [], 10**8\n for j in [s.solve(p-i, pl, [i]) for i in poss]:\n if abs(sum(j)-p)&lt;md: ml,md = j, abs(sum(j)-p)\n s.total += 1\n return ml + curList\n\n\npriceList = [5.8, 4.2, 3.55, 3.35, 2.75, 2.15]\nappetizers = ['Sampler Plate', 'Mozzarella Sticks', \\\n 'Hot wings', 'Side salad', 'French Fries', 'Mixed Fruit']\n\nmenu = zip(priceList, appetizers)\n\nsol = Solver()\nq = sol.solve(15.05, priceList)\nprint 'Total time it runned: ', sol.total\nprint '-'*30\norder = [(m, q.count(m[0])) for m in menu if m[0] in q]\nfor o in order:\n print '%d x %s \\t\\t\\t (%.2f)' % (o[1],o[0][1],o[0][0])\n\nprint '-'*30\nts = 'Total: %.2f' % sum(q)\nprint ' '*(30-len(ts)-1),ts\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Total time it runned: 29\n------------------------------\n1 x Sampler Plate (5.80)\n2 x Hot wings (3.55)\n1 x Mixed Fruit (2.15)\n------------------------------\n Total: 15.05\n</code></pre>\n" }, { "answer_id": 2022885, "author": "Scott McDonald", "author_id": 245805, "author_profile": "https://Stackoverflow.com/users/245805", "pm_score": 0, "selected": false, "text": "<p>If you want an optimized algorithm, it's best to try the prices in descending order. That lets you use up as much of the remaining amount first and then see how the rest can be filled in.</p>\n\n<p>Also, you can use math to figure out the maximum quantity of each food item to start each time so you don't try combinations that would go over the $15.05 goal.</p>\n\n<p>This algorithm only needs to try 88 combinations to get a complete answer and that looks like the lowest that's been posted so far:</p>\n\n<pre><code>public class NPComplete {\n private static final int[] FOOD = { 580, 420, 355, 335, 275, 215 };\n private static int tries;\n\n public static void main(String[] ignore) {\n tries = 0;\n addFood(1505, \"\", 0);\n System.out.println(\"Combinations tried: \" + tries);\n }\n\n private static void addFood(int goal, String result, int index) {\n // If no more food to add, see if this is a solution\n if (index &gt;= FOOD.length) {\n tries++;\n if (goal == 0)\n System.out.println(tries + \" tries: \" + result.substring(3));\n return;\n }\n\n // Try all possible quantities of this food\n // If this is the last food item, only try the max quantity\n int qty = goal / FOOD[index];\n do {\n addFood(goal - qty * FOOD[index],\n result + \" + \" + qty + \" * \" + FOOD[index], index + 1);\n } while (index &lt; FOOD.length - 1 &amp;&amp; --qty &gt;= 0);\n }\n}\n</code></pre>\n\n<p>Here's the output showing the two solutions:</p>\n\n<pre>\n9 tries: 1 * 580 + 0 * 420 + 2 * 355 + 0 * 335 + 0 * 275 + 1 * 215\n88 tries: 0 * 580 + 0 * 420 + 0 * 355 + 0 * 335 + 0 * 275 + 7 * 215\nCombinations tried: 88\n</pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
The problem/comic in question: <http://xkcd.com/287/> ![General solutions get you a 50% tip](https://imgs.xkcd.com/comics/np_complete.png) I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone. ``` <cffunction name="testCombo" returntype="boolean"> <cfargument name="currentCombo" type="string" required="true" /> <cfargument name="currentTotal" type="numeric" required="true" /> <cfargument name="apps" type="array" required="true" /> <cfset var a = 0 /> <cfset var found = false /> <cfloop from="1" to="#arrayLen(arguments.apps)#" index="a"> <cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) /> <cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost /> <cfif arguments.currentTotal eq 15.05> <!--- print current combo ---> <cfoutput><strong>#arguments.currentCombo# = 15.05</strong></cfoutput><br /> <cfreturn true /> <cfelseif arguments.currentTotal gt 15.05> <cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br /> <cfreturn false /> <cfelse> <!--- less than 15.05 ---> <cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br /> <cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) /> </cfif> </cfloop> </cffunction> <cfset mf = {name="Mixed Fruit", cost=2.15} /> <cfset ff = {name="French Fries", cost=2.75} /> <cfset ss = {name="side salad", cost=3.35} /> <cfset hw = {name="hot wings", cost=3.55} /> <cfset ms = {name="moz sticks", cost=4.20} /> <cfset sp = {name="sampler plate", cost=5.80} /> <cfset apps = [ mf, ff, ss, hw, ms, sp ] /> <cfloop from="1" to="6" index="b"> <cfoutput>#testCombo(apps[b].name, apps[b].cost, apps)#</cfoutput> </cfloop> ``` The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete. Is there a better algorithm to come to the correct solution? Did I come to the correct solution?
The point about an NP-complete problem is not that it's tricky on a small data set, but that the amount of work to solve it grows at a rate greater than polynomial, i.e. there is no O(n^x) algorithm. If the time complexity is O(n!), as in (I believe) the two problems mentioned above, that is in NP.
141,807
<p>I've got a really large project I made for myself and rece3ntly a client asked for their own version of it with some modifications. The project name was rather silly and my client wants the source so I figured it'd be best if I renamed all my files from</p> <pre><code>sillyname.h sillyname.cpp sillyname.dsp </code></pre> <p>etc.. Unfortunatly after I added everything back together I can't see any way to change the project name itself. Plus now I'm getting this error on compilation.</p> <pre><code>main.obj : error LNK2001: unresolved external symbol __imp__InitCommonControls@0 Debug/New_Name_Thats_not_so_silly.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. </code></pre> <p>There has to be an easier way to change all this, right?</p>
[ { "answer_id": 141839, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 0, "selected": false, "text": "<p>You can simply rename the .vcproj or .dsp file and then either create a new workspace (sln dsw) and include the renamed project or simply chnage the name inside the sln file (it's just xml) I can't remember the format of the old workspace but it's still text.</p>\n\n<p>You can either manually rename and reinclude all the .cpp of edit the project file and rename them in there.</p>\n\n<p>sorry don't know of refactoring tool that will do all this but there probably is one.</p>\n" }, { "answer_id": 141866, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 2, "selected": false, "text": "<p>Here is a <a href=\"http://www.platinumbay.com/blogs/dotneticated/archive/2008/01/01/renaming-and-copying-projects-and-solutions.aspx\" rel=\"nofollow noreferrer\">Step by Step</a> on Steve Andrews' blog (he works on Visual Studio at Microsoft)</p>\n" }, { "answer_id": 141929, "author": "Niklas", "author_id": 15323, "author_profile": "https://Stackoverflow.com/users/15323", "pm_score": 1, "selected": false, "text": "<p>I haven't verified this, but I've done this a number of times and if my memory serves me right, you can actually use the search-and-replace functionality in VS2005 to rename all instances of the string \"X\" to \"Y\" in any type of file.\nThen you need to close the solution and change the project (and any other file with the same name regardless of extension) file name(s).</p>\n\n<p>You will obviously need to do a full rebuild afterwards.</p>\n" }, { "answer_id": 141955, "author": "pestophagous", "author_id": 10278, "author_profile": "https://Stackoverflow.com/users/10278", "pm_score": 0, "selected": false, "text": "<p>I assume that in addition to the renamed set of files, you also still maintain a complete \"parallel\" set of the original files in some other directory, am I right?</p>\n\n<p>Assuming you have both versions, what I would do is:</p>\n\n<p>Get a file comparison tool like <a href=\"http://www.google.com/search?hl=en&amp;q=%22beyond+compare%22+%22scooter+software%22&amp;btnG=Search\" rel=\"nofollow noreferrer\">Beyond Compare</a> or <a href=\"http://www.google.com/search?hl=en&amp;q=sourcegear+diffmerge&amp;btnG=Search\" rel=\"nofollow noreferrer\">DiffMerge</a> and compare the old SLN file and the new SLN file side-by-side. Also do this for each \"proj\" file and any other \"config\" type files.</p>\n\n<p>It is possible to edit these files by hand. Usually looking at what is different between two copies will help illuminate what you should do to get the second one working.</p>\n\n<p>You might as well start tinkering with the renamed project by hand, anyway, given that it already isn't working. You can't make it much worse. And: you might learn some handy tricks about the XML structure of these files.</p>\n\n<p>Even if you do make small mistakes when hand-tweaking this files, I have repeatedly been very impressed by how Visual Studio handles things. Visual Studio will usually tell you exactly where you got it wrong.</p>\n" }, { "answer_id": 18336557, "author": "Philm", "author_id": 1469896, "author_profile": "https://Stackoverflow.com/users/1469896", "pm_score": 1, "selected": false, "text": "<p>I find it always annoying too, to do this manually.</p>\n\n<p>So I tried some tools available by googling- two didn't work (VS C++ here), dunno, if they are more useful for C#. </p>\n\n<p>The following tool worked good for me: I have used the trial version, but I will pay 39,- bucks for it. For me it is worth it. It has also a VS add-in. VS 2013 was not supported directly, at least not mentioned, yet, when I looked:\n<a href=\"http://www.kinook.com/CopyWiz\" rel=\"nofollow\">http://www.kinook.com/CopyWiz</a></p>\n\n<p>In-place rename didn't work (access error), but \"rename-while-copying\" worked fine.</p>\n\n<p>But I really wonder, if it is so difficult as some programmers claim. For most parts file renaming and a search&amp;replace of all occurences in all text files in the project dir should be a quite easy and working approach. Maybe someone can contibute what shall be so difficult.</p>\n\n<p>The rational part of my brain forbids the dreaming part to program an own tool- I am lucky ! :-)</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a really large project I made for myself and rece3ntly a client asked for their own version of it with some modifications. The project name was rather silly and my client wants the source so I figured it'd be best if I renamed all my files from ``` sillyname.h sillyname.cpp sillyname.dsp ``` etc.. Unfortunatly after I added everything back together I can't see any way to change the project name itself. Plus now I'm getting this error on compilation. ``` main.obj : error LNK2001: unresolved external symbol __imp__InitCommonControls@0 Debug/New_Name_Thats_not_so_silly.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. ``` There has to be an easier way to change all this, right?
Here is a [Step by Step](http://www.platinumbay.com/blogs/dotneticated/archive/2008/01/01/renaming-and-copying-projects-and-solutions.aspx) on Steve Andrews' blog (he works on Visual Studio at Microsoft)
141,808
<p>I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect. But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record <strong>is</strong> returned but the iext <strong>is not</strong> highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly.</p> <p>My code is as simple as:</p> <pre><code>&lt;%= highlight(result_pessoa.observacoes, search_string, '&lt;span style="background-color: yellow;"&gt;\1&lt;/span&gt;') %&gt; </code></pre>
[ { "answer_id": 141823, "author": "Kolten", "author_id": 13959, "author_profile": "https://Stackoverflow.com/users/13959", "pm_score": 0, "selected": false, "text": "<p>it sounds like you are using two different methods for deciding whether a match has occured or not: one for your search, and one for the hilight. Use the same method as your search for your highlighting and it should pick it up, no? </p>\n" }, { "answer_id": 146130, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "<p>Maybe you're searching UTF-8 strings directly against a MySQL database?</p>\n\n<p>A properly configured MySQL server (and likely any other mainstream database server) will perform correctly with case-insensitive and accent-insensitive comparisons.</p>\n\n<p>That's not the case of Ruby, though. As of version 1.8 Ruby does not support Unicode strings. So you are getting correct results from your database server but the Rails' <em>highlight</em> function, which uses <em>gsub</em>, fails to find your search string. You need to reimplement <em>highlight</em> using an Unicode-aware string library, like <a href=\"http://icu4r.rubyforge.org/\" rel=\"nofollow noreferrer\">ICU4R</a>.</p>\n" }, { "answer_id": 1922265, "author": "johno", "author_id": 233852, "author_profile": "https://Stackoverflow.com/users/233852", "pm_score": 3, "selected": true, "text": "<p>I've just submitted a patch to Rails thats solves this.</p>\n\n<p><a href=\"http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3593-patch-support-for-highlighting-with-ignoring-special-chars\" rel=\"nofollow noreferrer\">http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3593-patch-support-for-highlighting-with-ignoring-special-chars</a></p>\n\n<pre><code> # Highlights one or more +phrases+ everywhere in +text+ by inserting it into\n # a &lt;tt&gt;:highlighter&lt;/tt&gt; string. The highlighter can be specialized by passing &lt;tt&gt;:highlighter&lt;/tt&gt;\n # as a single-quoted string with \\1 where the phrase is to be inserted (defaults to\n # '&lt;strong class=\"highlight\"&gt;\\1&lt;/strong&gt;')\n #\n # ==== Examples\n # highlight('You searched for: rails', 'rails')\n # # =&gt; You searched for: &lt;strong class=\"highlight\"&gt;rails&lt;/strong&gt;\n #\n # highlight('You searched for: ruby, rails, dhh', 'actionpack')\n # # =&gt; You searched for: ruby, rails, dhh\n #\n # highlight('You searched for: rails', ['for', 'rails'], :highlighter =&gt; '&lt;em&gt;\\1&lt;/em&gt;')\n # # =&gt; You searched &lt;em&gt;for&lt;/em&gt;: &lt;em&gt;rails&lt;/em&gt;\n #\n # highlight('You searched for: rails', 'rails', :highlighter =&gt; '&lt;a href=\"search?q=\\1\"&gt;\\1&lt;/a&gt;')\n # # =&gt; You searched for: &lt;a href=\"search?q=rails\"&gt;rails&lt;/a&gt;\n #\n # highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars =&gt; true)\n # # =&gt; &lt;strong class=\"highlight\"&gt;Šumné&lt;/strong&gt; &lt;strong class=\"highlight\"&gt;dievča&lt;/strong&gt;tá \n #\n # You can still use &lt;tt&gt;highlight&lt;/tt&gt; with the old API that accepts the\n # +highlighter+ as its optional third parameter:\n # highlight('You searched for: rails', 'rails', '&lt;a href=\"search?q=\\1\"&gt;\\1&lt;/a&gt;') # =&gt; You searched for: &lt;a href=\"search?q=rails\"&gt;rails&lt;/a&gt;\n def highlight(text, phrases, *args)\n options = args.extract_options!\n unless args.empty?\n options[:highlighter] = args[0] || '&lt;strong class=\"highlight\"&gt;\\1&lt;/strong&gt;'\n end\n options.reverse_merge!(:highlighter =&gt; '&lt;strong class=\"highlight\"&gt;\\1&lt;/strong&gt;')\n\n if text.blank? || phrases.blank?\n text\n else\n haystack = text.clone\n match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')\n if options[:ignore_special_chars]\n haystack = haystack.mb_chars.normalize(:kd)\n match = match.mb_chars.normalize(:kd).gsub(/[^\\x00-\\x7F]+/n, '').gsub(/\\w/, '\\0[^\\x00-\\x7F]*')\n end\n highlighted = haystack.gsub(/(#{match})(?!(?:[^&lt;]*?)(?:[\"'])[^&lt;&gt;]*&gt;)/i, options[:highlighter])\n highlighted = highlighted.mb_chars.normalize(:kc) if options[:ignore_special_chars]\n highlighted\n end\n end\n</code></pre>\n" }, { "answer_id": 3574628, "author": "Vojto", "author_id": 304321, "author_profile": "https://Stackoverflow.com/users/304321", "pm_score": 0, "selected": false, "text": "<p>Here's my <a href=\"http://codingwithlove.com/thoughts/searching-documents-with-accented-characters\" rel=\"nofollow noreferrer\">article</a> that explains elegant solution where you don't need Rails or ActiveSupport.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect. But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record **is** returned but the iext **is not** highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly. My code is as simple as: ``` <%= highlight(result_pessoa.observacoes, search_string, '<span style="background-color: yellow;">\1</span>') %> ```
I've just submitted a patch to Rails thats solves this. <http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3593-patch-support-for-highlighting-with-ignoring-special-chars> ``` # Highlights one or more +phrases+ everywhere in +text+ by inserting it into # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt> # as a single-quoted string with \1 where the phrase is to be inserted (defaults to # '<strong class="highlight">\1</strong>') # # ==== Examples # highlight('You searched for: rails', 'rails') # # => You searched for: <strong class="highlight">rails</strong> # # highlight('You searched for: ruby, rails, dhh', 'actionpack') # # => You searched for: ruby, rails, dhh # # highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>') # # => You searched <em>for</em>: <em>rails</em> # # highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>') # # => You searched for: <a href="search?q=rails">rails</a> # # highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars => true) # # => <strong class="highlight">Šumné</strong> <strong class="highlight">dievča</strong>tá # # You can still use <tt>highlight</tt> with the old API that accepts the # +highlighter+ as its optional third parameter: # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a> def highlight(text, phrases, *args) options = args.extract_options! unless args.empty? options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>' end options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>') if text.blank? || phrases.blank? text else haystack = text.clone match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') if options[:ignore_special_chars] haystack = haystack.mb_chars.normalize(:kd) match = match.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]+/n, '').gsub(/\w/, '\0[^\x00-\x7F]*') end highlighted = haystack.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter]) highlighted = highlighted.mb_chars.normalize(:kc) if options[:ignore_special_chars] highlighted end end ```
141,864
<p>I need help understanding some C++ operator overload statements. The class is declared like this: </p> <pre><code>template &lt;class key_t, class ipdc_t&gt; class ipdc_map_template_t : public ipdc_lockable_t { ... typedef map&lt;key_t, ipdc_t*, less&lt;key_t&gt;&gt; map_t; ... </code></pre> <p>The creator of the class has created an iterator for the internal map structure:</p> <pre><code>struct iterator : public map_t::iterator { iterator() {} iterator(const map_t::iterator &amp; it) : map_t::iterator(it) {} iterator(const iterator &amp; it) : map_t::iterator( *static_cast&lt;const map_t::iterator *&gt;(&amp;it)) {} operator key_t() {return ((this-&gt;operator*()).first);} // I don't understand this. operator ipdc_t*() const {return ((this-&gt;operator*()).second);} // or this. }; </code></pre> <p>And begin() and end() return the begin() and end() of the map:</p> <pre><code>iterator begin() {IT_ASSERT(is_owner()); return map.begin();} iterator end() {return map.end();} </code></pre> <p>My question is, if I have an iterator, how do I use those overloads to get the key and the value?</p> <pre><code>ipdc_map_template_t::iterator iter; for( iter = my_instance.begin(); iter != my_instance.end(); ++iter ) { key_t my_key = ??????; ipdc_t *my_value = ??????; } </code></pre>
[ { "answer_id": 141893, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>The creator of the class has overridden the cast operators.\nSo by just assigning the iter to an object of the correct type it should auto cast itself via the methods into the correct values.</p>\n\n<p><b>N.B.</b>: The value type is being stored as a pointer. So when you extract the value you need to specify the pointer to the value type that you specified in the map interface.</p>\n\n<pre><code> typedef ipdc_map_template_t&lt;int,std::string&gt; MyMap;\n MyMap mymap;\n\n for(MyMap::iterator iter = mymap.begin();\n iter != mymap.end();\n ++iter )\n {\n int my_key = iter;\n std::string* my_value = iter;\n\n }\n</code></pre>\n\n<p>Not sure I agree with the direction taken here.\nDoes this make the code more readable? I would stick with the old fashioned map iterator sounds more usable. Is this container being defined in some specialized library that you need, or would it be beneficial to look at the boost pointer containers?</p>\n" }, { "answer_id": 141903, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 2, "selected": false, "text": "<p>operator key_t() and operator ipdc_t*() are both cast definitions. So, given an iterator as defined in the class, you should be able to simply assign your variables:</p>\n\n<pre><code>ipdc_map_template_t::iterator iter;\n for( iter = my_instance.begin();\n iter != my_instance.end();\n ++iter )\n {\n key_t my_key = iter;\n ipdc_t my_value = iter;\n }\n</code></pre>\n" }, { "answer_id": 141926, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 4, "selected": true, "text": "<p>These are typecast operators, so you can do this:</p>\n\n<pre><code>{\n key_t key = iter;\n ipdc_t *val = iter;\n}\n</code></pre>\n\n<p>Or, since <code>ipdc_map_template::iterator</code> is a subclass of <code>std::map::iterator</code>, you can still use the original accessors (which I find more readable):</p>\n\n<pre><code>{\n key_t key = (*iter).first;\n ipdc_t *val = (*iter).second;\n\n // or, equivalently\n key_t key = iter-&gt;first;\n ipdc_t *val = iter-&gt;second;\n\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19719/" ]
I need help understanding some C++ operator overload statements. The class is declared like this: ``` template <class key_t, class ipdc_t> class ipdc_map_template_t : public ipdc_lockable_t { ... typedef map<key_t, ipdc_t*, less<key_t>> map_t; ... ``` The creator of the class has created an iterator for the internal map structure: ``` struct iterator : public map_t::iterator { iterator() {} iterator(const map_t::iterator & it) : map_t::iterator(it) {} iterator(const iterator & it) : map_t::iterator( *static_cast<const map_t::iterator *>(&it)) {} operator key_t() {return ((this->operator*()).first);} // I don't understand this. operator ipdc_t*() const {return ((this->operator*()).second);} // or this. }; ``` And begin() and end() return the begin() and end() of the map: ``` iterator begin() {IT_ASSERT(is_owner()); return map.begin();} iterator end() {return map.end();} ``` My question is, if I have an iterator, how do I use those overloads to get the key and the value? ``` ipdc_map_template_t::iterator iter; for( iter = my_instance.begin(); iter != my_instance.end(); ++iter ) { key_t my_key = ??????; ipdc_t *my_value = ??????; } ```
These are typecast operators, so you can do this: ``` { key_t key = iter; ipdc_t *val = iter; } ``` Or, since `ipdc_map_template::iterator` is a subclass of `std::map::iterator`, you can still use the original accessors (which I find more readable): ``` { key_t key = (*iter).first; ipdc_t *val = (*iter).second; // or, equivalently key_t key = iter->first; ipdc_t *val = iter->second; } ```
141,875
<p>What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:</p> <pre><code>number: (MONTH|INT); </code></pre> <p>It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:</p> <pre><code>date: month '/' day ( '/' year )? -&gt; ^('DATE' year month day); </code></pre> <p>I don't care if month,day &amp; year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:</p> <pre><code>foo: STRING OP number -&gt; ^(OP STRING number); STRING: ('a'..'z')+; OP: ('&lt;'|'&gt;'); </code></pre>
[ { "answer_id": 142009, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "<p>The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser. It's a common mistake, and something that is only possible in very simple languages.</p>\n\n<p>What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks. How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs. I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates. The first approach:</p>\n\n<pre><code>INT: '0'..'9'+;\n</code></pre>\n\n<p>The second approach:</p>\n\n<pre><code>DATENUM: '0' '1'..'9';\nINT: '0' | SIGN? '1'..'9' '0'..'9'*;\n</code></pre>\n\n<p>After accepting using these rules in the lexer, your date field would be either:</p>\n\n<pre><code>date: INT '/' INT ( '/' INT )?\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?\n</code></pre>\n\n<p>After that, you would perform a semantic run over your AST to make sure that your dates are valid.</p>\n\n<p>If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:</p>\n\n<pre><code>date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}\n</code></pre>\n\n<p>When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.</p>\n" }, { "answer_id": 31711538, "author": "simonrkeen", "author_id": 5171119, "author_profile": "https://Stackoverflow.com/users/5171119", "pm_score": 1, "selected": false, "text": "<p>Using ANTLR4, here is a simple combined grammar that I used. It makes use of the lexer to match simple tokens only, leaving the parser rules to interpret dates vs numbers. </p>\n\n<pre><code>// parser rules\n\ndate \n : INT SEPARATOR month SEPARATOR INT\n | INT SEPARATOR month SEPARATOR INT4\n | INT SEPARATOR INT SEPARATOR INT4;\n\nmonth : JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC ;\n\nnumber : FLOAT | INT | INT4 ;\n\n// lexer rules\n\nFLOAT : DIGIT+ '.' DIGIT+ ;\n\nINT4 : DIGIT DIGIT DIGIT DIGIT;\nINT : DIGIT+;\n\nJAN : [Jj][Aa][Nn] ;\nFEB : [Ff][Ee][Bb] ;\nMAR : [Mm][Aa][Rr] ;\nAPR : [Aa][Pp][Rr] ;\nMAY : [Mm][Aa][Yy] ; \nJUN : [Jj][Uu][Nn] ;\nJUL : [Jj][Uu][Ll] ;\nAUG : [Aa][Uu][Gg] ;\nSEP : [Ss][Ee][Pp] ; \nOCT : [Oo][Cc][Tt] ; \nNOV : [Nn][Oo][Vv] ;\nDEC : [Dd][Ee][Cc] ;\n\nSEPARATOR : [/\\\\\\-] ;\n\nfragment DIGIT : [0-9];\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12034/" ]
What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like: ``` number: (MONTH|INT); ``` It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this: ``` date: month '/' day ( '/' year )? -> ^('DATE' year month day); ``` I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.: ``` foo: STRING OP number -> ^(OP STRING number); STRING: ('a'..'z')+; OP: ('<'|'>'); ```
The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser. It's a common mistake, and something that is only possible in very simple languages. What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks. How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs. I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates. The first approach: ``` INT: '0'..'9'+; ``` The second approach: ``` DATENUM: '0' '1'..'9'; INT: '0' | SIGN? '1'..'9' '0'..'9'*; ``` After accepting using these rules in the lexer, your date field would be either: ``` date: INT '/' INT ( '/' INT )? ``` or: ``` date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )? ``` After that, you would perform a semantic run over your AST to make sure that your dates are valid. If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this: ``` date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)} ``` When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.
141,876
<p>Platform: Windows XP Development Platform: VB6</p> <p>When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.</p> <p>Does anyone have a workaround or fix for this? </p> <hr> <p>Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) . </p> <p>Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string. </p> <p>I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB. </p>
[ { "answer_id": 142183, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 1, "selected": false, "text": "<p>It appears that VB6 limits the App.Title property to 40 characters. Unfortunately, I can't locate any documentation on MSDN detailing this behavior. (And unfortunately, I don't have documentation loaded onto the machine where my copy of VB6 still resides.)</p>\n\n<p>I ran an experiment with long titles, and that was the observed behavior. If your title is longer than 40 characters, it simply will get truncated.</p>\n" }, { "answer_id": 142214, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 2, "selected": false, "text": "<p>I just created a Standard EXE project in the IDE and typed text into the application title field under the Project Properties Make tab until I filled the field. From this quick test, it appears that App.Title is limited to 40 characters. Next I tried it in code by putting the following code in the default form (Form1) created for the project:</p>\n\n<pre><code>Private Sub Form_Load()\n App.Title = String(41, \"X\")\n MsgBox Len(App.Title)\nEnd Sub\n</code></pre>\n\n<p>This quick test confirms the 40-characater limit, because the MsgBox displays 40, even though the code attempts to set App.Title to a 41-character string.</p>\n\n<p>If it's really important to get the full string to display in the titlebar of a Form, then only way I can think of to ensure that the entire title is displayed would be to get the width of the titlebar text and use that to increase the width of your Form so that it can accommodate the complete title string. I may come back and post code for this if I can find the right API incantations, but it might look something like this in the Form_Load event:</p>\n\n<pre><code>Dim nTitleBarTextWidth As Long\nDim nNewWidth As Long\n\nMe.Caption = \"My really really really really really long app title here\"\n\n' Get titlebar text width (somehow) '\nnTitleBarTextWidth = GetTitleBarTextWidth()\n\n' Compute the new width for the Form such that the title will fit within it '\n' (May have to add a constant to this to make sure the title fits correctly) '\nnNewWidth = Me.ScaleX(nTitleBarTextWidth, vbPixels, Me.ScaleMode)\n\n' If the new width is bigger than the forms current size, use the new width '\nIf nNewWidth &gt; Me.Width Then\n Form.Width = nNewWidth\nEnd If\n</code></pre>\n" }, { "answer_id": 142943, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 3, "selected": true, "text": "<h2>One solution using the Windows API</h2>\n\n<p><br/>\n<strong>Disclaimer</strong>: <em>IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...</em></p>\n\n<p>Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning.</p>\n\n<ul>\n<li>See the <a href=\"http://www.vbaccelerator.com/home/VB/Tips/Get_System_Display_Fonts_and_Non-Client_Area_Sizes/article.asp\" rel=\"nofollow noreferrer\">vbAccelerator</a> page for the original article (not directly related to the question, but there was enough there for me to formulate an answer)</li>\n</ul>\n\n<p>The basic premise is to first calculate the width of the form's caption text and then to use <strong>GetSystemMetrics</strong> to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form.</p>\n\n<p>In order to accurately calculate the width (\"extent\") of the form's caption, we need to get the system caption font, hence the <strong>SystemParametersInfo</strong> and <strong>CreateFontIndirect</strong> calls and related goodness.</p>\n\n<p>The end result all this effort is the <strong>GetRecommendedWidth</strong> function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width.</p>\n\n<p>I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either. </p>\n\n<p>By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know.</p>\n\n<p><strong>To try it out, paste the following code into a new module</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Type SIZE\n cx As Long\n cy As Long\nEnd Type\n\nPrivate Const LF_FACESIZE = 32\n\n'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'\n' '\n' For some bizarre reason, maybe to do with byte '\n' alignment, the LOGFONT structure we must apply '\n' to NONCLIENTMETRICS seems to require an LF_FACESIZE '\n' 4 bytes smaller than normal: '\n\nPrivate Type NMLOGFONT\n lfHeight As Long\n lfWidth As Long\n lfEscapement As Long\n lfOrientation As Long\n lfWeight As Long\n lfItalic As Byte\n lfUnderline As Byte\n lfStrikeOut As Byte\n lfCharSet As Byte\n lfOutPrecision As Byte\n lfClipPrecision As Byte\n lfQuality As Byte\n lfPitchAndFamily As Byte\n lfFaceName(LF_FACESIZE - 4) As Byte\nEnd Type\n\nPrivate Type LOGFONT\n lfHeight As Long\n lfWidth As Long\n lfEscapement As Long\n lfOrientation As Long\n lfWeight As Long\n lfItalic As Byte\n lfUnderline As Byte\n lfStrikeOut As Byte\n lfCharSet As Byte\n lfOutPrecision As Byte\n lfClipPrecision As Byte\n lfQuality As Byte\n lfPitchAndFamily As Byte\n lfFaceName(LF_FACESIZE) As Byte\nEnd Type\n\nPrivate Type NONCLIENTMETRICS\n cbSize As Long\n iBorderWidth As Long\n iScrollWidth As Long\n iScrollHeight As Long\n iCaptionWidth As Long\n iCaptionHeight As Long\n lfCaptionFont As NMLOGFONT\n iSMCaptionWidth As Long\n iSMCaptionHeight As Long\n lfSMCaptionFont As NMLOGFONT\n iMenuWidth As Long\n iMenuHeight As Long\n lfMenuFont As NMLOGFONT\n lfStatusFont As NMLOGFONT\n lfMessageFont As NMLOGFONT\nEnd Type\n\nPrivate Enum SystemMetrics\n SM_CXBORDER = 5\n SM_CXDLGFRAME = 7\n SM_CXFRAME = 32\n SM_CXSCREEN = 0\n SM_CXICON = 11\n SM_CXICONSPACING = 38\n SM_CXSIZE = 30\n SM_CXEDGE = 45\n SM_CXSMICON = 49\n SM_CXSMSIZE = 52\nEnd Enum\n\nPrivate Const SPI_GETNONCLIENTMETRICS = 41\nPrivate Const SPI_SETNONCLIENTMETRICS = 42\n\nPrivate Declare Function GetTextExtentPoint32 Lib \"gdi32\" Alias \"GetTextExtentPoint32A\" _\n (ByVal hdc As Long, _\n ByVal lpszString As String, _\n ByVal cbString As Long, _\n lpSize As SIZE) As Long\n\nPrivate Declare Function GetSystemMetrics Lib \"user32\" (ByVal nIndex As SystemMetrics) As Long\n\nPrivate Declare Function SystemParametersInfo Lib \"user32\" Alias \"SystemParametersInfoA\" ( _\n ByVal uAction As Long, _\n ByVal uParam As Long, _\n lpvParam As Any, _\n ByVal fuWinIni As Long) As Long\n\nPrivate Declare Function SelectObject Lib \"gdi32\" (ByVal hdc As Long, ByVal hObject As Long) As Long\nPrivate Declare Function DeleteObject Lib \"gdi32\" (ByVal hObject As Long) As Long\nPrivate Declare Function CreateFontIndirect Lib \"gdi32\" Alias \"CreateFontIndirectA\" (lpLogFont As LOGFONT) As Long\n\nPrivate Declare Sub CopyMemory Lib \"kernel32\" Alias \"RtlMoveMemory\" (Destination As Any, Source As Any, ByVal Length As Long)\n\nPrivate Function GetCaptionTextWidth(ByVal frm As Form) As Long\n\n '-----------------------------------------------'\n ' This function does the following: '\n ' '\n ' 1. Get the font used for the forms caption '\n ' 2. Call GetTextExtent32 to get the width in '\n ' pixels of the forms caption '\n ' 3. Convert the width from pixels into '\n ' the scaling mode being used by the form '\n ' '\n '-----------------------------------------------'\n\n Dim sz As SIZE\n Dim hOldFont As Long\n Dim hCaptionFont As Long\n Dim CaptionFont As LOGFONT\n Dim ncm As NONCLIENTMETRICS\n\n ncm.cbSize = LenB(ncm)\n\n If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then\n ' What should we do if we the call fails? Change as needed for your app,'\n ' but this call is unlikely to fail anyway'\n Exit Function\n End If\n\n CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)\n\n hCaptionFont = CreateFontIndirect(CaptionFont)\n hOldFont = SelectObject(frm.hdc, hCaptionFont)\n\n GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz\n GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)\n\n 'clean up, otherwise bad things will happen...'\n DeleteObject (SelectObject(frm.hdc, hOldFont))\n\nEnd Function\n\nPrivate Function GetControlBoxWidth(ByVal frm As Form) As Long\n\n Dim nButtonWidth As Long\n Dim nButtonCount As Long\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n nButtonCount = 1 'close button is always present'\n nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'\n\n ' account for min and max buttons if they are visible'\n If frm.MinButton Then nButtonCount = nButtonCount + 1\n If frm.MaxButton Then nButtonCount = nButtonCount + 1\n\n nFinalWidth = nButtonWidth * nButtonCount\n\n End If\n\n 'convert to whatever scale the form is using'\n GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetIconWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.BorderStyle\n\n Case vbFixedSingle, vbFixedDialog, vbSizable:\n 'we have an icon, gets its width'\n nFinalWidth = GetSystemMetrics(SM_CXSMICON)\n Case Else:\n 'no icon present, so report zero width'\n nFinalWidth = 0\n\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetFrameWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.BorderStyle\n\n Case vbFixedSingle, vbFixedDialog:\n nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)\n Case vbSizable:\n nFinalWidth = GetSystemMetrics(SM_CXFRAME)\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPrivate Function GetBorderWidth(ByVal frm As Form) As Long\n\n Dim nFinalWidth As Long\n\n If frm.ControlBox Then\n\n Select Case frm.Appearance\n\n Case 0 'flat'\n nFinalWidth = GetSystemMetrics(SM_CXBORDER)\n Case 1 '3D'\n nFinalWidth = GetSystemMetrics(SM_CXEDGE)\n End Select\n\n End If\n\n 'convert to whatever scale the form is using'\n GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)\n\nEnd Function\n\nPublic Function GetRecommendedWidth(ByVal frm As Form) As Long\n\n Dim nNewWidth As Long\n\n ' An abitrary amount of extra padding so that the caption text '\n ' is not scrunched up against the min/max/close buttons '\n\n Const PADDING_TWIPS = 120\n\n nNewWidth = _\n GetCaptionTextWidth(frm) _\n + GetControlBoxWidth(frm) _\n + GetIconWidth(frm) _\n + GetFrameWidth(frm) * 2 _\n + GetBorderWidth(frm) * 2 _\n + PADDING_TWIPS\n\n If nNewWidth &gt; frm.Width Then\n GetRecommendedWidth = nNewWidth\n Else\n GetRecommendedWidth = frm.Width\n End If\n\nEnd Function\n</code></pre>\n\n<p><strong>Then place the following in your Form_Load event</strong></p>\n\n<pre><code>Private Sub Form_Load()\n\n Me.Caption = String(100, \"x\") 'replace this with your caption'\n Me.Width = GetRecommendedWidth(Me)\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 143411, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 2, "selected": false, "text": "<p>The MsgBox-Function takes a parameter for the title. If you dont want to change every single call to the MsgBox-Function, you could \"override\" the default behavior:</p>\n\n<pre><code>Function MsgBox(Prompt, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title, Optional HelpFile, Optional Context) As VbMsgBoxResult\n If IsMissing(Title) Then Title = String(40, \"x\") &amp; \"abc\"\n MsgBox = Interaction.MsgBox(Prompt, Buttons, Title, HelpFile, Context)\nEnd Function\n</code></pre>\n\n<p>Edit: As Mike Spross notes: This only hides the normal MsgBox-Function. If you wanted to access your custom MsgBox from another project, you would have to qualify it.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
Platform: Windows XP Development Platform: VB6 When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed. Does anyone have a workaround or fix for this? --- Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) . Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string. I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB.
One solution using the Windows API ---------------------------------- **Disclaimer**: *IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...* Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning. * See the [vbAccelerator](http://www.vbaccelerator.com/home/VB/Tips/Get_System_Display_Fonts_and_Non-Client_Area_Sizes/article.asp) page for the original article (not directly related to the question, but there was enough there for me to formulate an answer) The basic premise is to first calculate the width of the form's caption text and then to use **GetSystemMetrics** to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form. In order to accurately calculate the width ("extent") of the form's caption, we need to get the system caption font, hence the **SystemParametersInfo** and **CreateFontIndirect** calls and related goodness. The end result all this effort is the **GetRecommendedWidth** function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width. I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either. By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know. **To try it out, paste the following code into a new module** ``` Option Explicit Private Type SIZE cx As Long cy As Long End Type Private Const LF_FACESIZE = 32 'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):' ' ' ' For some bizarre reason, maybe to do with byte ' ' alignment, the LOGFONT structure we must apply ' ' to NONCLIENTMETRICS seems to require an LF_FACESIZE ' ' 4 bytes smaller than normal: ' Private Type NMLOGFONT lfHeight As Long lfWidth As Long lfEscapement As Long lfOrientation As Long lfWeight As Long lfItalic As Byte lfUnderline As Byte lfStrikeOut As Byte lfCharSet As Byte lfOutPrecision As Byte lfClipPrecision As Byte lfQuality As Byte lfPitchAndFamily As Byte lfFaceName(LF_FACESIZE - 4) As Byte End Type Private Type LOGFONT lfHeight As Long lfWidth As Long lfEscapement As Long lfOrientation As Long lfWeight As Long lfItalic As Byte lfUnderline As Byte lfStrikeOut As Byte lfCharSet As Byte lfOutPrecision As Byte lfClipPrecision As Byte lfQuality As Byte lfPitchAndFamily As Byte lfFaceName(LF_FACESIZE) As Byte End Type Private Type NONCLIENTMETRICS cbSize As Long iBorderWidth As Long iScrollWidth As Long iScrollHeight As Long iCaptionWidth As Long iCaptionHeight As Long lfCaptionFont As NMLOGFONT iSMCaptionWidth As Long iSMCaptionHeight As Long lfSMCaptionFont As NMLOGFONT iMenuWidth As Long iMenuHeight As Long lfMenuFont As NMLOGFONT lfStatusFont As NMLOGFONT lfMessageFont As NMLOGFONT End Type Private Enum SystemMetrics SM_CXBORDER = 5 SM_CXDLGFRAME = 7 SM_CXFRAME = 32 SM_CXSCREEN = 0 SM_CXICON = 11 SM_CXICONSPACING = 38 SM_CXSIZE = 30 SM_CXEDGE = 45 SM_CXSMICON = 49 SM_CXSMSIZE = 52 End Enum Private Const SPI_GETNONCLIENTMETRICS = 41 Private Const SPI_SETNONCLIENTMETRICS = 42 Private Declare Function GetTextExtentPoint32 Lib "gdi32" Alias "GetTextExtentPoint32A" _ (ByVal hdc As Long, _ ByVal lpszString As String, _ ByVal cbString As Long, _ lpSize As SIZE) As Long Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As SystemMetrics) As Long Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" ( _ ByVal uAction As Long, _ ByVal uParam As Long, _ lpvParam As Any, _ ByVal fuWinIni As Long) As Long Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) Private Function GetCaptionTextWidth(ByVal frm As Form) As Long '-----------------------------------------------' ' This function does the following: ' ' ' ' 1. Get the font used for the forms caption ' ' 2. Call GetTextExtent32 to get the width in ' ' pixels of the forms caption ' ' 3. Convert the width from pixels into ' ' the scaling mode being used by the form ' ' ' '-----------------------------------------------' Dim sz As SIZE Dim hOldFont As Long Dim hCaptionFont As Long Dim CaptionFont As LOGFONT Dim ncm As NONCLIENTMETRICS ncm.cbSize = LenB(ncm) If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then ' What should we do if we the call fails? Change as needed for your app,' ' but this call is unlikely to fail anyway' Exit Function End If CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont) hCaptionFont = CreateFontIndirect(CaptionFont) hOldFont = SelectObject(frm.hdc, hCaptionFont) GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode) 'clean up, otherwise bad things will happen...' DeleteObject (SelectObject(frm.hdc, hOldFont)) End Function Private Function GetControlBoxWidth(ByVal frm As Form) As Long Dim nButtonWidth As Long Dim nButtonCount As Long Dim nFinalWidth As Long If frm.ControlBox Then nButtonCount = 1 'close button is always present' nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar' ' account for min and max buttons if they are visible' If frm.MinButton Then nButtonCount = nButtonCount + 1 If frm.MaxButton Then nButtonCount = nButtonCount + 1 nFinalWidth = nButtonWidth * nButtonCount End If 'convert to whatever scale the form is using' GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode) End Function Private Function GetIconWidth(ByVal frm As Form) As Long Dim nFinalWidth As Long If frm.ControlBox Then Select Case frm.BorderStyle Case vbFixedSingle, vbFixedDialog, vbSizable: 'we have an icon, gets its width' nFinalWidth = GetSystemMetrics(SM_CXSMICON) Case Else: 'no icon present, so report zero width' nFinalWidth = 0 End Select End If 'convert to whatever scale the form is using' GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode) End Function Private Function GetFrameWidth(ByVal frm As Form) As Long Dim nFinalWidth As Long If frm.ControlBox Then Select Case frm.BorderStyle Case vbFixedSingle, vbFixedDialog: nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME) Case vbSizable: nFinalWidth = GetSystemMetrics(SM_CXFRAME) End Select End If 'convert to whatever scale the form is using' GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode) End Function Private Function GetBorderWidth(ByVal frm As Form) As Long Dim nFinalWidth As Long If frm.ControlBox Then Select Case frm.Appearance Case 0 'flat' nFinalWidth = GetSystemMetrics(SM_CXBORDER) Case 1 '3D' nFinalWidth = GetSystemMetrics(SM_CXEDGE) End Select End If 'convert to whatever scale the form is using' GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode) End Function Public Function GetRecommendedWidth(ByVal frm As Form) As Long Dim nNewWidth As Long ' An abitrary amount of extra padding so that the caption text ' ' is not scrunched up against the min/max/close buttons ' Const PADDING_TWIPS = 120 nNewWidth = _ GetCaptionTextWidth(frm) _ + GetControlBoxWidth(frm) _ + GetIconWidth(frm) _ + GetFrameWidth(frm) * 2 _ + GetBorderWidth(frm) * 2 _ + PADDING_TWIPS If nNewWidth > frm.Width Then GetRecommendedWidth = nNewWidth Else GetRecommendedWidth = frm.Width End If End Function ``` **Then place the following in your Form\_Load event** ``` Private Sub Form_Load() Me.Caption = String(100, "x") 'replace this with your caption' Me.Width = GetRecommendedWidth(Me) End Sub ```
141,878
<p>The following snippet is supposed to take the value of PROJECT (defined in the Makefile) and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR</p> <p>I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?</p> <pre><code>#define PROJECT classifier #define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define MAKEINC(x) x ## _ir.h #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC) #include PROJECTINCSTR </code></pre> <p>Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.</p>
[ { "answer_id": 141919, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 0, "selected": false, "text": "<p>That barebone example works with gcc (v4.1.2) and tries to include \"PROJECT_ir.h\"</p>\n" }, { "answer_id": 141930, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 4, "selected": true, "text": "<pre><code>#define QMAKESTR(x) #x\n#define MAKESTR(x) QMAKESTR(x)\n#define SMASH(x,y) x##y\n#define MAKEINC(x) SMASH(x,_ir.h)\n#define PROJECTINC MAKEINC(PROJECT)\n#define PROJECTINCSTR MAKESTR(PROJECTINC)</code></pre>\n" }, { "answer_id": 141962, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "<p>This works for me:</p>\n\n<pre><code>#define QMAKESTR(x) #x\n#define MAKESTR(x) QMAKESTR(x)\n#define MAKEINC(x) x ## _ir.h\n#define PROJECTINC(x) MAKEINC(x)\n#define PROJECTINCSTR MAKESTR(PROJECTINC(PROJECT))\n\n#include PROJECTINCSTR\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22781/" ]
The following snippet is supposed to take the value of PROJECT (defined in the Makefile) and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier\_ir.h for PROJECTINCSTR I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped? ``` #define PROJECT classifier #define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define MAKEINC(x) x ## _ir.h #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC) #include PROJECTINCSTR ``` Edit: The compiler should try to include classifier\_ir.h, not PROJECT\_ir.h.
``` #define QMAKESTR(x) #x #define MAKESTR(x) QMAKESTR(x) #define SMASH(x,y) x##y #define MAKEINC(x) SMASH(x,_ir.h) #define PROJECTINC MAKEINC(PROJECT) #define PROJECTINCSTR MAKESTR(PROJECTINC) ```
141,913
<p>I'm parsing XML results from an API call using PHP and xpath. </p> <pre><code> $dom = new DOMDocument(); $dom-&gt;loadXML($response-&gt;getBody()); $xpath = new DOMXPath($dom); $xpath-&gt;registerNamespace("a", "http://www.example.com"); $hrefs = $xpath-&gt;query('//a:Books/text()', $dom); for ($i = 0; $i &lt; $hrefs-&gt;length; $i++) { $arrBookTitle[$i] = $hrefs-&gt;item($i)-&gt;data; } $hrefs = $xpath-&gt;query('//a:Books', $dom); for ($i = 0; $i &lt; $hrefs-&gt;length; $i++) { $arrBookDewey[$i] = $hrefs-&gt;item($i)-&gt;getAttribute('DeweyDecimal'); } </code></pre> <p>This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?</p>
[ { "answer_id": 141933, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>Could you query for the concatenation?</p>\n\n<pre><code>$xpath-&gt;query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);\n</code></pre>\n\n<p>XSLT is an expression language in itself, and you can construct whatever specific format of return value you want from within the expression.</p>\n" }, { "answer_id": 143029, "author": "Scott Gottreu", "author_id": 2863, "author_profile": "https://Stackoverflow.com/users/2863", "pm_score": 3, "selected": true, "text": "<p>After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node.</p>\n\n<pre><code>$hrefs = $xpath-&gt;query('//a:Books', $dom);\n\nfor ($i = 0; $i &lt; $hrefs-&gt;length; $i++) {\n $arrBookTitle[$i] = $hrefs-&gt;item($i)-&gt;nodeValue;\n $arrBookDewey[$i] = $hrefs-&gt;item($i)-&gt;getAttribute('DeweyDecimal');\n}\n</code></pre>\n" }, { "answer_id": 143360, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "<p>If your're just retrieving values from your XML document, <a href=\"http://de.php.net/manual/en/book.simplexml.php\" rel=\"nofollow noreferrer\">SimpleXML</a> might be the leaner, faster and memory-friendlier solution:</p>\n\n<pre><code>$xml=simplexml_load_string($response-&gt;getBody());\n$xml-&gt;registerXPathNamespace('a', 'http://www.example.com');\n$books=$xml-&gt;xpath('//a:Books');\nforeach ($books as $i =&gt; $book) {\n $arrBookTitle[$i]=(string)$book;\n $arrBookDewey[$i]=$book['DeweyDecimal'];\n}\n</code></pre>\n" }, { "answer_id": 328375, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "<p>One single XPath expression that will select both the text nodes of \"a:Books\" and their \"DeweyDecimal\" attribute, is the following</p>\n\n<p><code>//a:Books/text() | //a:Books/@DeweyDecimal</code></p>\n\n<p><strong>Do note</strong> the use of the XPath's union operator in the expression above.</p>\n\n<p><strong>Another note</strong>: try to avoid using the \"//\" abbreviation as it may cause the whole XML document to be traversed and thus is very expensive. It is recommended to use a more specific XPath expression (such as consisting of a chain of specific location steps) always when the structure of the XML document is known.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
I'm parsing XML results from an API call using PHP and xpath. ``` $dom = new DOMDocument(); $dom->loadXML($response->getBody()); $xpath = new DOMXPath($dom); $xpath->registerNamespace("a", "http://www.example.com"); $hrefs = $xpath->query('//a:Books/text()', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookTitle[$i] = $hrefs->item($i)->data; } $hrefs = $xpath->query('//a:Books', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal'); } ``` This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?
After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node. ``` $hrefs = $xpath->query('//a:Books', $dom); for ($i = 0; $i < $hrefs->length; $i++) { $arrBookTitle[$i] = $hrefs->item($i)->nodeValue; $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal'); } ```
141,939
<p>I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting </p> <pre><code>./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj </code></pre> <p>Which c++filt describes as </p> <pre><code>std::_Rb_tree&lt;unsigned int, unsigned int, std::_Identity&lt;unsigned int&gt;, std::less&lt;unsigned int&gt;, std::allocator&lt;unsigned int&gt; &gt;::insert_unique(unsigned int const&amp;) </code></pre> <p>I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including <code>-lstdc++</code>.</p> <p>Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?</p> <p><em>EDIT:</em> After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.</p>
[ { "answer_id": 141957, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 1, "selected": false, "text": "<p><code>std::_Rb_Tree</code> might be a red-black tree, which would most likely be from using <code>map</code>. It should be part of <code>libstdc++</code>, unless your library is linking against a different version of <code>libstdc++</code> than the application, which from what you've said so far seems unlikely.</p>\n\n<p>EDIT: Just to clarify, the red-black tree is the underlying data structure in <code>map</code>. All that <code>hash_map</code> does is hash the key before using it, rather than using the raw value.</p>\n" }, { "answer_id": 141977, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>Try <pre><code>#include &lt; map > </code></pre> in the source file where you are using map.</p>\n" }, { "answer_id": 142763, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You seem to have 2 different incompatible versions of libstdc++.so from different versions of gcc. Check your paths.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209/" ]
I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting ``` ./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj ``` Which c++filt describes as ``` std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&) ``` I thought this might have come from using hash\_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including `-lstdc++`. Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to? *EDIT:* After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.
`std::_Rb_Tree` might be a red-black tree, which would most likely be from using `map`. It should be part of `libstdc++`, unless your library is linking against a different version of `libstdc++` than the application, which from what you've said so far seems unlikely. EDIT: Just to clarify, the red-black tree is the underlying data structure in `map`. All that `hash_map` does is hash the key before using it, rather than using the raw value.
141,970
<p>I'm experimenting with generics and I'm trying to create structure similar to Dataset class.<br> I have following code</p> <pre><code>public struct Column&lt;T&gt; { T value; T originalValue; public bool HasChanges { get { return !value.Equals(originalValue); } } public void AcceptChanges() { originalValue = value; } } public class Record { Column&lt;int&gt; id; Column&lt;string&gt; name; Column&lt;DateTime?&gt; someDate; Column&lt;int?&gt; someInt; public bool HasChanges { get { return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges; } } public void AcceptChanges() { id.AcceptChanges(); name.AcceptChanges(); someDate.AcceptChanges(); someInt.AcceptChanges(); } } </code></pre> <p>Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.<br> So first solution that cames to my mind was something like this:</p> <pre><code>public interface IColumn { bool HasChanges { get; } void AcceptChanges(); } public struct Column&lt;T&gt; : IColumn {...} public class Record { Column&lt;int&gt; id; Column&lt;string&gt; name; Column&lt;DateTime?&gt; someDate; Column&lt;int?&gt; someInt; IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }} public bool HasChanges { get { bool has = false; IColumn[] columns = Columns; //clone and boxing for (int i = 0; i &lt; columns.Length; i++) has |= columns[i].HasChanges; return has; } } public void AcceptChanges() { IColumn[] columns = Columns; //clone and boxing for (int i = 0; i &lt; columns.Length; i++) columns[i].AcceptChanges(); //Here we are changing clone } } </code></pre> <p>As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me. <br> <br> So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage. <br> <br> <strong>Edit:</strong><br> sfg thanks for suggestion about macros.<br> In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.<br><br> Some usefull links:<br> <a href="http://www.t4editor.net/" rel="nofollow noreferrer" title="T4 Editor for VS">T4 Editor for VS</a><br> <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" rel="nofollow noreferrer" title="Blog with links and tutorials about T4">Blog with links and tutorials about T4</a><br> <a href="http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/" rel="nofollow noreferrer" title="Blog entry with example that uses EnvDTE to read project files">Blog entry with example that uses EnvDTE to read project files</a></p>
[ { "answer_id": 142115, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>You could use reflection to iterate over the members and invoke HasChanges and AcceptChanges. The Record class could store the reflection metadata as a static so there is no per-instance memory overhead. However, the performance cost at runtime is going to be huge -- you might also end up boxing and unboxing the column which would add even more to the cost.</p>\n" }, { "answer_id": 142180, "author": "sfg", "author_id": 19830, "author_profile": "https://Stackoverflow.com/users/19830", "pm_score": 2, "selected": true, "text": "<p>As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#. </p>\n\n<p>In terms of performance: the macro would be evaluated at compile time (thus slowing compilation a tiny amount), but would cause no slow-down at run-time as the run-time code would be the same as what you would write manually.</p>\n\n<p>I think you might have to accept your original AcceptChanges() as you need to access the structs directly by their identifiers if you want to avoid writing to cloned versions.</p>\n\n<p>In other words: you need a program to write the program for you, and I do not know how to do that in C# without going to extraordinary lengths or losing more in performance than you ever would by switching the structs to classes (e.g. reflection).</p>\n" }, { "answer_id": 142253, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 1, "selected": false, "text": "<p>Honestly, it sounds like you really want these <code>Column</code>s to be classes, but don't want to pay the runtime cost associated with classes, so you're trying to make them be structs. I don't think you're going to find an elegant way to do what you want. Structs are supposed to be value types, and you want to make them behave like reference types.</p>\n\n<p>You cannot efficiently store your Columns in an array of <code>IColumn</code>s, so no array approach is going to work well. The compiler has no way to know that the <code>IColumn</code> array will only hold structs, and indeed, it wouldn't help if it did, because there are still different types of structs you are trying to jam in there. Every time someone calls <code>AcceptChanges()</code> or <code>HasChanges()</code>, you're going to end up boxing and cloning your structs anyway, so I seriously doubt that making your <code>Column</code> a struct instead of a class is going to save you much memory.</p>\n\n<p>However, you <em>could</em> probably store your <code>Column</code>s directly in an array and index them with an enum. E.g:</p>\n\n<pre><code>public class Record\n{\n public enum ColumnNames { ID = 0, Name, Date, Int, NumCols };\n\n private IColumn [] columns;\n\n public Record()\n {\n columns = new IColumn[ColumnNames.NumCols];\n columns[ID] = ...\n }\n\n public bool HasChanges\n {\n get\n {\n bool has = false;\n for (int i = 0; i &lt; columns.Length; i++)\n has |= columns[i].HasChanges;\n return has;\n }\n }\n\n public void AcceptChanges()\n {\n for (int i = 0; i &lt; columns.Length; i++)\n columns[i].AcceptChanges();\n }\n}\n</code></pre>\n\n<p>I don't have a C# compiler handy, so I can't check to see if that will work or not, but the basic idea should work, even if I didn't get all the details right. However, I'd just go ahead and make them classes. You're paying for it anyway.</p>\n" }, { "answer_id": 142297, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "<p>The only way I can think of to do what you really want to do is to use Reflection. This would still box/unbox, but it <em>would</em> allow you to store the clone back into the field, effectively making it the real value.</p>\n\n<pre><code>public void AcceptChanges()\n{\n foreach (FieldInfo field in GetType().GetFields()) {\n if (!typeof(IColumn).IsAssignableFrom(field.FieldType))\n continue; // ignore all non-IColumn fields\n IColumn col = (IColumn)field.GetValue(this); // Boxes storage -&gt; clone\n col.AcceptChanges(); // Works on clone\n field.SetValue(this, col); // Unboxes clone -&gt; storage\n }\n}\n</code></pre>\n" }, { "answer_id": 143068, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 0, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>public interface IColumn&lt;T&gt;\n{\n T Value { get; set; }\n T OriginalValue { get; set; }\n}\n\npublic struct Column&lt;T&gt; : IColumn&lt;T&gt;\n{\n public T Value { get; set; }\n public T OriginalValue { get; set; }\n}\n\npublic static class ColumnService\n{\n public static bool HasChanges&lt;T, S&gt;(T column) where T : IColumn&lt;S&gt;\n {\n return !(column.Value.Equals(column.OriginalValue));\n }\n\n public static void AcceptChanges&lt;T, S&gt;(T column) where T : IColumn&lt;S&gt;\n {\n column.Value = column.OriginalValue;\n }\n}\n</code></pre>\n\n<p>The client code is then:</p>\n\n<pre><code>Column&lt;int&gt; age = new Column&lt;int&gt;();\nage.Value = 35;\nage.OriginalValue = 34;\n\nif (ColumnService.HasChanges&lt;Column&lt;int&gt;, int&gt;(age))\n{\n ColumnService.AcceptChanges&lt;Column&lt;int&gt;, int&gt;(age);\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22569/" ]
I'm experimenting with generics and I'm trying to create structure similar to Dataset class. I have following code ``` public struct Column<T> { T value; T originalValue; public bool HasChanges { get { return !value.Equals(originalValue); } } public void AcceptChanges() { originalValue = value; } } public class Record { Column<int> id; Column<string> name; Column<DateTime?> someDate; Column<int?> someInt; public bool HasChanges { get { return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges; } } public void AcceptChanges() { id.AcceptChanges(); name.AcceptChanges(); someDate.AcceptChanges(); someInt.AcceptChanges(); } } ``` Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring. So first solution that cames to my mind was something like this: ``` public interface IColumn { bool HasChanges { get; } void AcceptChanges(); } public struct Column<T> : IColumn {...} public class Record { Column<int> id; Column<string> name; Column<DateTime?> someDate; Column<int?> someInt; IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }} public bool HasChanges { get { bool has = false; IColumn[] columns = Columns; //clone and boxing for (int i = 0; i < columns.Length; i++) has |= columns[i].HasChanges; return has; } } public void AcceptChanges() { IColumn[] columns = Columns; //clone and boxing for (int i = 0; i < columns.Length; i++) columns[i].AcceptChanges(); //Here we are changing clone } } ``` As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me. So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage. **Edit:** sfg thanks for suggestion about macros. In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain. Some usefull links: [T4 Editor for VS](http://www.t4editor.net/ "T4 Editor for VS") [Blog with links and tutorials about T4](http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ "Blog with links and tutorials about T4") [Blog entry with example that uses EnvDTE to read project files](http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/ "Blog entry with example that uses EnvDTE to read project files")
As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#. In terms of performance: the macro would be evaluated at compile time (thus slowing compilation a tiny amount), but would cause no slow-down at run-time as the run-time code would be the same as what you would write manually. I think you might have to accept your original AcceptChanges() as you need to access the structs directly by their identifiers if you want to avoid writing to cloned versions. In other words: you need a program to write the program for you, and I do not know how to do that in C# without going to extraordinary lengths or losing more in performance than you ever would by switching the structs to classes (e.g. reflection).
141,973
<p>Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.</p> <p>EDIT: Here is what I have unsuccessfully tried:</p> <pre><code>class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return self._series </code></pre> <p>And in my template:</p> <pre><code>&lt;a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}"&gt;more&lt;/a&gt; </code></pre> <p>The result:</p> <pre><code>&lt;a href="games/view-series.html?series=#comm59"&gt;more&lt;/a&gt; </code></pre>
[ { "answer_id": 142106, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 1, "selected": false, "text": "<p>You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.</p>\n\n<p>Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.</p>\n" }, { "answer_id": 164870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be \"protected\" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.</p>\n\n<p>However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:</p>\n\n<pre><code>class Comment(db.Model):\n series = db.ReferenceProperty(reference_class=Series);\n\n def series_id(self):\n return Comment.series.get_value_for_datastore(self)\n</code></pre>\n\n<p>When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an \_, but I have been unable to get any code working. Examples would be much appreciated. Thanks. EDIT: Here is what I have unsuccessfully tried: ``` class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return self._series ``` And in my template: ``` <a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a> ``` The result: ``` <a href="games/view-series.html?series=#comm59">more</a> ```
Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '\_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes. However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example: ``` class Comment(db.Model): series = db.ReferenceProperty(reference_class=Series); def series_id(self): return Comment.series.get_value_for_datastore(self) ``` When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.
141,993
<p>I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.</p> <p>When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)</p> <p>I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. </p> <p>So, boiled down, the question is:</p> <p>Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.</p>
[ { "answer_id": 142004, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://xom.nu\" rel=\"noreferrer\">Xom</a> has a Canonicalizer utility which turns your DOMs into a regular form, which you can then stringify and compare. So regardless of whitespace irregularities or attribute ordering, you can get regular, predictable comparisons of your documents.</p>\n\n<p>This works especially well in IDEs that have dedicated visual String comparators, like Eclipse. You get a visual representation of the semantic differences between the documents.</p>\n" }, { "answer_id": 142167, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 9, "selected": true, "text": "<p>Sounds like a job for XMLUnit</p>\n\n<ul>\n<li><a href=\"http://www.xmlunit.org/\" rel=\"noreferrer\">http://www.xmlunit.org/</a></li>\n<li><a href=\"https://github.com/xmlunit\" rel=\"noreferrer\">https://github.com/xmlunit</a></li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>public class SomeTest extends XMLTestCase {\n @Test\n public void test() {\n String xml1 = ...\n String xml2 = ...\n\n XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences\n\n // can also compare xml Documents, InputSources, Readers, Diffs\n assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase\n }\n}\n</code></pre>\n" }, { "answer_id": 142199, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": "<p>skaffman seems to be giving a good answer.</p>\n\n<p>another way is probably to format the XML using a commmand line utility like xmlstarlet(<a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">http://xmlstar.sourceforge.net/</a>) and then format both the strings and then use any diff utility(library) to diff the resulting output files. I don't know if this is a good solution when issues are with namespaces.</p>\n" }, { "answer_id": 143951, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": -1, "selected": false, "text": "<p>Since you say \"semantically equivalent\" I assume you mean that you want to do more than just literally verify that the xml outputs are (string) equals, and that you'd want something like </p>\n\n<p> &lt;foo&gt; some stuff here&lt;/foo&gt;&lt;/code&gt;</p>\n\n<p>and </p>\n\n<p>&lt;foo&gt;some stuff here&lt;/foo&gt;&lt;/code&gt;</p>\n\n<p>do read as equivalent. Ultimately it's going to matter how you're defining \"semantically equivalent\" on whatever object you're reconstituting the message from. Simply build that object from the messages and use a custom equals() to define what you're looking for.</p>\n" }, { "answer_id": 4022381, "author": "Pimin Konstantin Kefaloukos", "author_id": 209786, "author_profile": "https://Stackoverflow.com/users/209786", "pm_score": 2, "selected": false, "text": "<p>I'm using <a href=\"http://www.altova.com/diffdog/diff-merge-tool.html\" rel=\"nofollow\">Altova DiffDog</a> which has options to compare XML files structurally (ignoring string data).</p>\n\n<p>This means that (if checking the 'ignore text' option):</p>\n\n<pre><code>&lt;foo a=\"xxx\" b=\"xxx\"&gt;xxx&lt;/foo&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;foo b=\"yyy\" a=\"yyy\"&gt;yyy&lt;/foo&gt; \n</code></pre>\n\n<p>are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!</p>\n" }, { "answer_id": 4211237, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 5, "selected": false, "text": "<p>The following will check if the documents are equal using standard JDK libraries.</p>\n\n<pre>\nDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\ndbf.setNamespaceAware(true);\ndbf.setCoalescing(true);\ndbf.setIgnoringElementContentWhitespace(true);\ndbf.setIgnoringComments(true);\nDocumentBuilder db = dbf.newDocumentBuilder();\n\nDocument doc1 = db.parse(new File(\"file1.xml\"));\ndoc1.normalizeDocument();\n\nDocument doc2 = db.parse(new File(\"file2.xml\"));\ndoc2.normalizeDocument();\n\nAssert.assertTrue(doc1.isEqualNode(doc2));\n</pre>\n\n<p>normalize() is there to make sure there are no cycles (there technically wouldn't be any)</p>\n\n<p>The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand <code>xml:space</code> if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.</p>\n" }, { "answer_id": 5816079, "author": "Javelin", "author_id": 728928, "author_profile": "https://Stackoverflow.com/users/728928", "pm_score": 3, "selected": false, "text": "<p>Thanks, I extended this, try this ...</p>\n\n<pre><code>import java.io.ByteArrayInputStream;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\n\npublic class XmlDiff \n{\n private boolean nodeTypeDiff = true;\n private boolean nodeValueDiff = true;\n\n public boolean diff( String xml1, String xml2, List&lt;String&gt; diffs ) throws Exception\n {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(true);\n dbf.setCoalescing(true);\n dbf.setIgnoringElementContentWhitespace(true);\n dbf.setIgnoringComments(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n\n\n Document doc1 = db.parse(new ByteArrayInputStream(xml1.getBytes()));\n Document doc2 = db.parse(new ByteArrayInputStream(xml2.getBytes()));\n\n doc1.normalizeDocument();\n doc2.normalizeDocument();\n\n return diff( doc1, doc2, diffs );\n\n }\n\n /**\n * Diff 2 nodes and put the diffs in the list \n */\n public boolean diff( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n {\n if( diffNodeExists( node1, node2, diffs ) )\n {\n return true;\n }\n\n if( nodeTypeDiff )\n {\n diffNodeType(node1, node2, diffs );\n }\n\n if( nodeValueDiff )\n {\n diffNodeValue(node1, node2, diffs );\n }\n\n\n System.out.println(node1.getNodeName() + \"/\" + node2.getNodeName());\n\n diffAttributes( node1, node2, diffs );\n diffNodes( node1, node2, diffs );\n\n return diffs.size() &gt; 0;\n }\n\n /**\n * Diff the nodes\n */\n public boolean diffNodes( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n {\n //Sort by Name\n Map&lt;String,Node&gt; children1 = new LinkedHashMap&lt;String,Node&gt;(); \n for( Node child1 = node1.getFirstChild(); child1 != null; child1 = child1.getNextSibling() )\n {\n children1.put( child1.getNodeName(), child1 );\n }\n\n //Sort by Name\n Map&lt;String,Node&gt; children2 = new LinkedHashMap&lt;String,Node&gt;(); \n for( Node child2 = node2.getFirstChild(); child2!= null; child2 = child2.getNextSibling() )\n {\n children2.put( child2.getNodeName(), child2 );\n }\n\n //Diff all the children1\n for( Node child1 : children1.values() )\n {\n Node child2 = children2.remove( child1.getNodeName() );\n diff( child1, child2, diffs );\n }\n\n //Diff all the children2 left over\n for( Node child2 : children2.values() )\n {\n Node child1 = children1.get( child2.getNodeName() );\n diff( child1, child2, diffs );\n }\n\n return diffs.size() &gt; 0;\n }\n\n\n /**\n * Diff the nodes\n */\n public boolean diffAttributes( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n { \n //Sort by Name\n NamedNodeMap nodeMap1 = node1.getAttributes();\n Map&lt;String,Node&gt; attributes1 = new LinkedHashMap&lt;String,Node&gt;(); \n for( int index = 0; nodeMap1 != null &amp;&amp; index &lt; nodeMap1.getLength(); index++ )\n {\n attributes1.put( nodeMap1.item(index).getNodeName(), nodeMap1.item(index) );\n }\n\n //Sort by Name\n NamedNodeMap nodeMap2 = node2.getAttributes();\n Map&lt;String,Node&gt; attributes2 = new LinkedHashMap&lt;String,Node&gt;(); \n for( int index = 0; nodeMap2 != null &amp;&amp; index &lt; nodeMap2.getLength(); index++ )\n {\n attributes2.put( nodeMap2.item(index).getNodeName(), nodeMap2.item(index) );\n\n }\n\n //Diff all the attributes1\n for( Node attribute1 : attributes1.values() )\n {\n Node attribute2 = attributes2.remove( attribute1.getNodeName() );\n diff( attribute1, attribute2, diffs );\n }\n\n //Diff all the attributes2 left over\n for( Node attribute2 : attributes2.values() )\n {\n Node attribute1 = attributes1.get( attribute2.getNodeName() );\n diff( attribute1, attribute2, diffs );\n }\n\n return diffs.size() &gt; 0;\n }\n /**\n * Check that the nodes exist\n */\n public boolean diffNodeExists( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n {\n if( node1 == null &amp;&amp; node2 == null )\n {\n diffs.add( getPath(node2) + \":node \" + node1 + \"!=\" + node2 + \"\\n\" );\n return true;\n }\n\n if( node1 == null &amp;&amp; node2 != null )\n {\n diffs.add( getPath(node2) + \":node \" + node1 + \"!=\" + node2.getNodeName() );\n return true;\n }\n\n if( node1 != null &amp;&amp; node2 == null )\n {\n diffs.add( getPath(node1) + \":node \" + node1.getNodeName() + \"!=\" + node2 );\n return true;\n }\n\n return false;\n }\n\n /**\n * Diff the Node Type\n */\n public boolean diffNodeType( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n { \n if( node1.getNodeType() != node2.getNodeType() ) \n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeType() + \"!=\" + node2.getNodeType() );\n return true;\n }\n\n return false;\n }\n\n /**\n * Diff the Node Value\n */\n public boolean diffNodeValue( Node node1, Node node2, List&lt;String&gt; diffs ) throws Exception\n { \n if( node1.getNodeValue() == null &amp;&amp; node2.getNodeValue() == null )\n {\n return false;\n }\n\n if( node1.getNodeValue() == null &amp;&amp; node2.getNodeValue() != null )\n {\n diffs.add( getPath(node1) + \":type \" + node1 + \"!=\" + node2.getNodeValue() );\n return true;\n }\n\n if( node1.getNodeValue() != null &amp;&amp; node2.getNodeValue() == null )\n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeValue() + \"!=\" + node2 );\n return true;\n }\n\n if( !node1.getNodeValue().equals( node2.getNodeValue() ) )\n {\n diffs.add( getPath(node1) + \":type \" + node1.getNodeValue() + \"!=\" + node2.getNodeValue() );\n return true;\n }\n\n return false;\n }\n\n\n /**\n * Get the node path\n */\n public String getPath( Node node )\n {\n StringBuilder path = new StringBuilder();\n\n do\n { \n path.insert(0, node.getNodeName() );\n path.insert( 0, \"/\" );\n }\n while( ( node = node.getParentNode() ) != null );\n\n return path.toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 14787497, "author": "Sree", "author_id": 1294908, "author_profile": "https://Stackoverflow.com/users/1294908", "pm_score": 0, "selected": false, "text": "<p>Using JExamXML with java application </p>\n\n<pre><code> import com.a7soft.examxml.ExamXML;\n import com.a7soft.examxml.Options;\n\n .................\n\n // Reads two XML files into two strings\n String s1 = readFile(\"orders1.xml\");\n String s2 = readFile(\"orders.xml\");\n\n // Loads options saved in a property file\n Options.loadOptions(\"options\");\n\n // Compares two Strings representing XML entities\n System.out.println( ExamXML.compareXMLString( s1, s2 ) );\n</code></pre>\n" }, { "answer_id": 16471601, "author": "acdcjunior", "author_id": 1850609, "author_profile": "https://Stackoverflow.com/users/1850609", "pm_score": 5, "selected": false, "text": "<p>The latest version of <a href=\"http://xmlunit.sourceforge.net/\">XMLUnit</a> can help the job of asserting two XML are equal. Also <code>XMLUnit.setIgnoreWhitespace()</code> and <code>XMLUnit.setIgnoreAttributeOrder()</code> may be necessary to the case in question.</p>\n\n<p>See working code of a simple example of XML Unit use below.</p>\n\n<pre><code>import org.custommonkey.xmlunit.DetailedDiff;\nimport org.custommonkey.xmlunit.XMLUnit;\nimport org.junit.Assert;\n\npublic class TestXml {\n\n public static void main(String[] args) throws Exception {\n String result = \"&lt;abc attr=\\\"value1\\\" title=\\\"something\\\"&gt; &lt;/abc&gt;\";\n // will be ok\n assertXMLEquals(\"&lt;abc attr=\\\"value1\\\" title=\\\"something\\\"&gt;&lt;/abc&gt;\", result);\n }\n\n public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {\n XMLUnit.setIgnoreWhitespace(true);\n XMLUnit.setIgnoreAttributeOrder(true);\n\n DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));\n\n List&lt;?&gt; allDifferences = diff.getAllDifferences();\n Assert.assertEquals(\"Differences found: \"+ diff.toString(), 0, allDifferences.size());\n }\n\n}\n</code></pre>\n\n<p>If using Maven, add this to your <code>pom.xml</code>:</p>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;xmlunit&lt;/groupId&gt;\n &lt;artifactId&gt;xmlunit&lt;/artifactId&gt;\n &lt;version&gt;1.4&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n" }, { "answer_id": 26361718, "author": "Wojtek", "author_id": 2685402, "author_profile": "https://Stackoverflow.com/users/2685402", "pm_score": 1, "selected": false, "text": "<p>This will compare full string XMLs (reformatting them on the way). It makes it easy to work with your IDE (IntelliJ, Eclipse), cos you just click and visually see the difference in the XML files.</p>\n\n<pre><code>import org.apache.xml.security.c14n.CanonicalizationException;\nimport org.apache.xml.security.c14n.Canonicalizer;\nimport org.apache.xml.security.c14n.InvalidCanonicalizerException;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.bootstrap.DOMImplementationRegistry;\nimport org.w3c.dom.ls.DOMImplementationLS;\nimport org.w3c.dom.ls.LSSerializer;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\nimport java.io.IOException;\nimport java.io.StringReader;\n\nimport static org.apache.xml.security.Init.init;\nimport static org.junit.Assert.assertEquals;\n\npublic class XmlUtils {\n static {\n init();\n }\n\n public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {\n Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);\n byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());\n return new String(canonXmlBytes);\n }\n\n public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {\n InputSource src = new InputSource(new StringReader(input));\n Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();\n Boolean keepDeclaration = input.startsWith(\"&lt;?xml\");\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n writer.getDomConfig().setParameter(\"format-pretty-print\", Boolean.TRUE);\n writer.getDomConfig().setParameter(\"xml-declaration\", keepDeclaration);\n return writer.writeToString(document);\n }\n\n public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {\n String canonicalExpected = prettyFormat(toCanonicalXml(expected));\n String canonicalActual = prettyFormat(toCanonicalXml(actual));\n assertEquals(canonicalExpected, canonicalActual);\n }\n}\n</code></pre>\n\n<p>I prefer this to XmlUnit because the client code (test code) is cleaner.</p>\n" }, { "answer_id": 36144815, "author": "Tom Saleeba", "author_id": 1410035, "author_profile": "https://Stackoverflow.com/users/1410035", "pm_score": 3, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/users/22850/tom\">Tom</a>'s answer, here's an example using XMLUnit v2.</p>\n\n<p>It uses these maven dependencies</p>\n\n<pre><code> &lt;dependency&gt;\n &lt;groupId&gt;org.xmlunit&lt;/groupId&gt;\n &lt;artifactId&gt;xmlunit-core&lt;/artifactId&gt;\n &lt;version&gt;2.0.0&lt;/version&gt;\n &lt;scope&gt;test&lt;/scope&gt;\n &lt;/dependency&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;org.xmlunit&lt;/groupId&gt;\n &lt;artifactId&gt;xmlunit-matchers&lt;/artifactId&gt;\n &lt;version&gt;2.0.0&lt;/version&gt;\n &lt;scope&gt;test&lt;/scope&gt;\n &lt;/dependency&gt;\n</code></pre>\n\n<p>..and here's the test code</p>\n\n<pre><code>import static org.junit.Assert.assertThat;\nimport static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;\nimport org.xmlunit.builder.Input;\nimport org.xmlunit.input.WhitespaceStrippedSource;\n\npublic class SomeTest extends XMLTestCase {\n @Test\n public void test() {\n String result = \"&lt;root&gt;&lt;/root&gt;\";\n String expected = \"&lt;root&gt; &lt;/root&gt;\";\n\n // ignore whitespace differences\n // https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource\n assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));\n\n assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences\n }\n}\n</code></pre>\n\n<p>The documentation that outlines this is <a href=\"https://github.com/xmlunit/xmlunit#comparing-two-documents\" rel=\"noreferrer\">https://github.com/xmlunit/xmlunit#comparing-two-documents</a></p>\n" }, { "answer_id": 36570105, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://joel-costigliola.github.io/assertj/\" rel=\"noreferrer\">AssertJ</a> 1.4+ has specific assertions to compare XML content:</p>\n\n<pre><code>String expectedXml = \"&lt;foo /&gt;\";\nString actualXml = \"&lt;bar /&gt;\";\nassertThat(actualXml).isXmlEqualTo(expectedXml);\n</code></pre>\n\n<p>Here is the <a href=\"https://github.com/joel-costigliola/assertj-core/wiki/New-and-noteworthy#xml-assertions\" rel=\"noreferrer\">Documentation</a></p>\n" }, { "answer_id": 36658480, "author": "TouDick", "author_id": 1688570, "author_profile": "https://Stackoverflow.com/users/1688570", "pm_score": 2, "selected": false, "text": "<p>I required the same functionality as requested in the main question. As I was not allowed to use any 3rd party libraries, I have created my own solution basing on @Archimedes Trajano solution.</p>\n\n<p>Following is my solution.</p>\n\n<pre><code>import java.io.ByteArrayInputStream;\nimport java.nio.charset.Charset;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\n\nimport org.junit.Assert;\nimport org.w3c.dom.Document;\n\n/**\n * Asserts for asserting XML strings.\n */\npublic final class AssertXml {\n\n private AssertXml() {\n }\n\n private static Pattern NAMESPACE_PATTERN = Pattern.compile(\"xmlns:(ns\\\\d+)=\\\"(.*?)\\\"\");\n\n /**\n * Asserts that two XML are of identical content (namespace aliases are ignored).\n * \n * @param expectedXml expected XML\n * @param actualXml actual XML\n * @throws Exception thrown if XML parsing fails\n */\n public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {\n // Find all namespace mappings\n Map&lt;String, String&gt; fullnamespace2newAlias = new HashMap&lt;String, String&gt;();\n generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);\n generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);\n\n for (Entry&lt;String, String&gt; entry : fullnamespace2newAlias.entrySet()) {\n String newAlias = entry.getValue();\n String namespace = entry.getKey();\n Pattern nsReplacePattern = Pattern.compile(\"xmlns:(ns\\\\d+)=\\\"\" + namespace + \"\\\"\");\n expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);\n actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);\n }\n\n // nomralize namespaces accoring to given mapping\n\n DocumentBuilder db = initDocumentParserFactory();\n\n Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName(\"UTF-8\"))));\n expectedDocuemnt.normalizeDocument();\n\n Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName(\"UTF-8\"))));\n actualDocument.normalizeDocument();\n\n if (!expectedDocuemnt.isEqualNode(actualDocument)) {\n Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse\n }\n }\n\n\n private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n dbf.setNamespaceAware(false);\n dbf.setCoalescing(true);\n dbf.setIgnoringElementContentWhitespace(true);\n dbf.setIgnoringComments(true);\n DocumentBuilder db = dbf.newDocumentBuilder();\n return db;\n }\n\n private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {\n Matcher nsMatcherExp = namespacePattern.matcher(xml);\n if (nsMatcherExp.find()) {\n xml = xml.replaceAll(nsMatcherExp.group(1) + \"[:]\", newAlias + \":\");\n xml = xml.replaceAll(nsMatcherExp.group(1) + \"=\", newAlias + \"=\");\n }\n return xml;\n }\n\n private static void generateNewAliasesForNamespacesFromXml(String xml, Map&lt;String, String&gt; fullnamespace2newAlias) {\n Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);\n while (nsMatcher.find()) {\n if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {\n fullnamespace2newAlias.put(nsMatcher.group(2), \"nsTr\" + (fullnamespace2newAlias.size() + 1));\n }\n }\n }\n\n}\n</code></pre>\n\n<p>It compares two XML strings and takes care of any mismatching namespace mappings by translating them to unique values in both input strings.</p>\n\n<p>Can be fine tuned i.e. in case of translation of namespaces. But for my requirements just does the job.</p>\n" }, { "answer_id": 45839956, "author": "arunkumar sambu", "author_id": 6799634, "author_profile": "https://Stackoverflow.com/users/6799634", "pm_score": 2, "selected": false, "text": "<p>Below code works for me </p>\n\n<pre><code>String xml1 = ...\nString xml2 = ...\nXMLUnit.setIgnoreWhitespace(true);\nXMLUnit.setIgnoreAttributeOrder(true);\nXMLAssert.assertXMLEqual(actualxml, xmlInDb);\n</code></pre>\n" }, { "answer_id": 71255057, "author": "Nicolas Sénave", "author_id": 13425151, "author_profile": "https://Stackoverflow.com/users/13425151", "pm_score": 1, "selected": false, "text": "<h2>Using XMLUnit 2.x</h2>\n<p>In the <code>pom.xml</code></p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;dependency&gt;\n &lt;groupId&gt;org.xmlunit&lt;/groupId&gt;\n &lt;artifactId&gt;xmlunit-assertj3&lt;/artifactId&gt;\n &lt;version&gt;2.9.0&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n<p>Test implementation (using junit 5) :</p>\n<pre class=\"lang-java prettyprint-override\"><code>import org.junit.jupiter.api.Test;\nimport org.xmlunit.assertj3.XmlAssert;\n\npublic class FooTest {\n\n @Test\n public void compareXml() {\n //\n String xmlContentA = &quot;&lt;foo&gt;&lt;/foo&gt;&quot;;\n String xmlContentB = &quot;&lt;foo&gt;&lt;/foo&gt;&quot;;\n //\n XmlAssert.assertThat(xmlContentA).and(xmlContentB).areSimilar();\n }\n}\n</code></pre>\n<p>Other methods : <code>areIdentical()</code>, <code>areNotIdentical()</code>, <code>areNotSimilar()</code></p>\n<p>More details (configuration of <code>assertThat(~).and(~)</code> and examples) in this <a href=\"https://github.com/xmlunit/user-guide/wiki/CompareAssert\" rel=\"nofollow noreferrer\">documentation page</a>.</p>\n<p>XMLUnit also has (among other features) a <a href=\"https://github.com/xmlunit/user-guide/wiki/DifferenceEvaluator\" rel=\"nofollow noreferrer\"><code>DifferenceEvaluator</code></a> to do more precise comparisons.</p>\n<p><a href=\"https://www.xmlunit.org/\" rel=\"nofollow noreferrer\">XMLUnit website</a></p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end. When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.) I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. So, boiled down, the question is: Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.
Sounds like a job for XMLUnit * <http://www.xmlunit.org/> * <https://github.com/xmlunit> Example: ``` public class SomeTest extends XMLTestCase { @Test public void test() { String xml1 = ... String xml2 = ... XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences // can also compare xml Documents, InputSources, Readers, Diffs assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase } } ```
142,000
<p>I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with <code>e.preventDefault()</code> and runs an AJAX command. This works fine when the submit button is clicked but when a link with <code>onclick='document.formName.submit();'</code> is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?</p>
[ { "answer_id": 142021, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 4, "selected": false, "text": "<p>If you are using jQuery, you should be attaching events via it's own <a href=\"http://docs.jquery.com/Events\" rel=\"noreferrer\">event mechanism</a> and not by using \"on\" properties (onclick etc.). It also has its own event triggering method, aptly named '<a href=\"http://docs.jquery.com/Events/trigger#typedata\" rel=\"noreferrer\">trigger</a>', which you should use to activate the form submission event. </p>\n" }, { "answer_id": 142075, "author": "user16624", "author_id": 16624, "author_profile": "https://Stackoverflow.com/users/16624", "pm_score": 1, "selected": false, "text": "<p>Thanks Eran</p>\n\n<p>I am using this event binding code</p>\n\n<pre><code>this._form.bind('submit', Delegate.create(this, function(e) {\n e.preventDefault();\n this._searchFadeOut();\n this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));\n});\n</code></pre>\n\n<p>but there is legacy <code>onclick</code> code on the HTML and I would prefer not to change it as there are just so many links.</p>\n" }, { "answer_id": 142109, "author": "stechz", "author_id": 10290, "author_profile": "https://Stackoverflow.com/users/10290", "pm_score": 6, "selected": true, "text": "<p>A couple of suggestions:</p>\n\n<ul>\n<li>Overwrite the submit function to do your evil bidding</li>\n</ul>\n\n<pre><code>\n var oldSubmit = form.submit;\n form.submit = function() {\n $(form).trigger(\"submit\");\n oldSubmit.call(form, arguments);\n }\n</code></pre>\n\n<ul>\n<li>Why not bind to all the &lt;a&gt; tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):</li>\n</ul>\n\n<pre><code>\n $(\"form a\").click(function() {\n $(this).parents().filter(\"form\").trigger(\"submit\");\n });\n</code></pre>\n" }, { "answer_id": 5640759, "author": "Joel", "author_id": 704789, "author_profile": "https://Stackoverflow.com/users/704789", "pm_score": 1, "selected": false, "text": "<p>This worked for me:</p>\n\n<p>Make a dummy button, hide the real submit with the name submit, </p>\n\n<p>and then:</p>\n\n<pre><code>$(\"#mySubmit\").click(function(){\n $(\"#submit\").trigger(\"click\"); });\n</code></pre>\n\n<p>set an event handler on your dummy to trigger click on the form submit button. let the browser figure out how to submit the form... This way you don't need to <code>preventDefault</code> on the form submit which is where the trouble starts.</p>\n\n<p>This seemed to work around the problem.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16624/" ]
I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with `e.preventDefault()` and runs an AJAX command. This works fine when the submit button is clicked but when a link with `onclick='document.formName.submit();'` is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?
A couple of suggestions: * Overwrite the submit function to do your evil bidding ``` var oldSubmit = form.submit; form.submit = function() { $(form).trigger("submit"); oldSubmit.call(form, arguments); } ``` * Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag): ``` $("form a").click(function() { $(this).parents().filter("form").trigger("submit"); }); ```
142,003
<p>I have a scenario. (Windows Forms, C#, .NET)</p> <ol> <li>There is a main form which hosts some user control.</li> <li>The user control does some heavy data operation, such that if I directly call the <code>UserControl_Load</code> method the UI become nonresponsive for the duration for load method execution.</li> <li>To overcome this I load data on different thread (trying to change existing code as little as I can)</li> <li>I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.</li> <li>Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.</li> </ol> <p>The pseudocode would look like this:</p> <p><strong>CODE 1</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (textbox1.text == &quot;MyName&quot;) // This gives exception { //Load data corresponding to &quot;MyName&quot;. //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage. } } </code></pre> <p>The Exception it gave was</p> <blockquote> <p>Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.</p> </blockquote> <p>To know more about this I did some googling and a suggestion came up like using the following code</p> <p><strong>CODE 2</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (InvokeRequired) // Line #1 { this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod)); return; } if (textbox1.text == &quot;MyName&quot;) // Now it won't give an exception { //Load data correspondin to &quot;MyName&quot; //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage } } </code></pre> <p>But it still seems that I've come back to square one. The Application again becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.</p> <p>I don't know whether I perceived this right or wrong. I'm new to threading.</p> <p>How do I resolve this and also what is the effect of execution of Line#1 if block?</p> <p><strong>The situation is this</strong>: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p> <p>So only accessing the value so that the corresponding data can be fetched from the database.</p>
[ { "answer_id": 142053, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>Controls in .NET are not generally thread safe. That means you shouldn't access a control from a thread other than the one where it lives. To get around this, you need to <em>invoke</em> the control, which is what your 2nd sample is attempting. </p>\n\n<p>However, in your case all you've done is pass the long-running method back to the main thread. Of course, that's not really what you want to do. You need to rethink this a little so that all you're doing on the main thread is setting a quick property here and there.</p>\n" }, { "answer_id": 142064, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>You only want to use <code>Invoke</code> or <code>BeginInvoke</code> for the bare minimum piece of work required to change the UI. Your \"heavy\" method should execute on another thread (e.g. via <code>BackgroundWorker</code>) but then using <code>Control.Invoke</code>/<code>Control.BeginInvoke</code> just to update the UI. That way your UI thread will be free to handle UI events etc.</p>\n\n<p>See my <a href=\"http://pobox.com/~skeet/csharp/threads\" rel=\"nofollow noreferrer\">threading article</a> for a <a href=\"http://pobox.com/~skeet/csharp/threads/winforms.shtml\" rel=\"nofollow noreferrer\">WinForms example</a> - although the article was written before <code>BackgroundWorker</code> arrived on the scene, and I'm afraid I haven't updated it in that respect. <code>BackgroundWorker</code> merely simplifies the callback a bit.</p>\n" }, { "answer_id": 142069, "author": "Jeff Hubbard", "author_id": 8844, "author_profile": "https://Stackoverflow.com/users/8844", "pm_score": 10, "selected": true, "text": "<p>As per <a href=\"https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108\">Prerak K's update comment</a> (since deleted):</p>\n<blockquote>\n<p>I guess I have not presented the question properly.</p>\n<p>Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p>\n<p>So only accessing the value so that corresponding data can be fetched from the database.</p>\n</blockquote>\n<p>The solution you want then should look like:</p>\n<pre><code>UserContrl1_LOadDataMethod()\n{\n string name = &quot;&quot;;\n if(textbox1.InvokeRequired)\n {\n textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));\n }\n if(name == &quot;MyName&quot;)\n {\n // do whatever\n }\n}\n</code></pre>\n<p>Do your serious processing in the separate thread <em>before</em> you attempt to switch back to the control's thread. For example:</p>\n<pre><code>UserContrl1_LOadDataMethod()\n{\n if(textbox1.text==&quot;MyName&quot;) //&lt;&lt;======Now it wont give exception**\n {\n //Load data correspondin to &quot;MyName&quot;\n //Populate a globale variable List&lt;string&gt; which will be\n //bound to grid at some later stage\n if(InvokeRequired)\n {\n // after we've done all the processing, \n this.Invoke(new MethodInvoker(delegate {\n // load the control with the appropriate data\n }));\n return;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 142154, "author": "Pat", "author_id": 14206, "author_profile": "https://Stackoverflow.com/users/14206", "pm_score": 3, "selected": false, "text": "<p>You need to look at the Backgroundworker example:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a>\nEspecially how it interacts with the UI layer. Based on your posting, this seems to answer your issues.</p>\n" }, { "answer_id": 437759, "author": "Peter C", "author_id": 1952, "author_profile": "https://Stackoverflow.com/users/1952", "pm_score": 5, "selected": false, "text": "<p>I have had this problem with the <code>FileSystemWatcher</code> and found that the following code solved the problem:</p>\n\n<p><code>fsw.SynchronizingObject = this</code></p>\n\n<p>The control then uses the current form object to deal with the events, and will therefore be on the same thread.</p>\n" }, { "answer_id": 792321, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 4, "selected": false, "text": "<p>The cleanest (and proper) solution for UI cross-threading issues is to use SynchronizationContext, see <a href=\"http://www.lostechies.com/blogs/gabrielschenker/archive/2009/01/23/synchronizing-calls-to-the-ui-in-a-multi-threaded-application.aspx\" rel=\"noreferrer\">Synchronizing calls to the UI in a multi-threaded application</a> article, it explains it very nicely.</p>\n" }, { "answer_id": 10746375, "author": "Ashitakalax", "author_id": 970011, "author_profile": "https://Stackoverflow.com/users/970011", "pm_score": 3, "selected": false, "text": "<p>Here is an alternative way if the object you are working with doesn't have </p>\n\n<pre><code>(InvokeRequired)\n</code></pre>\n\n<p>This is useful if you are working with the main form in a class other than the main form with an object that is in the main form, but doesn't have InvokeRequired</p>\n\n<pre><code>delegate void updateMainFormObject(FormObjectType objectWithoutInvoke, string text);\n\nprivate void updateFormObjectType(FormObjectType objectWithoutInvoke, string text)\n{\n MainForm.Invoke(new updateMainFormObject(UpdateObject), objectWithoutInvoke, text);\n}\n\npublic void UpdateObject(ToolStripStatusLabel objectWithoutInvoke, string text)\n{\n objectWithoutInvoke.Text = text;\n}\n</code></pre>\n\n<p>It works the same as above, but it is a different approach if you don't have an object with invokerequired, but do have access to the MainForm</p>\n" }, { "answer_id": 18748673, "author": "RandallTo", "author_id": 609346, "author_profile": "https://Stackoverflow.com/users/609346", "pm_score": 3, "selected": false, "text": "<p>I found a need for this while programming an iOS-Phone monotouch app controller in a visual studio winforms prototype project outside of xamarin stuidio. Preferring to program in VS over xamarin studio as much as possible, I wanted the controller to be completely decoupled from the phone framework. This way implementing this for other frameworks like Android and Windows Phone would be much easier for future uses.</p>\n\n<p>I wanted a solution where the GUI could respond to events without the burden of dealing with the cross threading switching code behind every button click. Basically let the class controller handle that to keep the client code simple. You could possibly have many events on the GUI where as if you could handle it in one place in the class would be cleaner. I am not a multi theading expert, let me know if this is flawed.</p>\n\n<pre><code>public partial class Form1 : Form\n{\n private ExampleController.MyController controller;\n\n public Form1()\n { \n InitializeComponent();\n controller = new ExampleController.MyController((ISynchronizeInvoke) this);\n controller.Finished += controller_Finished;\n }\n\n void controller_Finished(string returnValue)\n {\n label1.Text = returnValue; \n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n controller.SubmitTask(\"Do It\");\n }\n}\n</code></pre>\n\n<p>The GUI form is unaware the controller is running asynchronous tasks.</p>\n\n<pre><code>public delegate void FinishedTasksHandler(string returnValue);\n\npublic class MyController\n{\n private ISynchronizeInvoke _syn; \n public MyController(ISynchronizeInvoke syn) { _syn = syn; } \n public event FinishedTasksHandler Finished; \n\n public void SubmitTask(string someValue)\n {\n System.Threading.ThreadPool.QueueUserWorkItem(state =&gt; submitTask(someValue));\n }\n\n private void submitTask(string someValue)\n {\n someValue = someValue + \" \" + DateTime.Now.ToString();\n System.Threading.Thread.Sleep(5000);\n//Finished(someValue); This causes cross threading error if called like this.\n\n if (Finished != null)\n {\n if (_syn.InvokeRequired)\n {\n _syn.Invoke(Finished, new object[] { someValue });\n }\n else\n {\n Finished(someValue);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 19023209, "author": "Ryszard Dżegan", "author_id": 2042090, "author_profile": "https://Stackoverflow.com/users/2042090", "pm_score": 8, "selected": false, "text": "<h1>Threading Model in UI</h1>\n\n<p>Please read the <em><a href=\"https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/threading-model\" rel=\"noreferrer\">Threading Model</a></em> in UI applications (<a href=\"https://msdn.microsoft.com/library/ms741870(v=vs.100).aspx\" rel=\"noreferrer\">old VB link is here</a>) in order to understand basic concepts. The link navigates to page that describes the WPF threading model. However, Windows Forms utilizes the same idea.</p>\n\n<h2>The UI Thread</h2>\n\n<ul>\n<li>There is only one thread (UI thread), that is allowed to access <a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control</a> and its subclasses members.</li>\n<li>Attempt to access member of <a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control</a> from different thread than UI thread will cause cross-thread exception.</li>\n<li>Since there is only one thread, all UI operations are queued as work items into that thread:</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/6MtB3.png\" alt=\"enter image description here\"></p>\n\n<ul>\n<li>If there is no work for UI thread, then there are idle gaps that can be used by a not-UI related computing.</li>\n<li>In order to use mentioned gaps use <a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.Invoke</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.BeginInvoke</a> methods:</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/WQPOJ.png\" alt=\"enter image description here\"></p>\n\n<h2>BeginInvoke and Invoke methods</h2>\n\n<ul>\n<li>The computing overhead of method being invoked should be small as well as computing overhead of event handler methods because the UI thread is used there - the same that is responsible for handling user input. Regardless if this is <a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.Invoke</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.BeginInvoke</a>.</li>\n<li>To perform computing expensive operation always use separate thread. Since .NET 2.0 <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"noreferrer\">BackgroundWorker</a> is dedicated to performing computing expensive operations in Windows Forms. However in new solutions you should use the async-await pattern as described <a href=\"https://stackoverflow.com/a/18033198/2042090\">here</a>.</li>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.Invoke</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.BeginInvoke</a> methods only to update a user interface. If you use them for heavy computations, your application will block:</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/UfBqr.png\" alt=\"enter image description here\"></p>\n\n<h3>Invoke</h3>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/System.Windows.Forms.Control.Invoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.Invoke</a> causes separate thread to wait till invoked method is completed:</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/XmFJu.png\" alt=\"enter image description here\"></p>\n\n<h3>BeginInvoke</h3>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx\" rel=\"noreferrer\">System.Windows.Forms.Control.BeginInvoke</a> doesn't cause the separate thread to wait till invoked method is completed:</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/8k5kn.png\" alt=\"enter image description here\"></p>\n\n<h2>Code solution</h2>\n\n<p>Read answers on question <a href=\"https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c\">How to update the GUI from another thread in C#?</a>.\nFor C# 5.0 and .NET 4.5 the recommended solution is <a href=\"https://stackoverflow.com/a/18033198/2042090\">here</a>.</p>\n" }, { "answer_id": 21576814, "author": "UrsulRosu", "author_id": 1764994, "author_profile": "https://Stackoverflow.com/users/1764994", "pm_score": 3, "selected": false, "text": "<p>For example to get the text from a Control of the UI thread:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Delegate Function GetControlTextInvoker(ByVal ctl As Control) As String\n\nPrivate Function GetControlText(ByVal ctl As Control) As String\n Dim text As String\n\n If ctl.InvokeRequired Then\n text = CStr(ctl.Invoke(\n New GetControlTextInvoker(AddressOf GetControlText), ctl))\n Else\n text = ctl.Text\n End If\n\n Return text\nEnd Function\n</code></pre>\n" }, { "answer_id": 26506411, "author": "Mike", "author_id": 3083679, "author_profile": "https://Stackoverflow.com/users/3083679", "pm_score": 3, "selected": false, "text": "<p>Along the same lines as previous answers,\nbut a very short addition that Allows to use all Control properties without having cross thread invokation exception.</p>\n\n<p><strong>Helper Method</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Helper method to determin if invoke required, if so will rerun method on correct thread.\n/// if not do nothing.\n/// &lt;/summary&gt;\n/// &lt;param name=\"c\"&gt;Control that might require invoking&lt;/param&gt;\n/// &lt;param name=\"a\"&gt;action to preform on control thread if so.&lt;/param&gt;\n/// &lt;returns&gt;true if invoke required&lt;/returns&gt;\npublic bool ControlInvokeRequired(Control c, Action a)\n{\n if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate\n {\n a();\n }));\n else return false;\n\n return true;\n}\n</code></pre>\n\n<p><strong>Sample Usage</strong></p>\n\n<pre><code>// usage on textbox\npublic void UpdateTextBox1(String text)\n{\n //Check if invoke requied if so return - as i will be recalled in correct thread\n if (ControlInvokeRequired(textBox1, () =&gt; UpdateTextBox1(text))) return;\n textBox1.Text = ellapsed;\n}\n\n//Or any control\npublic void UpdateControl(Color c, String s)\n{\n //Check if invoke requied if so return - as i will be recalled in correct thread\n if (ControlInvokeRequired(myControl, () =&gt; UpdateControl(c, s))) return;\n myControl.Text = s;\n myControl.BackColor = c;\n}\n</code></pre>\n" }, { "answer_id": 36983936, "author": "Rob", "author_id": 563532, "author_profile": "https://Stackoverflow.com/users/563532", "pm_score": 4, "selected": false, "text": "<p>I find the check-and-invoke code which needs to be littered within all methods related to forms to be way too verbose and unneeded. Here's a simple extension method which lets you do away with it completely:</p>\n\n<pre><code>public static class Extensions\n{\n public static void Invoke&lt;TControlType&gt;(this TControlType control, Action&lt;TControlType&gt; del) \n where TControlType : Control\n {\n if (control.InvokeRequired)\n control.Invoke(new Action(() =&gt; del(control)));\n else\n del(control);\n }\n}\n</code></pre>\n\n<p>And then you can simply do this:</p>\n\n<pre><code>textbox1.Invoke(t =&gt; t.Text = \"A\");\n</code></pre>\n\n<p>No more messing around - simple.</p>\n" }, { "answer_id": 37077612, "author": "Vanderley Maia", "author_id": 2126783, "author_profile": "https://Stackoverflow.com/users/2126783", "pm_score": 3, "selected": false, "text": "<p>Follow the simplest (in my opinion) way to modify objects from another thread:</p>\n\n<pre><code>using System.Threading.Tasks;\nusing System.Threading;\n\nnamespace TESTE\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Action&lt;string&gt; DelegateTeste_ModifyText = THREAD_MOD;\n Invoke(DelegateTeste_ModifyText, \"MODIFY BY THREAD\");\n }\n\n private void THREAD_MOD(string teste)\n {\n textBox1.Text = teste;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 37245647, "author": "JWP", "author_id": 1522548, "author_profile": "https://Stackoverflow.com/users/1522548", "pm_score": 3, "selected": false, "text": "<p>A new look using Async/Await and callbacks. You only need one line of code if you keep the extension method in your project. </p>\n\n<pre><code>/// &lt;summary&gt;\n/// A new way to use Tasks for Asynchronous calls\n/// &lt;/summary&gt;\npublic class Example\n{\n /// &lt;summary&gt;\n /// No more delegates, background workers etc. just one line of code as shown below\n /// Note it is dependent on the XTask class shown next.\n /// &lt;/summary&gt;\n public async void ExampleMethod()\n {\n //Still on GUI/Original Thread here\n //Do your updates before the next line of code\n await XTask.RunAsync(() =&gt;\n {\n //Running an asynchronous task here\n //Cannot update GUI Thread here, but can do lots of work\n });\n //Can update GUI/Original thread on this line\n }\n}\n\n/// &lt;summary&gt;\n/// A class containing extension methods for the Task class \n/// Put this file in folder named Extensions\n/// Use prefix of X for the class it Extends\n/// &lt;/summary&gt;\npublic static class XTask\n{\n /// &lt;summary&gt;\n /// RunAsync is an extension method that encapsulates the Task.Run using a callback\n /// &lt;/summary&gt;\n /// &lt;param name=\"Code\"&gt;The caller is called back on the new Task (on a different thread)&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public async static Task RunAsync(Action Code)\n {\n await Task.Run(() =&gt;\n {\n Code();\n });\n return;\n }\n}\n</code></pre>\n\n<p>You can add other things to the Extension method such as wrapping it in a Try/Catch statement, allowing caller to tell it what type to return after completion, an exception callback to caller:</p>\n\n<p><strong>Adding Try Catch, Auto Exception Logging and CallBack</strong></p>\n\n<pre><code> /// &lt;summary&gt;\n /// Run Async\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type to return&lt;/typeparam&gt;\n /// &lt;param name=\"Code\"&gt;The callback to the code&lt;/param&gt;\n /// &lt;param name=\"Error\"&gt;The handled and logged exception if one occurs&lt;/param&gt;\n /// &lt;returns&gt;The type expected as a competed task&lt;/returns&gt;\n\n public async static Task&lt;T&gt; RunAsync&lt;T&gt;(Func&lt;string,T&gt; Code, Action&lt;Exception&gt; Error)\n {\n var done = await Task&lt;T&gt;.Run(() =&gt;\n {\n T result = default(T);\n try\n {\n result = Code(\"Code Here\");\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Unhandled Exception: \" + ex.Message);\n Console.WriteLine(ex.StackTrace);\n Error(ex);\n }\n return result;\n\n });\n return done;\n }\n public async void HowToUse()\n {\n //We now inject the type we want the async routine to return!\n var result = await RunAsync&lt;bool&gt;((code) =&gt; {\n //write code here, all exceptions are logged via the wrapped try catch.\n //return what is needed\n return someBoolValue;\n }, \n error =&gt; {\n\n //exceptions are already handled but are sent back here for further processing\n });\n if (result)\n {\n //we can now process the result because the code above awaited for the completion before\n //moving to this statement\n }\n }\n</code></pre>\n" }, { "answer_id": 43012655, "author": "Saurabh", "author_id": 3556867, "author_profile": "https://Stackoverflow.com/users/3556867", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c\">Same question : how-to-update-the-gui-from-another-thread-in-c</a></p>\n\n<p>Two Ways:</p>\n\n<ol>\n<li><p>Return value in e.result and use it to set yout textbox value in backgroundWorker_RunWorkerCompleted event</p></li>\n<li><p>Declare some variable to hold these kind of values in a separate class (which will work as data holder) . Create static instance of this class adn you can access it over any thread.</p></li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>public class data_holder_for_controls\n{\n //it will hold value for your label\n public string status = string.Empty;\n}\n\nclass Demo\n{\n public static data_holder_for_controls d1 = new data_holder_for_controls();\n static void Main(string[] args)\n {\n ThreadStart ts = new ThreadStart(perform_logic);\n Thread t1 = new Thread(ts);\n t1.Start();\n t1.Join();\n //your_label.Text=d1.status; --- can access it from any thread \n }\n\n public static void perform_logic()\n {\n //put some code here in this function\n for (int i = 0; i &lt; 10; i++)\n {\n //statements here\n }\n //set result in status variable\n d1.status = \"Task done\";\n }\n}\n</code></pre>\n" }, { "answer_id": 43890612, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 3, "selected": false, "text": "<p>This is not the recommended way to solve this error but you can suppress it quickly, it will do the job . I prefer this for prototypes or demos . add </p>\n\n<pre><code>CheckForIllegalCrossThreadCalls = false\n</code></pre>\n\n<p>in <code>Form1()</code> constructor . </p>\n" }, { "answer_id": 46789543, "author": "Bravo", "author_id": 835464, "author_profile": "https://Stackoverflow.com/users/835464", "pm_score": 6, "selected": false, "text": "<p>I know its too late now. However even today if you are having trouble accessing cross thread controls? This is the shortest answer till date :P</p>\n\n<pre><code>Invoke(new Action(() =&gt;\n {\n label1.Text = \"WooHoo!!!\";\n }));\n</code></pre>\n\n<p>This is how i access any form control from a thread.</p>\n" }, { "answer_id": 47085518, "author": "Hamid Jolany", "author_id": 555078, "author_profile": "https://Stackoverflow.com/users/555078", "pm_score": 3, "selected": false, "text": "<pre><code>this.Invoke(new MethodInvoker(delegate\n {\n //your code here;\n }));\n</code></pre>\n" }, { "answer_id": 47852810, "author": "Antonio Leite", "author_id": 1150820, "author_profile": "https://Stackoverflow.com/users/1150820", "pm_score": 0, "selected": false, "text": "<p>Action y; //declared inside class</p>\n\n<p>label1.Invoke(y=()=>label1.Text=\"text\");</p>\n" }, { "answer_id": 49626128, "author": "Nasir Mahmood", "author_id": 1019417, "author_profile": "https://Stackoverflow.com/users/1019417", "pm_score": -1, "selected": false, "text": "<p>There are two options for cross thread operations.</p>\n\n<pre><code>Control.InvokeRequired Property \n</code></pre>\n\n<p>and second one is to use </p>\n\n<pre><code>SynchronizationContext Post Method\n</code></pre>\n\n<p>Control.InvokeRequired is only useful when working controls inherited from Control class while SynchronizationContext can be used anywhere. Some useful information is as following links</p>\n\n<p><a href=\"http://www.ilmlinks.com/Snippets/cross-thread-update-ui-in-dotnet\" rel=\"nofollow noreferrer\">Cross Thread Update UI | .Net</a> </p>\n\n<p><a href=\"http://www.ilmlinks.com/Snippets/cross-thread-update-ui-in-dotnet-synchronization-context\" rel=\"nofollow noreferrer\">Cross Thread Update UI using SynchronizationContext | .Net</a></p>\n" }, { "answer_id": 55894507, "author": "Hasan Shouman", "author_id": 3293110, "author_profile": "https://Stackoverflow.com/users/3293110", "pm_score": 2, "selected": false, "text": "<p>Simply use this:</p>\n\n<pre><code>this.Invoke((MethodInvoker)delegate\n {\n YourControl.Property= value; // runs thread safe\n });\n</code></pre>\n" }, { "answer_id": 61685935, "author": "Timothy Macharia", "author_id": 3499361, "author_profile": "https://Stackoverflow.com/users/3499361", "pm_score": 3, "selected": false, "text": "<p>Simple and re-usable way to work around this problem.</p>\n\n<p><strong>Extension Method</strong></p>\n\n<pre><code>public static class FormExts\n{\n public static void LoadOnUI(this Form frm, Action action)\n {\n if (frm.InvokeRequired) frm.Invoke(action);\n else action.Invoke();\n }\n}\n</code></pre>\n\n<p><strong>Sample Usage</strong></p>\n\n<pre><code>private void OnAnyEvent(object sender, EventArgs args)\n{\n this.LoadOnUI(() =&gt;\n {\n label1.Text = \"\";\n button1.Text = \"\";\n });\n}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22858/" ]
I have a scenario. (Windows Forms, C#, .NET) 1. There is a main form which hosts some user control. 2. The user control does some heavy data operation, such that if I directly call the `UserControl_Load` method the UI become nonresponsive for the duration for load method execution. 3. To overcome this I load data on different thread (trying to change existing code as little as I can) 4. I used a background worker thread which will be loading the data and when done will notify the application that it has done its work. 5. Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl. The pseudocode would look like this: **CODE 1** ``` UserContrl1_LoadDataMethod() { if (textbox1.text == "MyName") // This gives exception { //Load data corresponding to "MyName". //Populate a globale variable List<string> which will be binded to grid at some later stage. } } ``` The Exception it gave was > > Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. > > > To know more about this I did some googling and a suggestion came up like using the following code **CODE 2** ``` UserContrl1_LoadDataMethod() { if (InvokeRequired) // Line #1 { this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod)); return; } if (textbox1.text == "MyName") // Now it won't give an exception { //Load data correspondin to "MyName" //Populate a globale variable List<string> which will be binded to grid at some later stage } } ``` But it still seems that I've come back to square one. The Application again becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned. I don't know whether I perceived this right or wrong. I'm new to threading. How do I resolve this and also what is the effect of execution of Line#1 if block? **The situation is this**: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread. So only accessing the value so that the corresponding data can be fetched from the database.
As per [Prerak K's update comment](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108) (since deleted): > > I guess I have not presented the question properly. > > > Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread. > > > So only accessing the value so that corresponding data can be fetched from the database. > > > The solution you want then should look like: ``` UserContrl1_LOadDataMethod() { string name = ""; if(textbox1.InvokeRequired) { textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; })); } if(name == "MyName") { // do whatever } } ``` Do your serious processing in the separate thread *before* you attempt to switch back to the control's thread. For example: ``` UserContrl1_LOadDataMethod() { if(textbox1.text=="MyName") //<<======Now it wont give exception** { //Load data correspondin to "MyName" //Populate a globale variable List<string> which will be //bound to grid at some later stage if(InvokeRequired) { // after we've done all the processing, this.Invoke(new MethodInvoker(delegate { // load the control with the appropriate data })); return; } } } ```
142,010
<p>Say I have the following XML...</p> <pre><code>&lt;root&gt; &lt;base&gt; &lt;tent key="1" color="red"/&gt; &lt;tent key="2" color="yellow"/&gt; &lt;tent key="3" color="blue"/&gt; &lt;/base&gt; &lt;bucket&gt; &lt;tent key="1"/&gt; &lt;tent key="3"/&gt; &lt;/bucket&gt; &lt;/root&gt; </code></pre> <p>...what would the XPath be that returns that the "bucket" contains "red" and "blue"?</p>
[ { "answer_id": 142067, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 2, "selected": false, "text": "<p>I think this will work:</p>\n\n<pre><code>/root/base/tent[/root/bucket/tent/@key = @key ]/@color\n</code></pre>\n" }, { "answer_id": 142714, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>It's not pretty. As with any lookup, you need to use current():</p>\n\n<p>/root/bucket[/root/base/tent[@key = current()/tent/@key]/@color = 'blue' or /root/base/tent[@key = current()/tent/@key]/@color = 'red']</p>\n" }, { "answer_id": 144505, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<p>If you're using XSLT, I'd recommend setting up a key:</p>\n\n<pre><code>&lt;xsl:key name=\"tents\" match=\"base/tent\" use=\"@key\" /&gt;\n</code></pre>\n\n<p>You can then get the <code>&lt;tent&gt;</code> within <code>&lt;base&gt;</code> with a particular <code>key</code> using</p>\n\n<pre><code>key('tents', $id)\n</code></pre>\n\n<p>Then you can do</p>\n\n<pre><code>key('tents', /root/bucket/tent/@key)/@color\n</code></pre>\n\n<p>or, if <code>$bucket</code> is a particular <code>&lt;bucket&gt;</code> element,</p>\n\n<pre><code>key('tents', $bucket/tent/@key)/@color\n</code></pre>\n" }, { "answer_id": 150744, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>JeniT has the appropriate response / code listed here. You need to create the key before you walk the XML Document, then perform matches against that key.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
Say I have the following XML... ``` <root> <base> <tent key="1" color="red"/> <tent key="2" color="yellow"/> <tent key="3" color="blue"/> </base> <bucket> <tent key="1"/> <tent key="3"/> </bucket> </root> ``` ...what would the XPath be that returns that the "bucket" contains "red" and "blue"?
If you're using XSLT, I'd recommend setting up a key: ``` <xsl:key name="tents" match="base/tent" use="@key" /> ``` You can then get the `<tent>` within `<base>` with a particular `key` using ``` key('tents', $id) ``` Then you can do ``` key('tents', /root/bucket/tent/@key)/@color ``` or, if `$bucket` is a particular `<bucket>` element, ``` key('tents', $bucket/tent/@key)/@color ```
142,016
<p>I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.</p> <p>IE: given</p> <pre><code>struct mstct { int myfield; int myfield2; }; </code></pre> <p>I could write:</p> <pre><code>mstct thing; printf("offset %lu\n", (unsigned long)(&amp;thing.myfield2 - &amp;thing)); </code></pre> <p>And get <code>offset 4</code> for the output. How can I do it without that <code>mstct thing</code> declaration/allocating one?</p> <p>I know that <code>&amp;&lt;struct&gt;</code> does not always point at the first byte of the first field of the structure, I can account for that later.</p>
[ { "answer_id": 142023, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 7, "selected": true, "text": "<p>How about the standard offsetof() macro (in stddef.h)?</p>\n\n<p>Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:</p>\n\n<pre><code>#define OFFSETOF(type, field) ((unsigned long) &amp;(((type *) 0)-&gt;field))\n</code></pre>\n" }, { "answer_id": 142049, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>Right, use the <code>offsetof</code> macro, which (at least with GNU CC) is available to both C and C++ code:</p>\n\n<pre><code>offsetof(struct mstct, myfield2)\n</code></pre>\n" }, { "answer_id": 142052, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>printf(\"offset: %d\\n\", &amp;((mstct*)0)->myfield2);</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure. IE: given ``` struct mstct { int myfield; int myfield2; }; ``` I could write: ``` mstct thing; printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing)); ``` And get `offset 4` for the output. How can I do it without that `mstct thing` declaration/allocating one? I know that `&<struct>` does not always point at the first byte of the first field of the structure, I can account for that later.
How about the standard offsetof() macro (in stddef.h)? Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like: ``` #define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field)) ```
142,042
<p>I want to attach an xslt stylesheet to an XML document that I build with XMLBuilder. This is done with a Processing Instruction that looks like</p> <pre><code>&lt;?xml-stylesheet type='text/xsl' href='/stylesheets/style.xslt' ?&gt; </code></pre> <p>Normally, I'd use the <code>instruct!</code> method, but <code>:xml-stylesheet</code> is not a valid Ruby symbol.</p> <p>XMLBuilder has a solution for this case for elements using <code>tag!</code> method, but I don't see the equivalent for Processing Instructions.</p> <p>Any ideas?</p>
[ { "answer_id": 142077, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 3, "selected": true, "text": "<p>I'm not sure this will solve your problem since I don't know the instruct! method of that object, but :'xml-stylesheet' is a valid ruby symbol.</p>\n" }, { "answer_id": 142158, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 3, "selected": false, "text": "<p>You do it like this:</p>\n\n<pre><code>xm.instruct! 'xml-stylesheet', {:href=&gt;'/stylesheets/style.xslt', :type=&gt;'text/xsl'}\n</code></pre>\n\n<p>Just add that line right after</p>\n\n<pre><code>xm.instruct! :xml, {:encoding=&gt;\"your_encoding_type\"}\n</code></pre>\n\n<p>and before the rest of your document output code and you should be good to go.</p>\n" }, { "answer_id": 26656521, "author": "andrhamm", "author_id": 169717, "author_profile": "https://Stackoverflow.com/users/169717", "pm_score": 0, "selected": false, "text": "<p>If using the <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/AtomFeedHelper.html#method-i-atom_feed\" rel=\"nofollow\"><code>atom_feed</code></a> helper, you can pass this in the <code>instruct</code> option:</p>\n\n<pre><code>atom_feed(instruct: {\n 'xml-stylesheet' =&gt; {type: 'text/xsl', href: 'styles.xml'}\n }) do |feed|\n feed.title \"My Atom Feed\"\n # entries...\nend\n</code></pre>\n\n<p>Which results in (showing only first 3 lines):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;?xml-stylesheet type=\"text/xsl\" href=\"styles.xml\"?&gt;\n&lt;feed xml:lang=\"en-US\" xmlns=\"http://www.w3.org/2005/Atom\"&gt;\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10026/" ]
I want to attach an xslt stylesheet to an XML document that I build with XMLBuilder. This is done with a Processing Instruction that looks like ``` <?xml-stylesheet type='text/xsl' href='/stylesheets/style.xslt' ?> ``` Normally, I'd use the `instruct!` method, but `:xml-stylesheet` is not a valid Ruby symbol. XMLBuilder has a solution for this case for elements using `tag!` method, but I don't see the equivalent for Processing Instructions. Any ideas?
I'm not sure this will solve your problem since I don't know the instruct! method of that object, but :'xml-stylesheet' is a valid ruby symbol.
142,090
<p>I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?</p> <p>Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.</p>
[ { "answer_id": 142112, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<pre><code>class ValidationRule {\n public delegate bool Validator();\n\n private Validator _v;\n\n public ValidationRule(Validator v) { _v = v; }\n\n public Validator Validator {\n get { return _v; }\n set { _v = value; }\n }\n\n public bool IsValid { get { return _v(); } }\n}\n\nvar alwaysPasses = new ValidationRule(() =&gt; true);\nvar alwaysFails = new ValidationRule(() =&gt; false);\n\nvar textBoxHasText = new ValidationRule(() =&gt; textBox1.Text.Length &gt; 0);\n</code></pre>\n\n<p>That should get you started. But, really, inheritance is far more appropriate here. The problem is simply that the <code>Validator</code> doesn't have access to any state that it doesn't close over, this means that it isn't as reusable as say <code>ValidationRules</code> that contain their own state. Compare the following class to the previous definition of <code>textBoxHasText</code>.</p>\n\n<pre><code>interface IValidationRule {\n bool IsValid { get; }\n}\n\nclass BoxHasText : IValidationRule {\n TextBox _c;\n\n public BoxHasText(TextBox c) { _c = c; }\n\n public bool IsValid {\n get { return _c.Text.Length &gt; 0; }\n }\n}\n</code></pre>\n" }, { "answer_id": 142129, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "<p>Really, what you want to use is <code>Func&lt;T,bool&gt;</code> where T is the type of the item you want to validate. Then you would do something like this</p>\n\n<pre><code>validator.AddValidation(item =&gt; (item.HasEnoughInformation() || item.IsEmpty());\n</code></pre>\n\n<p>you could store them in a <code>List&lt;Func&lt;T,bool&gt;&gt;</code>.</p>\n" }, { "answer_id": 142160, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 1, "selected": false, "text": "<p>something like:</p>\n\n<pre><code>class ValidationRule\n{\n private Func&lt;bool&gt; validation;\n\n public ValidationRule(Func&lt;bool&gt; validation)\n {\n this.validation = validation;\n }\n public bool IsValid()\n {\n return validation();\n }\n}\n</code></pre>\n\n<p>would be more C# 3 style but is compiled to the same code as @Frank Krueger's answer.\nThis is what you asked for, but doesn't feel right. Is there a good reason why the entity can't be extended to perform validation?</p>\n" }, { "answer_id": 142165, "author": "Jason Olson", "author_id": 5418, "author_profile": "https://Stackoverflow.com/users/5418", "pm_score": 2, "selected": false, "text": "<p>Well, simply, if you have an Entity class, and you want to use lambda expressions on that Entity to determine if something is valid (returning boolean), you could use a Func. </p>\n\n<p>So, given an Entity:</p>\n\n<pre><code> class Entity\n {\n public string MyProperty { get; set; }\n }\n</code></pre>\n\n<p>You could define a ValidationRule class for that like this:</p>\n\n<pre><code> class ValidationRule&lt;T&gt; where T : Entity\n {\n private Func&lt;T, bool&gt; _rule;\n\n public ValidationRule(Func&lt;T, bool&gt; rule)\n {\n _rule = rule;\n }\n\n public bool IsValid(T entity)\n {\n return _rule(entity);\n }\n }\n</code></pre>\n\n<p>Then you could use it like this:</p>\n\n<pre><code> var myEntity = new Entity() { MyProperty = \"Hello World\" };\n var rule = new ValidationRule&lt;Entity&gt;(entity =&gt; entity.MyProperty == \"Hello World\");\n\n var valid = rule.IsValid(myEntity);\n</code></pre>\n\n<p>Of course, that's just one possible solution.</p>\n\n<p>If you remove the generic constraint above (\"where T : Entity\"), you could make this a generic rules engine that could be used with any POCO. You wouldn't have to derive a class for every type of usage you need. So if I wanted to use this same class on a TextBox, I could use the following (after removing the generic constraint):</p>\n\n<pre><code> var rule = new ValidationRule&lt;TextBox&gt;(tb =&gt; tb.Text.Length &gt; 0);\n rule.IsValid(myTextBox);\n</code></pre>\n\n<p>It's pretty flexible this way. Using lambda expressions and generics together is very powerful. Instead of accepting Func or Action, you could accept an Expression> or Expression> and have direct access to the express tree to automatically investigate things like the name of a method or property, what type of expression it is, etc. And people using your class would not have to change a single line of code.</p>\n" }, { "answer_id": 541488, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": "<p>Would a rule definition syntax like this one work for you?</p>\n\n<pre><code> public static void Valid(Address address, IScope scope)\n {\n scope.Validate(() =&gt; address.Street1, StringIs.Limited(10, 256));\n scope.Validate(() =&gt; address.Street2, StringIs.Limited(256));\n scope.Validate(() =&gt; address.Country, Is.NotDefault);\n scope.Validate(() =&gt; address.Zip, StringIs.Limited(10));\n\n switch (address.Country)\n {\n case Country.USA:\n scope.Validate(() =&gt; address.Zip, StringIs.Limited(5, 10));\n break;\n case Country.France:\n break;\n case Country.Russia:\n scope.Validate(() =&gt; address.Zip, StringIs.Limited(6, 6));\n break;\n default:\n scope.Validate(() =&gt; address.Zip, StringIs.Limited(1, 64));\n break;\n }\n</code></pre>\n\n<p>Check out <a href=\"http://abdullin.com/journal/2009/1/29/ddd-and-rule-driven-ui-validation-in-net.html\" rel=\"nofollow noreferrer\">DDD and Rule driven UI Validation in .NET</a> for more information</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property? Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.
Really, what you want to use is `Func<T,bool>` where T is the type of the item you want to validate. Then you would do something like this ``` validator.AddValidation(item => (item.HasEnoughInformation() || item.IsEmpty()); ``` you could store them in a `List<Func<T,bool>>`.
142,110
<p>Basically I want to know how to set center alignment for a cell using VBScript...</p> <p>I've been googling it and can't seem to find anything that helps.</p>
[ { "answer_id": 142170, "author": "mistrmark", "author_id": 19242, "author_profile": "https://Stackoverflow.com/users/19242", "pm_score": 1, "selected": false, "text": "<p>There are many ways to select a cell or a range of cells, but the following will work for a single cell.</p>\n\n<pre><code>'Select a Cell Range\nRange(\"D4\").Select\n\n'Set the horizontal and vertical alignment\nWith Selection\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlBottom\nEnd With\n</code></pre>\n\n<p>The HorizontalAlignment options are xlLeft, xlRight, and xlCenter</p>\n" }, { "answer_id": 142187, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 4, "selected": true, "text": "<pre><code>Set excel = CreateObject(\"Excel.Application\")\n\nexcel.Workbooks.Add() ' create blank workbook\n\nSet workbook = excel.Workbooks(1)\n\n' set A1 to be centered.\nworkbook.Sheets(1).Cells(1,1).HorizontalAlignment = -4108 ' xlCenter constant.\n\nworkbook.SaveAs(\"C:\\NewFile.xls\")\n\nexcel.Quit()\n\nset excel = nothing\n\n'If the script errors, it'll give you an orphaned excel process, so be warned.\n</code></pre>\n\n<p>Save that as a .vbs and run it using the command prompt or double clicking.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Basically I want to know how to set center alignment for a cell using VBScript... I've been googling it and can't seem to find anything that helps.
``` Set excel = CreateObject("Excel.Application") excel.Workbooks.Add() ' create blank workbook Set workbook = excel.Workbooks(1) ' set A1 to be centered. workbook.Sheets(1).Cells(1,1).HorizontalAlignment = -4108 ' xlCenter constant. workbook.SaveAs("C:\NewFile.xls") excel.Quit() set excel = nothing 'If the script errors, it'll give you an orphaned excel process, so be warned. ``` Save that as a .vbs and run it using the command prompt or double clicking.
142,121
<p>I have a class that processes a 2 xml files and produces a text file. </p> <p>I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:</p> <ol> <li>For input A and B, generate the output.</li> <li>Compare the contents of the generated file to the contents expected output</li> <li>When the actual contents differ from the expected contents, fail and display some <strong>useful</strong> information about the differences.</li> </ol> <p>Below is the prototype for the class along with my first stab at unit tests.</p> <p><strong>Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?</strong></p> <p><strong>Is there a better way to coax text-file differences from NUnit?</strong> Should I embed a textfile diff algorithm?</p> <hr> <pre><code>class ReportGenerator { string Generate(string inputPathA, string inputPathB) { //do stuff } } </code></pre> <hr> <pre><code>[TextFixture] public class ReportGeneratorTests { static Diff(string pathToExpectedResult, string pathToActualResult) { using (StreamReader rs1 = File.OpenText(pathToExpectedResult)) { using (StreamReader rs2 = File.OpenText(pathToActualResult)) { string actualContents = rs2.ReadToEnd(); string expectedContents = rs1.ReadToEnd(); //this works, but the output could be a LOT more useful. Assert.AreEqual(expectedContents, actualContents); } } } static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult) { ReportGenerator obj = new ReportGenerator(); string pathToResult = obj.Generate(pathToInputA, pathToInputB); Diff(pathToExpectedResult, pathToResult); } [Test] public void TestX() { TestGenerate("x1.xml", "x2.xml", "x-expected.txt"); } [Test] public void TestY() { TestGenerate("y1.xml", "y2.xml", "y-expected.txt"); } //etc... } </code></pre> <hr> <h2>Update</h2> <p>I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.</p>
[ { "answer_id": 142169, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 0, "selected": false, "text": "<p>Rather than call .AreEqual you could parse the two input streams yourself, keep a count of line and column and compare the contents. As soon as you find a difference, you can generate a message like...</p>\n\n<blockquote>\n <p>Line 32 Column 12 - Found 'x' when 'y' was expected</p>\n</blockquote>\n\n<p>You could optionally enhance that by displaying multiple lines of output</p>\n\n<blockquote>\n <p>Difference at Line 32 Column 12, first difference shown<br>\n A = this is a t<strong>x</strong>st<br>\n B = this is a t<strong>e</strong>sts</p>\n</blockquote>\n\n<p>Note, as a rule, I'd generally only generate through my code one of the two streams you have. The other I'd grab from a test/text file, having verified by eye or other method that the data contained is correct!</p>\n" }, { "answer_id": 142172, "author": "Alan Hensel", "author_id": 14532, "author_profile": "https://Stackoverflow.com/users/14532", "pm_score": 0, "selected": false, "text": "<p>I would probably write a single unit test that contains a loop. Inside the loop, I'd read 2 xml files and a diff file, and then diff the xml files (without writing it to disk) and compare it to the diff file read from disk. The files would be numbered, e.g. a1.xml, b1.xml, diff1.txt ; a2.xml, b2.xml, diff2.txt ; a3.xml, b3.xml, diff3.txt, etc., and the loop stops when it doesn't find the next number.</p>\n\n<p>Then, you can write new tests just by adding new text files.</p>\n" }, { "answer_id": 142312, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 4, "selected": true, "text": "<p>As for the multiple tests with different data, use the NUnit RowTest extension:</p>\n\n<pre><code>using NUnit.Framework.Extensions;\n\n[RowTest]\n[Row(\"x1.xml\", \"x2.xml\", \"x-expected.xml\")]\n[Row(\"y1.xml\", \"y2.xml\", \"y-expected.xml\")]\npublic void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)\n {\n ReportGenerator obj = new ReportGenerator();\n string pathToResult = obj.Generate(pathToInputA, pathToInputB);\n Diff(pathToExpectedResult, pathToResult);\n }\n</code></pre>\n" }, { "answer_id": 143054, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 0, "selected": false, "text": "<p>I would probably use XmlReader to iterate through the files and compare them. When I hit a difference I would display an XPath to the location where the files are different.</p>\n\n<p>PS: But in reality it was always enough for me to just do a simple read of the whole file to a string and compare the two strings. For the reporting it is enough to see that the test failed. Then when I do the debugging I usually diff the files using <a href=\"http://www.araxis.com/merge/index.html\" rel=\"nofollow noreferrer\">Araxis Merge</a> to see where exactly I have issues.</p>\n" }, { "answer_id": 145345, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "<p>You are probably asking for the testing against \"gold\" data. I don't know if there is specific term for this kind of testing accepted world-wide, but this is how we do it. </p>\n\n<p>Create base fixture class. It basically has \"void DoTest(string fileName)\", which will read specific file into memory, execute abstract transformation method \"string Transform(string text)\", then read fileName.gold from the same place and compare transformed text with what was expected. If content is different, it throws exception. Exception thrown contains line number of the first difference as well as text of expected and actual line. As text is stable, this is usually enough information to spot the problem right away. Be sure to mark lines with \"Expected:\" and \"Actual:\", or you will be guessing forever which is which when looking at test results. </p>\n\n<p>Then, you will have specific test fixtures, where you implement Transform method which does right job, and then have tests which look like this:</p>\n\n<pre><code>[Test] public void TestX() { DoTest(\"X\"); }\n[Test] public void TestY() { DoTest(\"Y\"); }\n</code></pre>\n\n<p>Name of the failed test will instantly tell you what is broken. Of course, you can use row testing to group similar tests. Having separate tests also helps in a number of situations like ignoring tests, communicating tests to colleagues and so on. It is not a big deal to create a snippet which will create test for you in a second, you will spend much more time preparing data. </p>\n\n<p>Then you will also need some test data and a way your base fixture will find it, be sure to set up rules about it for the project. If test fails, dump actual output to the file near the gold, and erase it if test pass. This way you can use diff tool when needed. When there is no gold data found, test fails with appropriate message, but actual output is written anyway, so you can check that it is correct and copy it to become \"gold\". </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
I have a class that processes a 2 xml files and produces a text file. I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following: 1. For input A and B, generate the output. 2. Compare the contents of the generated file to the contents expected output 3. When the actual contents differ from the expected contents, fail and display some **useful** information about the differences. Below is the prototype for the class along with my first stab at unit tests. **Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?** **Is there a better way to coax text-file differences from NUnit?** Should I embed a textfile diff algorithm? --- ``` class ReportGenerator { string Generate(string inputPathA, string inputPathB) { //do stuff } } ``` --- ``` [TextFixture] public class ReportGeneratorTests { static Diff(string pathToExpectedResult, string pathToActualResult) { using (StreamReader rs1 = File.OpenText(pathToExpectedResult)) { using (StreamReader rs2 = File.OpenText(pathToActualResult)) { string actualContents = rs2.ReadToEnd(); string expectedContents = rs1.ReadToEnd(); //this works, but the output could be a LOT more useful. Assert.AreEqual(expectedContents, actualContents); } } } static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult) { ReportGenerator obj = new ReportGenerator(); string pathToResult = obj.Generate(pathToInputA, pathToInputB); Diff(pathToExpectedResult, pathToResult); } [Test] public void TestX() { TestGenerate("x1.xml", "x2.xml", "x-expected.txt"); } [Test] public void TestY() { TestGenerate("y1.xml", "y2.xml", "y-expected.txt"); } //etc... } ``` --- Update ------ I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.
As for the multiple tests with different data, use the NUnit RowTest extension: ``` using NUnit.Framework.Extensions; [RowTest] [Row("x1.xml", "x2.xml", "x-expected.xml")] [Row("y1.xml", "y2.xml", "y-expected.xml")] public void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult) { ReportGenerator obj = new ReportGenerator(); string pathToResult = obj.Generate(pathToInputA, pathToInputB); Diff(pathToExpectedResult, pathToResult); } ```
142,142
<p>Is there a query in SQL Server 2005 I can use to get the server's IP or name?</p>
[ { "answer_id": 142144, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "<pre><code>select @@servername\n</code></pre>\n" }, { "answer_id": 142146, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 3, "selected": false, "text": "<p>It's in the <a href=\"http://msdn.microsoft.com/en-us/library/ms187944.aspx\" rel=\"noreferrer\">@@SERVERNAME </a>variable;</p>\n\n<pre><code>SELECT @@SERVERNAME;\n</code></pre>\n" }, { "answer_id": 142157, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "<p>You can get the[hostname]\\[instancename] by:</p>\n\n<pre><code>SELECT @@SERVERNAME;\n</code></pre>\n\n<p>To get only the hostname when you have hostname\\instance name format:</p>\n\n<pre><code>SELECT LEFT(ltrim(rtrim(@@ServerName)), Charindex('\\', ltrim(rtrim(@@ServerName))) -1)\n</code></pre>\n\n<p>Alternatively as @GilM pointed out:</p>\n\n<pre><code>SELECT SERVERPROPERTY('MachineName')\n</code></pre>\n\n<p>You can get the actual IP address using this:</p>\n\n<pre><code>create Procedure sp_get_ip_address (@ip varchar(40) out)\nas\nbegin\nDeclare @ipLine varchar(200)\nDeclare @pos int\nset nocount on\n set @ip = NULL\n Create table #temp (ipLine varchar(200))\n Insert #temp exec master..xp_cmdshell 'ipconfig'\n select @ipLine = ipLine\n from #temp\n where upper (ipLine) like '%IP ADDRESS%'\n if (isnull (@ipLine,'***') != '***')\n begin \n set @pos = CharIndex (':',@ipLine,1);\n set @ip = rtrim(ltrim(substring (@ipLine , \n @pos + 1 ,\n len (@ipLine) - @pos)))\n end \ndrop table #temp\nset nocount off\nend \ngo\n\ndeclare @ip varchar(40)\nexec sp_get_ip_address @ip out\nprint @ip\n</code></pre>\n\n<p><a href=\"http://www.sqlmag.com/Articles/ArticleID/48303/48303.html?Ad=1\" rel=\"noreferrer\">Source of the SQL script</a>.</p>\n" }, { "answer_id": 142517, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 2, "selected": false, "text": "<p>A simpler way to get the machine name without the \\InstanceName is:</p>\n\n<pre><code>SELECT SERVERPROPERTY('MachineName')\n</code></pre>\n" }, { "answer_id": 9622810, "author": "chris", "author_id": 1236579, "author_profile": "https://Stackoverflow.com/users/1236579", "pm_score": 5, "selected": false, "text": "<p>The server might have multiple IP addresses that it is listening on. If your connection has the VIEW SERVER STATE server permission granted to it, you can run this query to get the address you have connected to SQL Server:</p>\n\n<pre><code>SELECT dec.local_net_address\nFROM sys.dm_exec_connections AS dec\nWHERE dec.session_id = @@SPID;\n</code></pre>\n\n<p>This solution does not require you to shell out to the OS via xp_cmdshell, which is a technique that should be disabled (or at least strictly secured) on a production server. It may require you to grant VIEW SERVER STATE to the appropriate login, but that is a far smaller security risk than running xp_cmdshell.</p>\n\n<p>The technique mentioned by GilM for the server name is the preferred one:</p>\n\n<pre><code>SELECT SERVERPROPERTY(N'MachineName');\n</code></pre>\n" }, { "answer_id": 14695530, "author": "Jeff Muzzy", "author_id": 2041021, "author_profile": "https://Stackoverflow.com/users/2041021", "pm_score": 8, "selected": false, "text": "<pre><code>SELECT \n CONNECTIONPROPERTY('net_transport') AS net_transport,\n CONNECTIONPROPERTY('protocol_type') AS protocol_type,\n CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,\n CONNECTIONPROPERTY('local_net_address') AS local_net_address,\n CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,\n CONNECTIONPROPERTY('client_net_address') AS client_net_address \n</code></pre>\n\n<p>The code here Will give you the IP Address; </p>\n\n<p>This will work for a remote client request to SQL 2008 and newer. </p>\n\n<p>If you have Shared Memory connections allowed, then running above on the server itself will give you </p>\n\n<ul>\n<li>\"Shared Memory\" as the value for 'net_transport', and </li>\n<li>NULL for 'local_net_address', and </li>\n<li>'<code>&lt;local machine&gt;</code>' will be shown in 'client_net_address'.</li>\n</ul>\n\n<p>'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.</p>\n\n<p>I advice strongly against using <a href=\"https://stackoverflow.com/a/142157/578411\">this answer</a>. Enabling the shell out is a very bad idea on a production SQL Server.</p>\n" }, { "answer_id": 33652731, "author": "Dave Mason", "author_id": 2961160, "author_profile": "https://Stackoverflow.com/users/2961160", "pm_score": 4, "selected": false, "text": "<p>Most solutions for getting the IP address via t-sql fall into these two camps:</p>\n\n<ol>\n<li><p>Run <code>ipconfig.exe</code> via <code>xp_cmdshell</code> and parse the output</p></li>\n<li><p>Query DMV <code>sys.dm_exec_connections</code></p></li>\n</ol>\n\n<p>I'm not a fan of option #1. Enabling xp_cmdshell has security drawbacks, and there's lots of parsing involved anyway. That's cumbersome. Option #2 is elegant. And it's a pure t-sql solution, which I almost always prefer. Here are two sample queries for option #2:</p>\n\n<pre><code>SELECT c.local_net_address\nFROM sys.dm_exec_connections AS c\nWHERE c.session_id = @@SPID;\n\nSELECT TOP(1) c.local_net_address\nFROM sys.dm_exec_connections AS c\nWHERE c.local_net_address IS NOT NULL;\n</code></pre>\n\n<p>Sometimes, neither of the above queries works, though. Query #1 returns NULL if you're connected over Shared Memory (logged in and running SSMS on the SQL host). Query #2 may return nothing if there are no connections using a non-Shared Memory protocol. This scenario is likely when connected to a newly installed SQL instance. The solution? Force a connection over TCP/IP. To do this, create a new connection in SSMS and use the \"tcp:\" prefix with the server name. Then re-run either query and you'll get the IP address.</p>\n\n<p><a href=\"https://i.stack.imgur.com/UTRSk.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UTRSk.png\" alt=\"SSMS - Connect to Database Engine\"></a></p>\n" }, { "answer_id": 35604300, "author": "Bert Van Landeghem", "author_id": 2208335, "author_profile": "https://Stackoverflow.com/users/2208335", "pm_score": 2, "selected": false, "text": "<p>I know this is an old post, but perhaps this solution can be usefull when you want to retrieve the IP address and TCP port from a Shared Memory connection (e.g. from a script run in SSMS locally on the server). The key is to open a secondary connection to your SQL Server using OPENROWSET, in which you specify 'tcp:' in your connection string. The rest of the code is merely building dynamic SQL to get around OPENROWSET’s limitation of not being able to take variables as its parameters.</p>\n\n<pre><code>DECLARE @ip_address varchar(15)\nDECLARE @tcp_port int \nDECLARE @connectionstring nvarchar(max) \nDECLARE @parm_definition nvarchar(max)\nDECLARE @command nvarchar(max)\n\nSET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'\nSET @parm_definition = N'@ip_address_OUT varchar(15) OUTPUT\n , @tcp_port_OUT int OUTPUT';\n\nSET @command = N'SELECT @ip_address_OUT = a.local_net_address,\n @tcp_port_OUT = a.local_tcp_port\n FROM OPENROWSET(''SQLNCLI''\n , ''' + @connectionstring + '''\n , ''SELECT local_net_address\n , local_tcp_port\n FROM sys.dm_exec_connections\n WHERE session_id = @@spid\n '') as a'\n\nEXEC SP_executeSQL @command\n , @parm_definition\n , @ip_address_OUT = @ip_address OUTPUT\n , @tcp_port_OUT = @tcp_port OUTPUT;\n\n\nSELECT @ip_address, @tcp_port\n</code></pre>\n" }, { "answer_id": 38758901, "author": "Ranjana Ghimire", "author_id": 6636573, "author_profile": "https://Stackoverflow.com/users/6636573", "pm_score": 3, "selected": false, "text": "<p>you can use command line query and execute in mssql:</p>\n\n<pre><code>exec xp_cmdshell 'ipconfig'\n</code></pre>\n" }, { "answer_id": 47144078, "author": "Hank Freeman", "author_id": 2437624, "author_profile": "https://Stackoverflow.com/users/2437624", "pm_score": 4, "selected": false, "text": "<p>--Try this script it works to my needs. Reformat to read it.</p>\n\n<pre><code>SELECT \nSERVERPROPERTY('ComputerNamePhysicalNetBios') as 'Is_Current_Owner'\n ,SERVERPROPERTY('MachineName') as 'MachineName'\n ,case when @@ServiceName = \n Right (@@Servername,len(@@ServiceName)) then @@Servername \n else @@servername +' \\ ' + @@Servicename\n end as '@@Servername \\ Servicename', \n CONNECTIONPROPERTY('net_transport') AS net_transport,\n CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,\n dec.local_tcp_port,\n CONNECTIONPROPERTY('local_net_address') AS local_net_address,\n dec.local_net_address as 'dec.local_net_address'\n FROM sys.dm_exec_connections AS dec\n WHERE dec.session_id = @@SPID;\n</code></pre>\n" }, { "answer_id": 65750630, "author": "Eralper", "author_id": 832991, "author_profile": "https://Stackoverflow.com/users/832991", "pm_score": 0, "selected": false, "text": "<p>It is possible to use the host_name() function</p>\n<pre><code>select HOST_NAME()\n</code></pre>\n" }, { "answer_id": 67483921, "author": "گلی", "author_id": 15765660, "author_profile": "https://Stackoverflow.com/users/15765660", "pm_score": 2, "selected": false, "text": "<p>Please use this query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT CONNECTIONPROPERTY('local_net_address') AS [IP]\n\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
Is there a query in SQL Server 2005 I can use to get the server's IP or name?
``` SELECT CONNECTIONPROPERTY('net_transport') AS net_transport, CONNECTIONPROPERTY('protocol_type') AS protocol_type, CONNECTIONPROPERTY('auth_scheme') AS auth_scheme, CONNECTIONPROPERTY('local_net_address') AS local_net_address, CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port, CONNECTIONPROPERTY('client_net_address') AS client_net_address ``` The code here Will give you the IP Address; This will work for a remote client request to SQL 2008 and newer. If you have Shared Memory connections allowed, then running above on the server itself will give you * "Shared Memory" as the value for 'net\_transport', and * NULL for 'local\_net\_address', and * '`<local machine>`' will be shown in 'client\_net\_address'. 'client\_net\_address' is the address of the computer that the request originated from, whereas 'local\_net\_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason. I advice strongly against using [this answer](https://stackoverflow.com/a/142157/578411). Enabling the shell out is a very bad idea on a production SQL Server.
142,147
<p>I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.</p> <p>When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.</p> <p>Why does the scope of the 'ii' variable continue between loops?</p> <pre><code>var fs:Array = new Array(); for (var i = 0; i &lt; 3; i++){ var ii = i + 1; fs[i] = function(){ trace(ii); } } fs[0](); </code></pre>
[ { "answer_id": 142224, "author": "gltovar", "author_id": 2855, "author_profile": "https://Stackoverflow.com/users/2855", "pm_score": 0, "selected": false, "text": "<p>Unfortunately Actionscript 2.0 does not have a strong scope... especially on the time line.</p>\n\n<pre><code>var fs:Array = new Array();\n\nfor (var i = 0; i &lt; 3; i++){\n\n var ii = i + 1; \n fs[i] = function(){\n trace(ii);\n }\n}\n\nfs[0]();\ntrace(\"out of scope: \" + ii + \"... but still works\");\n</code></pre>\n" }, { "answer_id": 143356, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, AS2 is not that kind of language; it doesn't have that kind of closure. Functions aren't exactly first-class citizens in AS2, and one of the results of that is that a function doesn't retain its own scope, it has to be associated with some scope when it's called (usually the same scope where the function itself is defined, unless you use a function's <code>call</code> or <code>apply</code> methods). </p>\n\n<p>Then when the function is executed, the scope of variables inside it is just the scope of wherever it happened to be called - in your case, the scope outside your loop. This is also why you can do things like this:</p>\n\n<pre><code>function foo() {\n trace( this.value );\n}\n\nobjA = { value:\"A\" };\nobjB = { value:\"B\" };\n\nfoo.apply( objA ); // A\nfoo.apply( objB ); // B\n\nobjA.foo = foo;\nobjB.foo = foo;\n\nobjA.foo(); // A\nobjB.foo(); // B\n</code></pre>\n\n<p>If you're used to true OO languages that looks very strange, and the reason is that AS2 is ultimately a <a href=\"http://en.wikipedia.org/wiki/Prototype-based_programming\" rel=\"nofollow noreferrer\">prototyped language</a>. Everything that looks object-oriented is just a coincidence. ;D</p>\n" }, { "answer_id": 148682, "author": "Bill", "author_id": 23063, "author_profile": "https://Stackoverflow.com/users/23063", "pm_score": 0, "selected": false, "text": "<p>I came up with a kind of strage solution to my own problem:</p>\n\n<pre><code>var fs:Array = new Array();\n\nfor (var i = 0; i &lt; 3; i++){ \n var ii = i + 1; \n\n f = function(j){\n return function(){\n trace(j);\n };\n };\n fs[i] = f(ii);\n}\n\nfs[0](); //1\nfs[1](); //2\nfs[2](); //3\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3. When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1. Why does the scope of the 'ii' variable continue between loops? ``` var fs:Array = new Array(); for (var i = 0; i < 3; i++){ var ii = i + 1; fs[i] = function(){ trace(ii); } } fs[0](); ```
Unfortunately, AS2 is not that kind of language; it doesn't have that kind of closure. Functions aren't exactly first-class citizens in AS2, and one of the results of that is that a function doesn't retain its own scope, it has to be associated with some scope when it's called (usually the same scope where the function itself is defined, unless you use a function's `call` or `apply` methods). Then when the function is executed, the scope of variables inside it is just the scope of wherever it happened to be called - in your case, the scope outside your loop. This is also why you can do things like this: ``` function foo() { trace( this.value ); } objA = { value:"A" }; objB = { value:"B" }; foo.apply( objA ); // A foo.apply( objB ); // B objA.foo = foo; objB.foo = foo; objA.foo(); // A objB.foo(); // B ``` If you're used to true OO languages that looks very strange, and the reason is that AS2 is ultimately a [prototyped language](http://en.wikipedia.org/wiki/Prototype-based_programming). Everything that looks object-oriented is just a coincidence. ;D
142,240
<p>Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.</p> <p>Some fancy compilers understand the (un)interrelatedness of instructions to a limited extent, and will automatically interleave instruction flows (probably over a longer window than the CPU sees) to better utilise the processor. Deliberate compile-time interleaving of floating and integer instructions is another example of this.</p> <p>Now I have highly-parallel task. And I typically have an ageing single-core x86 processor without hyper-threading.</p> <p>Is there a straight-forward way to get my the body of my 'for' loop for this highly-parallel task to be interleaved so that two (or more) iterations are being done together? (This is slightly different from 'loop unwinding' as I understand it.)</p> <p>My task is a 'virtual machine' running through a set of instructions, which I'll really simplify for illustration as:</p> <pre>void run(int num) { for(int n=0; n&lt;num; n++) { vm_t data(n); for(int i=0; i&lt;data.len(); i++) { data.insn(i).parse(); data.insn(i).eval(); } } }</pre> <p>So the execution trail might look like this:</p> <pre>data(1) insn(0) parse data(1) insn(0) eval data(1) insn(1) parse ... data(2) insn(1) eval data(2) insn(2) parse data(2) insn(2) eval</pre> <p>Now, what I'd like is to be able to do two (or more) iterations explicitly in parallel:</p> <pre>data(1) insn(0) parse data(2) insn(0) parse \ processor can do OOO as these two flow in data(1) insn(0) eval / data(2) insn(0) eval \ OOO opportunity here too data(1) insn(1) parse / data(2) insn(1) parse</pre> <p>I know, from profiling, (e.g. using Callgrind with --simulate-cache=yes), that parsing is about random memory accesses (cache missing) and eval is about doing ops in registers and then writing results back. Each step is several thousand instructions long. So if I can intermingle the two steps for two iterations at once, the processor will hopefully have something to do whilst the cache misses of the parse step are occurring...</p> <p>Is there some c++ template madness to get this kind of explicit parallelism generated?</p> <p>Of course I can do the interleaving - and even staggering - myself in code, but it makes for much less readable code. And if I really want unreadable, I can go so far as assembler! But surely there is some pattern for this kind of thing?</p>
[ { "answer_id": 142277, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 2, "selected": false, "text": "<p>Your best plan may be to look into <a href=\"http://openmp.org\" rel=\"nofollow noreferrer\">OpenMP</a>. It basically allows you to insert \"pragmas\" into your code which tell the compiler how it can split between processors.</p>\n" }, { "answer_id": 142291, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 2, "selected": false, "text": "<p>Hyperthreading is a much higher-level system than instruction reordering. It makes the processor look like two processors to the operating system, so you'd need to use an actual threading library to take advantage of that. The same thing naturally applies to multicore processors.</p>\n\n<p>If you don't want to use low-level threading libraries and instead want to use a task-based parallel system (and it sounds like that's what you're after) I'd suggest looking at <a href=\"http://www.openmp.org/\" rel=\"nofollow noreferrer\">OpenMP</a> or Intel's <a href=\"http://www.threadingbuildingblocks.org/\" rel=\"nofollow noreferrer\">Threading Building Blocks</a>.</p>\n\n<p>TBB is a library, so it can be used with any modern C++ compiler. OpenMP is a set of compiler extensions, so you need a compiler that supports it. GCC/G++ will from verion 4.2 and newer. Recent versions of the Intel and Microsoft compilers also support it. I don't know about any others, though.</p>\n\n<p>EDIT: One other note. Using a system like TBB or OpenMP will scale the processing as much as possible - that is, if you have 100 objects to work on, they'll get split about 50/50 in a two-core system, 25/25/25/25 in a four-core system, etc.</p>\n" }, { "answer_id": 142293, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "<p>Modern processors like the Core 2 have an <em>enormous</em> instruction reorder buffer on the order of nearly 100 instructions; even if the compiler is rather dumb the CPU can still make up for it.</p>\n\n<p>The main issue would be if the code used a lot of registers, in which case the register pressure could force the code to be executed in sequence even if theoretically it could be done in parallel.</p>\n" }, { "answer_id": 142303, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 2, "selected": false, "text": "<p>There is no support for parallel execution in the current C++ standard. This will change for the next version of the standard, due out next year or so.</p>\n\n<p>However, I don't see what you are trying to accomplish. Are you referring to one single-core processor, or multiple processors or cores? If you have only one core, you should do whatever gets the fewest cache misses, which means whatever approach uses the smallest memory working set. This would probably be either doing all the parsing followed by all the evaluation, or doing the parsing and evaluation alternately.</p>\n\n<p>If you have two cores, and want to use them efficiently, you're going to have to either use a particularly smart compiler or language extensions. Is there one particular operating system you're developing for, or should this be for multiple systems? </p>\n" }, { "answer_id": 142402, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 2, "selected": true, "text": "<p>It sounds like you ran into the same problem chip designers face: Executing a single instruction takes a lot of effort, but it involves a bunch of different steps that can be strung together in an <a href=\"http://en.wikipedia.org/wiki/Pipeline_(computing)\" rel=\"nofollow noreferrer\">execution pipeline</a>. (It is easier to execute things in parallel when you can build them out of separate blocks of hardware.)</p>\n\n<p>The most obvious way is to split each task into different threads. You might want to create a single thread to execute each instruction to completion, or create one thread for each of your two execution steps and pass data between them. In either case, you'll have to be very careful with how you share data between threads and make sure to handle the case where one instruction affects the result of the following instruction. Even though you only have one core and only one thread can be running at any given time, your operating system should be able to schedule compute-intense threads while other threads are waiting for their cache misses.</p>\n\n<p>(A few hours of your time would probably pay for a single very fast computer, but if you're trying to deploy it widely on cheap hardware it might make sense to consider the problem the way you're looking at it. Regardless, it's an interesting problem to consider.)</p>\n" }, { "answer_id": 142555, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<p>Given optimizing compilers and pipelined processors, I would suggest you just write clear, readable code.</p>\n" }, { "answer_id": 151001, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://supertech.csail.mit.edu/cilk/\" rel=\"nofollow noreferrer\">cilk</a>. It's an extension to ANSI C that has some nice constructs for writing parallelized code in C. However, since it's an extension of C, it has very limited compiler support, and can be tricky to work with.</p>\n" }, { "answer_id": 174107, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 0, "selected": false, "text": "<p><em>This answer was written assuming the questions does not contain the part \"And I typically have an ageing single-core x86 processor without hyper-threading.\". I hope it might help other people who want to parallelize highly-parallel tasks, but target dual/multicore CPUs.</em></p>\n\n<p>As already posted in <a href=\"https://stackoverflow.com/questions/142240/explicit-code-parallelism-in-c#142277\">another answer</a>, OpenMP is a portable way how to do this. However my experience is OpenMP overhead is quite high and it is very easy to beat it by \nrolling a DIY (Do It Youself) implementation. Hopefully OpenMP will improve over time, but as it is now, I would not recommend using it for anything else than prototyping.</p>\n\n<p>Given the nature of your task, What you want to do is most likely a data based parallelism, which in my experience is quite easy - the programming style can be very similar to a single-core code, because you know what other threads are doing, which makes maintaining thread safety a lot easier - an approach which worked for me: avoid dependencies and call only thread safe functions from the loop.</p>\n\n<p>To create a DYI OpenMP parallel loop you need to:</p>\n\n<ul>\n<li>as a preparation create a serial for loop template and change your code to use functors to implement the loop bodies. This can be tedious, as you need to pass all references across the functor object</li>\n<li>create a virtual JobItem interface for the functor, and inherit your functors from this interface</li>\n<li>create a thread function which is able process individual JobItems objects </li>\n<li>create a thread pool of the thread using this thread function</li>\n<li>experiment with various synchronizations primitives to see which works best for you. While semaphore is very easy to use, its overhead is quite significant and if your loop body is very short, you do not want to pay this overhead for each loop iteration. What worked great for me was a combination of manual reset event + atomic (interlocked) counter as a much faster alternative.</li>\n<li>experiment with various JobItem scheduling strategies. If you have long enough loop, it is better if each thread picks up multiple successive JobItems at a time. This reduces the synchronization overhead and at the same time it makes the threads more cache friendly. You may also want to do this in some dynamic way, reducing the length of the scheduled sequence as you are exhausting your tasks, or letting individual threads to steal items from other thread schedules.</li>\n</ul>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15721/" ]
Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading. Some fancy compilers understand the (un)interrelatedness of instructions to a limited extent, and will automatically interleave instruction flows (probably over a longer window than the CPU sees) to better utilise the processor. Deliberate compile-time interleaving of floating and integer instructions is another example of this. Now I have highly-parallel task. And I typically have an ageing single-core x86 processor without hyper-threading. Is there a straight-forward way to get my the body of my 'for' loop for this highly-parallel task to be interleaved so that two (or more) iterations are being done together? (This is slightly different from 'loop unwinding' as I understand it.) My task is a 'virtual machine' running through a set of instructions, which I'll really simplify for illustration as: ``` void run(int num) { for(int n=0; n<num; n++) { vm_t data(n); for(int i=0; i<data.len(); i++) { data.insn(i).parse(); data.insn(i).eval(); } } } ``` So the execution trail might look like this: ``` data(1) insn(0) parse data(1) insn(0) eval data(1) insn(1) parse ... data(2) insn(1) eval data(2) insn(2) parse data(2) insn(2) eval ``` Now, what I'd like is to be able to do two (or more) iterations explicitly in parallel: ``` data(1) insn(0) parse data(2) insn(0) parse \ processor can do OOO as these two flow in data(1) insn(0) eval / data(2) insn(0) eval \ OOO opportunity here too data(1) insn(1) parse / data(2) insn(1) parse ``` I know, from profiling, (e.g. using Callgrind with --simulate-cache=yes), that parsing is about random memory accesses (cache missing) and eval is about doing ops in registers and then writing results back. Each step is several thousand instructions long. So if I can intermingle the two steps for two iterations at once, the processor will hopefully have something to do whilst the cache misses of the parse step are occurring... Is there some c++ template madness to get this kind of explicit parallelism generated? Of course I can do the interleaving - and even staggering - myself in code, but it makes for much less readable code. And if I really want unreadable, I can go so far as assembler! But surely there is some pattern for this kind of thing?
It sounds like you ran into the same problem chip designers face: Executing a single instruction takes a lot of effort, but it involves a bunch of different steps that can be strung together in an [execution pipeline](http://en.wikipedia.org/wiki/Pipeline_(computing)). (It is easier to execute things in parallel when you can build them out of separate blocks of hardware.) The most obvious way is to split each task into different threads. You might want to create a single thread to execute each instruction to completion, or create one thread for each of your two execution steps and pass data between them. In either case, you'll have to be very careful with how you share data between threads and make sure to handle the case where one instruction affects the result of the following instruction. Even though you only have one core and only one thread can be running at any given time, your operating system should be able to schedule compute-intense threads while other threads are waiting for their cache misses. (A few hours of your time would probably pay for a single very fast computer, but if you're trying to deploy it widely on cheap hardware it might make sense to consider the problem the way you're looking at it. Regardless, it's an interesting problem to consider.)
142,252
<p>This code works (C# 3)</p> <pre><code>double d; if(d == (double)(int)d) ...; </code></pre> <ol> <li>Is there a better way to do this?</li> <li>For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)</li> </ol> <p><em>Note:</em> Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.</p>
[ { "answer_id": 142262, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You don't need the extra (double) in there. This works:</p>\n\n<pre><code>if (d == (int)d) {\n //...\n}\n</code></pre>\n" }, { "answer_id": 142263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<pre><code>d == Math.Floor(d)\n</code></pre>\n\n<p>does the same thing in other words.</p>\n\n<p>NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.</p>\n" }, { "answer_id": 142272, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>Something like this</p>\n\n<pre><code>double d = 4.0;\nint i = 4;\n\nbool equal = d.CompareTo(i) == 0; // true\n</code></pre>\n" }, { "answer_id": 142274, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 2, "selected": false, "text": "<p>Use Math.Truncate()</p>\n" }, { "answer_id": 142287, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 3, "selected": false, "text": "<p>If your double is the result of another calculation, you probably want something like:</p>\n\n<pre><code>d == Math.Floor(d + 0.00001);\n</code></pre>\n\n<p>That way, if there's been a slight rounding error, it'll still match.</p>\n" }, { "answer_id": 142295, "author": "VoxPelli", "author_id": 20667, "author_profile": "https://Stackoverflow.com/users/20667", "pm_score": 3, "selected": false, "text": "<p>This would work I think:</p>\n\n<pre><code>if (d % 1 == 0) {\n //...\n}\n</code></pre>\n" }, { "answer_id": 142302, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 3, "selected": false, "text": "<p>I cannot answer the C#-specific part of the question, but I must point out you are probably missing a generic problem with floating point numbers.</p>\n\n<p>Generally, integerness is not well defined on floats. For the same reason that equality is not well defined on floats. Floating point calculations normally include both rounding and representation errors.</p>\n\n<p>For example, <code>1.1 + 0.6 != 1.7</code>.</p>\n\n<p>Yup, that's just the way floating point numbers work.</p>\n\n<p>Here, <code>1.1 + 0.6 - 1.7 == 2.2204460492503131e-16</code>.</p>\n\n<p>Strictly speaking, the closest thing to equality comparison you can do with floats is comparing them <em>up to a chosen precision</em>.</p>\n\n<p>If this is not sufficient, you must work with a decimal number representation, with a floating point number representation with built-in error range, or with symbolic computations.</p>\n" }, { "answer_id": 142309, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>If you are just going to convert it, Mike F / Khoth's answer is good, but doesn't quite answer your question. If you are going to actually test, and it's actually important, I recommend you implement something that includes a margin of error.</p>\n\n<p>For instance, if you are considering money and you want to test for even dollar amounts, you might say (following Khoth's pattern):</p>\n\n<pre><code>if( Math.abs(d - Math.Floor(d + 0.001)) &lt; 0.001)\n</code></pre>\n\n<p>In other words, take the absolute value of the difference of the value and it's integer representation and ensure that it's small.</p>\n" }, { "answer_id": 142412, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 1, "selected": false, "text": "<p>This will let you choose what precision you're looking for, plus or minus half a tick, to account for floating point drift. The comparison is integral also which is nice.</p>\n\n<pre><code>static void Main(string[] args)\n{\n const int precision = 10000;\n\n foreach (var d in new[] { 2, 2.9, 2.001, 1.999, 1.99999999, 2.00000001 })\n {\n if ((int) (d*precision + .5)%precision == 0)\n {\n Console.WriteLine(\"{0} is an int\", d);\n }\n }\n}\n</code></pre>\n\n<p>and the output is</p>\n\n<pre><code>2 is an int\n1.99999999 is an int\n2.00000001 is an int\n</code></pre>\n" }, { "answer_id": 598312, "author": "Crash893", "author_id": 72136, "author_profile": "https://Stackoverflow.com/users/72136", "pm_score": 0, "selected": false, "text": "<p>Could you use this</p>\n\n<pre><code> bool IsInt(double x)\n {\n try\n {\n int y = Int16.Parse(x.ToString());\n return true;\n }\n catch \n {\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 13444282, "author": "ccook", "author_id": 51275, "author_profile": "https://Stackoverflow.com/users/51275", "pm_score": 0, "selected": false, "text": "<p>To handle the precision of the double...</p>\n\n<pre><code>Math.Abs(d - Math.Floor(d)) &lt;= double.Epsilon\n</code></pre>\n\n<p>Consider the following case where a value <strong>less then double.Epsilon</strong> fails to compare as zero.</p>\n\n<pre><code>// number of possible rounds\nconst int rounds = 1;\n\n// precision causes rounding up to double.Epsilon\ndouble d = double.Epsilon*.75;\n\n// due to the rounding this comparison fails\nConsole.WriteLine(d == Math.Floor(d));\n\n// this comparison succeeds by accounting for the rounding\nConsole.WriteLine(Math.Abs(d - Math.Floor(d)) &lt;= rounds*double.Epsilon);\n\n// The difference is double.Epsilon, 4.940656458412465E-324\nConsole.WriteLine(Math.Abs(d - Math.Floor(d)).ToString(\"E15\"));\n</code></pre>\n" }, { "answer_id": 15013545, "author": "yonil", "author_id": 2097391, "author_profile": "https://Stackoverflow.com/users/2097391", "pm_score": 2, "selected": false, "text": "<p>A simple test such as 'x == floor(x)' is mathematically assured to work correctly, for any fixed-precision FP number.</p>\n\n<p>All legal fixed-precision FP encodings represent distinct real numbers, and so for every integer x, there is at most one fixed-precision FP encoding that matches it exactly. </p>\n\n<p>Therefore, for every integer x that CAN be represented in such way, we have x == floor(x) necessarily, since floor(x) by definition returns the largest FP number y such that y &lt;= x and y represents an integer; so floor(x) must return x.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
This code works (C# 3) ``` double d; if(d == (double)(int)d) ...; ``` 1. Is there a better way to do this? 2. For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good) *Note:* Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.
``` d == Math.Floor(d) ``` does the same thing in other words. NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.
142,317
<p>I have the following code that shows either a bug or a misunderstanding on my part.</p> <p>I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.</p> <p>Is this work as it should, or should I file a bug?</p> <pre> import java.io.*; import java.net.*; import java.util.*; public class OOS { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new Runnable() { public void run() { try { ServerSocket ss = new ServerSocket(12344); Socket s= ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); List same = new ArrayList(); same.add(0); oos.writeObject(same); same.clear(); same.add(1); oos.writeObject(same); } catch(Exception e) { e.printStackTrace(); } } }); t1.start(); Socket s = new Socket("localhost", 12344); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); // outputs [0] as expected System.out.println(ois.readObject()); // outputs [0], but expected [1] System.out.println(ois.readObject()); System.exit(0); } } </pre>
[ { "answer_id": 142367, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 6, "selected": true, "text": "<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).</p>\n\n<p>See the reset() method if you want to reset the graph.</p>\n" }, { "answer_id": 142704, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "<p>Max is correct, but you can also use:</p>\n\n<pre><code>public void writeUnshared(Object obj);\n</code></pre>\n\n<p>See comment below for caveat</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
I have the following code that shows either a bug or a misunderstanding on my part. I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow. Is this work as it should, or should I file a bug? ``` import java.io.*; import java.net.*; import java.util.*; public class OOS { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new Runnable() { public void run() { try { ServerSocket ss = new ServerSocket(12344); Socket s= ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); List same = new ArrayList(); same.add(0); oos.writeObject(same); same.clear(); same.add(1); oos.writeObject(same); } catch(Exception e) { e.printStackTrace(); } } }); t1.start(); Socket s = new Socket("localhost", 12344); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); // outputs [0] as expected System.out.println(ois.readObject()); // outputs [0], but expected [1] System.out.println(ois.readObject()); System.exit(0); } } ```
The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing). See the reset() method if you want to reset the graph.
142,319
<p>This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL?</p> <p>ADDED: Here's the program I'm using to test this. This file lives at <a href="http://kibotzer.com/sigs.php" rel="nofollow noreferrer">http://kibotzer.com/sigs.php</a>. The no-cache header idea, taken from here -- <a href="http://mapki.com/wiki/Dynamic_XML" rel="nofollow noreferrer">http://mapki.com/wiki/Dynamic_XML</a> -- seems to not help.</p> <pre><code>&lt;?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // HTTP/1.1 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.0 header("Pragma: no-cache"); //XML Header header("content-type:text/xml"); ?&gt; &lt;!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd"&gt; &lt;rss version="0.91"&gt; &lt;channel&gt; &lt;title&gt;Dynamic Signatures&lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;Blah blah&lt;/description&gt; &lt;language&gt;en-us&lt;/language&gt; &lt;pubDate&gt;26 Sep 2008 02:15:01 -0000&lt;/pubDate&gt; &lt;webMaster&gt;[email protected]&lt;/webMaster&gt; &lt;managingEditor&gt;[email protected] (Daniel Reeves)&lt;/managingEditor&gt; &lt;lastBuildDate&gt;26 Sep 2008 02:15:01 -0000&lt;/lastBuildDate&gt; &lt;image&gt; &lt;title&gt;Kibotzer Logo&lt;/title&gt; &lt;url&gt;http://kibotzer.com/logos/kibo-logo-1.gif&lt;/url&gt; &lt;link&gt;http://kibotzer.com/&lt;/link&gt; &lt;width&gt;120&lt;/width&gt; &lt;height&gt;60&lt;/height&gt; &lt;description&gt;Kibotzer&lt;/description&gt; &lt;/image&gt; &lt;item&gt; &lt;title&gt; Dynamic Signature 1 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;This is the description for Signature 1 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/description&gt; &lt;/item&gt; &lt;item&gt; &lt;title&gt; Dynamic Signature 2 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/title&gt; &lt;link&gt;http://kibotzer.com&lt;/link&gt; &lt;description&gt;This is the description for Signature 2 (&lt;?php echo gmdate("H:i:s"); ?&gt;) &lt;/description&gt; &lt;/item&gt; &lt;/channel&gt; &lt;/rss&gt; </code></pre> <pre> -- http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves" Latest probabilities from intrade... 42.1% McCain becomes president (last trade 18:07 FRI) 57.0% Obama becomes president (last trade 18:34 FRI) 17.6% US recession in 2008 (last trade 16:24 FRI) 16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI) </pre>
[ { "answer_id": 142367, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 6, "selected": true, "text": "<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).</p>\n\n<p>See the reset() method if you want to reset the graph.</p>\n" }, { "answer_id": 142704, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "<p>Max is correct, but you can also use:</p>\n\n<pre><code>public void writeUnshared(Object obj);\n</code></pre>\n\n<p>See comment below for caveat</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL? ADDED: Here's the program I'm using to test this. This file lives at <http://kibotzer.com/sigs.php>. The no-cache header idea, taken from here -- <http://mapki.com/wiki/Dynamic_XML> -- seems to not help. ``` <?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // HTTP/1.1 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); // HTTP/1.0 header("Pragma: no-cache"); //XML Header header("content-type:text/xml"); ?> <!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd"> <rss version="0.91"> <channel> <title>Dynamic Signatures</title> <link>http://kibotzer.com</link> <description>Blah blah</description> <language>en-us</language> <pubDate>26 Sep 2008 02:15:01 -0000</pubDate> <webMaster>[email protected]</webMaster> <managingEditor>[email protected] (Daniel Reeves)</managingEditor> <lastBuildDate>26 Sep 2008 02:15:01 -0000</lastBuildDate> <image> <title>Kibotzer Logo</title> <url>http://kibotzer.com/logos/kibo-logo-1.gif</url> <link>http://kibotzer.com/</link> <width>120</width> <height>60</height> <description>Kibotzer</description> </image> <item> <title> Dynamic Signature 1 (<?php echo gmdate("H:i:s"); ?>) </title> <link>http://kibotzer.com</link> <description>This is the description for Signature 1 (<?php echo gmdate("H:i:s"); ?>) </description> </item> <item> <title> Dynamic Signature 2 (<?php echo gmdate("H:i:s"); ?>) </title> <link>http://kibotzer.com</link> <description>This is the description for Signature 2 (<?php echo gmdate("H:i:s"); ?>) </description> </item> </channel> </rss> ``` ``` -- http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves" Latest probabilities from intrade... 42.1% McCain becomes president (last trade 18:07 FRI) 57.0% Obama becomes president (last trade 18:34 FRI) 17.6% US recession in 2008 (last trade 16:24 FRI) 16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI) ```
The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing). See the reset() method if you want to reset the graph.
142,320
<p>I'm setting up our new Dev server, what is the easiest way to assign multiple IP addresses to Windows 2008 Server Network Adapter?</p> <p>I'm setting up our development machine, running IIS 7 and want to have the range between 192.168.1.200 - .254 available when I'm setting up a new website in IIS 7.</p>
[ { "answer_id": 142347, "author": "David", "author_id": 3351, "author_profile": "https://Stackoverflow.com/users/3351", "pm_score": 0, "selected": false, "text": "<p>Network Connections -> Local Area Network Connection Properties -> TCP/IP Properties -> Advanced -> IP Settings -> Add Button.</p>\n" }, { "answer_id": 142411, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "<pre><code>&gt; netsh interface ipv4 add address \"Local Area Connection\" 192.168.1.201 255.255.255.0\n</code></pre>\n\n<p>Wrap in a cmd.exe \"for\" loop to add multiple IPs.</p>\n\n<p>EDIT: (from Brian) \"Local Area Connection\" above is a placeholder, make sure you use the actual network adapter name on your system.</p>\n" }, { "answer_id": 142477, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "<p>The complete CMD.EXE loop:</p>\n\n<pre><code>FOR /L %b IN (200,1,254) DO netsh interface ip add address \"your_adapter\" 192.168.1.%b 255.255.255.0\n</code></pre>\n\n<p>In the code above, replace \"your_adapter\" with the actual interface name (usually \"Local Area Connection\"). In addition, the netmask at the end is an assumption of /24 or Class C subnet; substitute the correct netmask.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
I'm setting up our new Dev server, what is the easiest way to assign multiple IP addresses to Windows 2008 Server Network Adapter? I'm setting up our development machine, running IIS 7 and want to have the range between 192.168.1.200 - .254 available when I'm setting up a new website in IIS 7.
The complete CMD.EXE loop: ``` FOR /L %b IN (200,1,254) DO netsh interface ip add address "your_adapter" 192.168.1.%b 255.255.255.0 ``` In the code above, replace "your\_adapter" with the actual interface name (usually "Local Area Connection"). In addition, the netmask at the end is an assumption of /24 or Class C subnet; substitute the correct netmask.
142,356
<p>What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?</p> <p>I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.</p> <pre><code>Type type = typeof(FooBar) BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; type.GetConstructors(flags) .Where(constructor =&gt; constructor.GetParameters().Length == 0) .First(); </code></pre>
[ { "answer_id": 142362, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "<pre><code>type.GetConstructor(Type.EmptyTypes)\n</code></pre>\n" }, { "answer_id": 142442, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 5, "selected": false, "text": "<p>If you actually <strong>need</strong> the ConstructorInfo object, then see <a href=\"https://stackoverflow.com/questions/142356/most-efficient-way-to-get-default-constructor-of-a-type#142362\">Curt Hagenlocher's answer</a>.</p>\n\n<p>On the other hand, if you're really just trying to create an object at run-time from a <code>System.Type</code>, see <a href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\" rel=\"noreferrer\"><code>System.Activator.CreateInstance</code></a> -- it's not just future-proofed (Activator handles more details than <code>ConstructorInfo.Invoke</code>), it's also <strong>much</strong> less ugly.</p>\n" }, { "answer_id": 142623, "author": "Mohamed Faramawi", "author_id": 20006, "author_profile": "https://Stackoverflow.com/users/20006", "pm_score": -1, "selected": false, "text": "<p>you would want to try FormatterServices.GetUninitializedObject(Type)\nthis one is better than Activator.CreateInstance </p>\n\n<p>However , this method doesn't call the object constructor , so if you are setting initial values there, this won't work\nCheck MSDN for this thing\n<a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx</a></p>\n\n<p>there is another way here\n<a href=\"http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx\" rel=\"nofollow noreferrer\">http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx</a></p>\n\n<p>however this one fails if the object have parametrize constructors</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 16045524, "author": "Jeff B", "author_id": 945456, "author_profile": "https://Stackoverflow.com/users/945456", "pm_score": 2, "selected": false, "text": "<p>If you only want to get the default constructor to instantiate the class, and are getting the type as a generic type parameter to a function, you can do the following:</p>\n\n<pre><code>T NewItUp&lt;T&gt;() where T : new()\n{\n return new T();\n}\n</code></pre>\n" }, { "answer_id": 17552973, "author": "DaFlame", "author_id": 1112470, "author_profile": "https://Stackoverflow.com/users/1112470", "pm_score": 2, "selected": false, "text": "<p>If you have the generic type parameter, then Jeff Bridgman's answer is the best one.\nIf you only have a Type object representing the type you want to construct, you could use <code>Activator.CreateInstance(Type)</code> like Alex Lyman suggested, but I have been told it is slow (I haven't profiled it personally though).</p>\n\n<p>However, if you find yourself constructing these objects very frequently, there is a more eloquent approach using dynamically compiled Linq Expressions:</p>\n\n<pre><code>using System;\nusing System.Linq.Expressions;\n\npublic static class TypeHelper\n{\n public static Func&lt;object&gt; CreateDefaultConstructor(Type type)\n {\n NewExpression newExp = Expression.New(type);\n\n // Create a new lambda expression with the NewExpression as the body.\n var lambda = Expression.Lambda&lt;Func&lt;object&gt;&gt;(newExp);\n\n // Compile our new lambda expression.\n return lambda.Compile();\n }\n}\n</code></pre>\n\n<p>Just call the delegate returned to you. You should cache this delegate, because constantly recompiling Linq expressions can be expensive, but if you cache the delegate and reuse it each time, it can be very fast! I personally use a static lookup dictionary indexed by type. This function comes in handy when you are dealing with serialized objects where you may only know the Type information.</p>\n\n<blockquote>\n <p><strong>NOTE: This can fail if the type is not constructable or does not have a default constructor!</strong></p>\n</blockquote>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12784/" ]
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type? I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it. ``` Type type = typeof(FooBar) BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; type.GetConstructors(flags) .Where(constructor => constructor.GetParameters().Length == 0) .First(); ```
``` type.GetConstructor(Type.EmptyTypes) ```
142,357
<p>What are the best JVM settings you have found for running Eclipse?</p>
[ { "answer_id": 142384, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 0, "selected": false, "text": "<p>Here's what I use (though I have them in the shortcut instead of the settings file):</p>\n\n<p>eclipse.exe -showlocation -vm \"C:\\Java\\jdk1.6.0_07\\bin\\javaw.exe\" -vmargs -Xms256M -Xmx768M -XX:+UseParallelGC -XX:MaxPermSize=128M</p>\n" }, { "answer_id": 142580, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 2, "selected": false, "text": "<p>Eclipse likes lots of RAM. Use at least -Xmx512M. More if available.</p>\n" }, { "answer_id": 142593, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 1, "selected": false, "text": "<p>-vm<br>\nC:\\Program Files\\Java\\jdk1.6.0_07\\jre\\bin\\client\\jvm.dll</p>\n\n<p>To specify which java version you are using, and use the dll instead of launching a javaw process</p>\n" }, { "answer_id": 142596, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 4, "selected": false, "text": "<p>-showlocation</p>\n\n<p>To make it easier to have eclipse running twice, and know which workspace you're dealing with</p>\n\n<p>Eclipse 3.6 adds a preferences option to specify what to show for the <code>Workspace name (shown in window title)</code> which works much better than <code>-showlocation</code> for three reasons:</p>\n\n<ol>\n<li>You do not need to restart eclipse for it to take affect.</li>\n<li>You can chose a short code.</li>\n<li>It appears first, before the perspective and application name.</li>\n</ol>\n" }, { "answer_id": 144349, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "<h1>Eclipse Ganymede 3.4.2 settings</h1>\n\n<hr>\n\n<p>For more recent settings, see <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/1409590#1409590\"><strong>Eclipse Galileo 3.5 settings above</strong></a>. </p>\n\n<hr>\n\n<h2>JDK</h2>\n\n<p>The best JVM setting <strong>always</strong>, in my opinion, includes the <strong>latest JDK you can find</strong> (so for now, jdk1.6.0_b07 up to b16, <a href=\"https://stackoverflow.com/questions/1027002/eclipse-swing-app-breakpoint-hit-only-after-an-uncaught-exception-is-thrown\">except b14 and b15</a>)</p>\n\n<h2>eclipse.ini</h2>\n\n<p>Even with those pretty low memory settings, I can run large java projects (along with a web server) on my old (2002) desktop with 2Go RAM.</p>\n\n<pre><code>-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256M\n-framework\nplugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar\n-vm\njdk1.6.0_10\\jre\\bin\\client\\jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms128m\n-Xmx384m\n-Xss2m\n-XX:PermSize=128m\n-XX:MaxPermSize=128m\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n-XX:CompileThreshold=5\n-Dcom.sun.management.jmxremote\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/94331/eclipse-memory-use#101995\">GKelly's SO answer</a> and <a href=\"http://piotrga.wordpress.com/2006/12/12/intellij-and-garbage-collection/\" rel=\"nofollow noreferrer\">Piotr Gabryanczyk's blog entry</a> for more details about the new options.</p>\n\n<h2>Monitoring</h2>\n\n<p>You can also consider launching:</p>\n\n<pre><code>C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n</code></pre>\n\n<p>As said in a <a href=\"https://stackoverflow.com/questions/100161/is-eclipse-34-ganymede-memory-usage-significantly-higher-than-32#101164\">previous question about memory consumption</a>.</p>\n" }, { "answer_id": 366121, "author": "Gilberto Olimpio", "author_id": 45869, "author_profile": "https://Stackoverflow.com/users/45869", "pm_score": 3, "selected": false, "text": "<p>If you are using Linux + Sun JDK/JRE <strong>32bits</strong>, change the \"-vm\" to:</p>\n\n<pre><code>-vm \n[your_jdk_folder]/jre/lib/i386/client/libjvm.so\n</code></pre>\n\n<p>If you are using Linux + Sun JDK/JRE <strong>64bits</strong>, change the \"-vm\" to:</p>\n\n<pre><code>-vm\n[your_jdk_folder]/jre/lib/amd64/server/libjvm.so\n</code></pre>\n\n<p>That's working fine for me on Ubuntu 8.10 and 9.04</p>\n" }, { "answer_id": 1094506, "author": "Ben W.", "author_id": 134412, "author_profile": "https://Stackoverflow.com/users/134412", "pm_score": 3, "selected": false, "text": "<p>If you're going with jdk6 update 14, I'd suggest using using the G1 garbage collector which seems to help performance.</p>\n\n<p>To do so, remove these settings:</p>\n\n<p>-XX:+UseConcMarkSweepGC<br/>\n-XX:+CMSIncrementalMode<br/>\n-XX:+CMSIncrementalPacing<br/></p>\n\n<p>and replace them with these:</p>\n\n<p>-XX:+UnlockExperimentalVMOptions<br/>\n-XX:+UseG1GC</p>\n" }, { "answer_id": 1409590, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": false, "text": "<h1>Eclipse Galileo 3.5 and 3.5.1 settings</h1>\n\n<p>Currently (November 2009), I am testing with jdk6 update 17 the following configuration set of options (with Galileo -- eclipse 3.5.x, see <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349\">below for 3.4</a> or <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/3275659#3275659\">above for <strong>Helios 3.6.x</strong></a>):<br>\n(of course, adapt the relative paths present in this eclipse.ini to the correct paths for your setup)</p>\n\n<p>Note: for <strong>eclipse3.5</strong>, replace <code>startup</code> and <code>launcher.library</code> lines by:</p>\n\n<pre><code>-startup\nplugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519\n</code></pre>\n\n<h2>eclipse.ini 3.5.1</h2>\n\n<pre><code>-data\n../../workspace\n-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n384m\n-startup\nplugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519\n-vm\n../../../../program files/Java/jdk1.6.0_17/jre/bin/client/jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms128m\n-Xmx384m\n-Xss4m\n-XX:PermSize=128m\n-XX:MaxPermSize=384m\n-XX:CompileThreshold=5\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n-Dcom.sun.management.jmxremote\n-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins\n</code></pre>\n\n<p>See also my <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349\">original answer above</a> for more information.</p>\n\n<h2>Changes (from July 2009)</h2>\n\n<ul>\n<li>refers to the launcher and not the framework</li>\n<li>shared plugins: <code>org.eclipse.equinox.p2.reconciler.dropins.directory</code> option.</li>\n<li>Galileo supports fully relative paths for workspace or VM (avoid having to modify those from one eclipse installation to another, if, of course, your JVM and workspace stay the same)<br>\nBefore, those relative paths kept being rewritten into absolute ones when eclipse launched itself...</li>\n<li>You also can copy the JRE directory of a Java JDK installation inside your eclipse directory</li>\n</ul>\n\n<h2>Caveats</h2>\n\n<p>There was a bug with <a href=\"https://stackoverflow.com/questions/1027002/eclipse-swing-app-breakpoint-hit-only-after-an-uncaught-exception-is-thrown\"><strong>ignored breakpoints</strong></a> actually related to the JDK.<br>\nDo use JDK6u16 or more recent for <em>launching</em> eclipse (You can then define as many JDKs you want to compile <em>within</em> eclipse: it is not because you launch an eclipse with JDK6 that you will have to compile with that same JDK).</p>\n\n<h2>Max</h2>\n\n<p>Note the usage of:</p>\n\n<pre><code>--launcher.XXMaxPermSize\n384m\n-vmargs\n-XX:MaxPermSize=128m\n</code></pre>\n\n<p>As documented in the <a href=\"http://wiki.eclipse.org/FAQ_How_do_I_increase_the_permgen_size_available_to_Eclipse%3F\" rel=\"nofollow noreferrer\">Eclipse Wiki</a>, </p>\n\n<blockquote>\n <p>Eclipse 3.3 supports a new argument to the launcher: <code>--launcher.XXMaxPermSize</code>.<br>\n If the VM being used is a Sun VM and there is not already a <code>-XX:MaxPermSize=</code> VM argument, then the launcher will automatically add <code>-XX:MaxPermSize=256m</code> to the list of VM arguments being used.<br>\n The 3.3 launcher is only capable of identifying Sun VMs on Windows.</p>\n</blockquote>\n\n<p>As detailed in <a href=\"http://dev.eclipse.org/newslists/news.eclipse.platform/msg69006.html\" rel=\"nofollow noreferrer\">this entry</a>:</p>\n\n<blockquote>\n <p>Not all vms accept the <code>-XX:MaxPermSize</code> argument which is why it is passed in this manner. There may (or may not) exist problems with identifying sun vms.<br>\n Note: Eclipse 3.3.1 has <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=203325\" rel=\"nofollow noreferrer\">a bug</a> where the launcher cannot detect a Sun VM, and therefore does not use the correct PermGen size. It seems this may have been <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=195897\" rel=\"nofollow noreferrer\">a known bug on Mac OS X for 3.3.0</a> as well.<br>\n <strong>If you are using either of these platform combination, add the <code>-XX</code> flag to the <code>eclipse.ini</code> as described above.</strong></p>\n \n <p>Notes:</p>\n \n <ul>\n <li>the \"<code>384m</code>\" line translates to the \"<code>=384m</code>\" part of the VM argument, if the VM is case sensitive on the \"<code>m</code>\", then the so is this argument. </li>\n <li>the \"<code>--launcher.</code>\" prefix, this specifies that the argument is consumed by the launcher itself and was added to launcher specific arguments to avoid name collisions with application arguments. (Other examples are <code>--launcher.library</code>, <code>--launcher.suppressErrors</code>)</li>\n </ul>\n \n <p>The <code>-vmargs -XX:MaxPermSize=384m</code> part is the argument passed directly to the VM, bypassing the launcher entirely and no check on the VM vendor is used.</p>\n</blockquote>\n" }, { "answer_id": 1529430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>XX:+UseParallelGC that's the most awesome option ever!!!</p>\n" }, { "answer_id": 1838017, "author": "Kire Haglin", "author_id": 2049208, "author_profile": "https://Stackoverflow.com/users/2049208", "pm_score": 3, "selected": false, "text": "<p>You can also try running with <a href=\"http://www.oracle.com/technology/software/products/jrockit/index.html\" rel=\"noreferrer\">JRockit</a>. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it. </p>\n\n<p>It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI. </p>\n\n<pre><code>-showsplash\norg.eclipse.platform\n-vm\n C:\\jrmc-3.1.2-1.6.0\\bin\\javaw.exe \n-vmargs\n-XgcPrio:deterministic\n-XpauseTarget:20\n</code></pre>\n\n<p>I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this <a href=\"http://www.oracle.com/technology/software/products/jrockit/missioncontrol/updates/eclipse-3.3/jrmc/index.html\" rel=\"noreferrer\">update site</a>. Note, only works for Eclipse 3.3 and Eclipse 3.4</p>\n" }, { "answer_id": 3275659, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 9, "selected": true, "text": "<p><sub>It is that time of year again: \"eclipse.ini take 3\" the settings strike back!</sub> </p>\n\n<h1>Eclipse Helios 3.6 and 3.6.x settings</h1>\n\n<p><a href=\"http://www.eclipse.org/home/promotions/friends-helios/helios.png\" rel=\"nofollow noreferrer\">alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png</a></p>\n\n<p>After settings for <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349\">Eclipse Ganymede 3.4.x</a> and <a href=\"https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/1409590#1409590\">Eclipse Galileo 3.5.x</a>, here is an in-depth look at an \"optimized\" <strong><a href=\"http://wiki.eclipse.org/Eclipse.ini\" rel=\"nofollow noreferrer\">eclipse.ini</a></strong> settings file for Eclipse Helios 3.6.x:</p>\n\n<ul>\n<li>based on <strong><a href=\"http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html\" rel=\"nofollow noreferrer\">runtime options</a></strong>, </li>\n<li>and using the <strong>Sun-Oracle JVM 1.6u21 b7</strong>, <a href=\"http://java.about.com/b/2010/07/27/java-6-update-21-build-07-released.htm\" rel=\"nofollow noreferrer\">released July, 27th</a> (<del>some some Sun proprietary options may be involved</del>).</li>\n</ul>\n\n<p>(<sup>by \"optimized\", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7</sup>)</p>\n\n<h2>Eclipse.ini</h2> \n\n<p><img src=\"https://www.eclipse.org/downloads/images/classic2.jpg\" alt=\"alt text\"></p>\n\n<p><strong>WARNING</strong>: for non-windows platform, use the Sun proprietary option <code>-XX:MaxPermSize</code> instead of the Eclipse proprietary option <code>--launcher.XXMaxPermSize</code>.<br>\nThat is: <strong>Unless</strong> you are using the latest <strong>jdk6u21 build 7</strong>. \nSee the Oracle section below.</p>\n\n<pre><code>-data\n../../workspace\n-showlocation\n-showsplash\norg.eclipse.platform\n--launcher.defaultAction\nopenFile\n-vm\nC:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll\n-vmargs\n-Dosgi.requiredJavaVersion=1.6\n-Declipse.p2.unsignedPolicy=allow\n-Xms128m\n-Xmx384m\n-Xss4m\n-XX:PermSize=128m\n-XX:MaxPermSize=384m\n-XX:CompileThreshold=5\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+CMSIncrementalPacing\n-XX:+UnlockExperimentalVMOptions\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n-Dcom.sun.management.jmxremote\n-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons\n</code></pre>\n\n<p>Note:<br>\nAdapt the <code>p2.reconciler.dropins.directory</code> to an external directory of your choice.<br>\nSee this <a href=\"https://stackoverflow.com/questions/2763843/eclipse-plugins-vs-features-vs-dropins/2763891#2763891\">SO answer</a>.\nThe idea is to be able to drop new plugins in a directory independently from any Eclipse installation.</p>\n\n<p>The following sections detail what are in this <code>eclipse.ini</code> file. </p>\n\n<hr>\n\n<h2>The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes</h2>\n\n<p><a href=\"https://stackoverflow.com/users/84728/andrew-niefer\">Andrew Niefer</a> did alert me to this situation, and wrote a <a href=\"http://aniefer.blogspot.com/2010/07/permgen-problems-and-running-eclipse-on.html\" rel=\"nofollow noreferrer\">blog post</a>, about a non-standard vm argument (<strong><code>-XX:MaxPermSize</code></strong>) and can cause vms from other vendors to not start at all.<br>\nBut the eclipse version of that option (<strong><code>--launcher.XXMaxPermSize</code></strong>) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below).</p>\n\n<p>The <del>final</del> solution is on the <a href=\"http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Oracle.2FSun_VM_1.6.0_21_on_Windows\" rel=\"nofollow noreferrer\">Eclipse Wiki</a>, and <strong>for Helios on Windows with 6u21 pre build 7</strong> only:</p>\n\n<ul>\n<li><strong>downloading the fixed <a href=\"https://bugs.eclipse.org/bugs/attachment.cgi?id=174343\" rel=\"nofollow noreferrer\">eclipse_1308.dll</a></strong> (July 16th, 2010)</li>\n<li>and place it into</li>\n</ul>\n\n<pre>\n(eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503\n</pre>\n\n<p>That's it. No setting to tweak here (again, only for Helios <strong>on Windows</strong> with a <strong>6u21 pre build 7</strong>).<br>\nFor non-Windows platform, you need to revert to the Sun proprietary option <code>-XX:MaxPermSize</code>.</p>\n\n<p>The issue is based one a regression: <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6969236\" rel=\"nofollow noreferrer\">JVM identification fails due to Oracle rebranding in java.exe</a>, and triggered <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514\" rel=\"nofollow noreferrer\">bug 319514</a> on Eclipse.<br>\nAndrew took care of <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=320005\" rel=\"nofollow noreferrer\"> Bug 320005 - [launcher] <code>--launcher.XXMaxPermSize: isSunVM</code> should return true for Oracle</a>, but that will be only for Helios 3.6.1.<br>\n<a href=\"http://dev.eclipse.org/blogs/francis/about/\" rel=\"nofollow noreferrer\">Francis Upton</a>, another Eclipse committer, <a href=\"http://dev.eclipse.org/blogs/francis/2010/07/15/some-thoughts-on-the-java-u21-problem/\" rel=\"nofollow noreferrer\">reflects on the all situation</a>.</p>\n\n<p><strong>Update u21b7, July, 27th</strong>:<br>\n<strong>Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7</strong>.<br>\nIf you use <strong><a href=\"http://www.oracle.com/technetwork/java/javase/downloads/index.html\" rel=\"nofollow noreferrer\">jdk6u21 build 7</a></strong>, you can revert to the <strong><code>--launcher.XXMaxPermSize</code></strong> (eclipse option) instead of <strong><code>-XX:MaxPermSize</code></strong> (the non-standard option).<br>\nThe <a href=\"http://www.infoq.com/news/2010/07/eclipse-java-6u21\" rel=\"nofollow noreferrer\">auto-detection happening in the C launcher shim <code>eclipse.exe</code></a> will still look for the \"<code>Sun Microsystems</code>\" string, but with 6u21b7, it will now work - again.</p>\n\n<p>For now, I still keep the <code>-XX:MaxPermSize</code> version (because I have no idea when everybody will launch eclipse the <em>right</em> JDK).</p>\n\n<hr>\n\n<h2>Implicit `-startup` and `--launcher.library`</h2>\n\n<p>Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases:</p>\n\n<ul>\n<li>startup: If not specified, the executable will look in the plugins directory for the <code>org.eclipse.equinox.launcher</code> bundle with the highest version.</li>\n<li>launcher.library: If not specified, the executable looks in the <code>plugins</code> directory for the appropriate <code>org.eclipse.equinox.launcher.[platform]</code> fragment with the highest version and uses the shared library named <code>eclipse_*</code> inside.</li>\n</ul>\n\n<hr>\n\n<h2>Use JDK6</h2>\n\n<p>The JDK6 is now explicitly required to launch Eclipse:</p>\n\n<pre><code>-Dosgi.requiredJavaVersion = 1.6\n</code></pre>\n\n<p>This <a href=\"https://stackoverflow.com/questions/2787055/using-the-android-sdk-on-a-mac-eclipse-is-really-slow-how-can-i-speed-it-up\">SO question</a> reports a positive incidence for development on Mac OS.</p>\n\n<hr>\n\n<h2>+UnlockExperimentalVMOptions</h2>\n\n<p>The following options are part of some of the experimental options of the Sun JVM.</p>\n\n<pre><code>-XX:+UnlockExperimentalVMOptions\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n</code></pre>\n\n<p>They have been reported in this <a href=\"http://ugosan.org/speeding-up-eclipse-a-bit-with-unlockexperimentalvmoptions/\" rel=\"nofollow noreferrer\">blog post</a> to potentially speed up Eclipse.<br>\nSee all the <a href=\"http://blogs.oracle.com/watt/resource/jvm-options-list.html\" rel=\"nofollow noreferrer\">JVM options here</a> and also in the official <a href=\"http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp\" rel=\"nofollow noreferrer\">Java Hotspot options page</a>.<br>\nNote: the <a href=\"http://www.md.pp.ru/~eu/jdk6options.html\" rel=\"nofollow noreferrer\">detailed list of those options</a> reports that <code>UseFastAccessorMethods</code> might be active by default. </p>\n\n<p>See also <a href=\"http://translate.googleusercontent.com/translate_c?hl=en&amp;sl=fr&amp;tl=en&amp;u=http://blog.xebia.fr/2010/07/13/revue-de-presse-xebia-167/&amp;rurl=translate.google.com&amp;twu=1&amp;usg=ALkJrhgLW58oZuCouEaFZBTA_u6ZTQwvGA#MettezjourvotreJVM\" rel=\"nofollow noreferrer\">\"Update your JVM\"</a>:</p>\n\n<blockquote>\n <p>As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17.</p>\n</blockquote>\n\n<hr>\n\n<h2>Opening files in Eclipse from the command line</h2>\n\n<p>See the <a href=\"http://aniefer.blogspot.com/2010/05/opening-files-in-eclipse-from-command.html\" rel=\"nofollow noreferrer\">blog post</a> from Andrew Niefer reporting this new option:</p>\n\n<pre><code>--launcher.defaultAction\nopenFile\n</code></pre>\n\n<blockquote>\n <p>This tells the launcher that if it is called with a command line that only contains arguments that don't start with \"<code>-</code>\", then those arguments should be treated as if they followed \"<code>--launcher.openFile</code>\".</p>\n</blockquote>\n\n<pre><code>eclipse myFile.txt\n</code></pre>\n\n<blockquote>\n <p>This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose \"<code>Open With</code>\" or \"<code>Send To</code>\" Eclipse.</p>\n \n <p><a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=300532\" rel=\"nofollow noreferrer\">Relative paths</a> will be resolved first against the current working directory, and second against the eclipse program directory.</p>\n</blockquote>\n\n<p>See <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=301033\" rel=\"nofollow noreferrer\">bug 301033</a> for reference. Originally <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=4922\" rel=\"nofollow noreferrer\">bug 4922</a> (October 2001, fixed 9 years later).</p>\n\n<hr>\n\n<h2>p2 and the Unsigned Dialog Prompt</h2>\n\n<p>If you are tired of this dialog box during the installation of your many plugins:</p>\n\n<p><img src=\"https://aniszczyk.org/wp-content/uploads/2010/05/unsigneddialog.png\" alt=\"alt text\"></p>\n\n<p>, add in your <code>eclipse.ini</code>:</p>\n\n<pre><code>-Declipse.p2.unsignedPolicy=allow\n</code></pre>\n\n<p>See this <a href=\"http://aniszczyk.org/2010/05/20/p2-and-the-unsigned-dialog-prompt/\" rel=\"nofollow noreferrer\">blog post</a> from <a href=\"http://aniszczyk.org/about/\" rel=\"nofollow noreferrer\">Chris Aniszczy</a>, and the <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=235526\" rel=\"nofollow noreferrer\">bug report 235526</a>. </p>\n\n<blockquote>\n <p>I do want to say that security research supports the fact that less prompts are better.<br>\n People ignore things that pop up in the flow of something they want to get done.</p>\n \n <p>For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them.<br>\n Instead, we should collect all the problems, do <em>not</em> install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called <strong><a href=\"http://www.eecs.berkeley.edu/~tygar/papers/Safe_staging_for_computer_security.pdf\" rel=\"nofollow noreferrer\">'safe staging'</a></strong>.</p>\n</blockquote>\n\n<p><a href=\"http://www.eclipse.org/home/categories/images/wiki.gif\" rel=\"nofollow noreferrer\">---------- http://www.eclipse.org/home/categories/images/wiki.gif</a> <a href=\"http://www.eclipse.org/home/categories/images/wiki.gif\" rel=\"nofollow noreferrer\">alt text http://www.eclipse.org/home/categories/images/wiki.gif</a> <a href=\"http://www.eclipse.org/home/categories/images/wiki.gif\" rel=\"nofollow noreferrer\">alt text http://www.eclipse.org/home/categories/images/wiki.gif</a></p>\n\n<h2> Additional options</h2>\n\n<p>Those options are not directly in the <code>eclipse.ini</code> above, but can come in handy if needed.</p>\n\n<hr>\n\n<h3>The `user.home` issue on Windows7</h3>\n\n<p>When eclipse starts, it will read its keystore file (where passwords are kept), a file located in <code>user.home</code>.<br>\nIf for some reason that <code>user.home</code> doesn't resolve itself properly to a full-fledge path, Eclipse won't start.<br>\nInitially raised in <a href=\"https://stackoverflow.com/questions/2120160/eclipse-is-not-starting-on-windows-7/2120198#2120198\">this SO question</a>, if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start)</p>\n\n<p>Add in your <code>eclipse.ini</code>:</p>\n\n<pre><code>-eclipse.keyring \nC:\\eclipse\\keyring.txt\n</code></pre>\n\n<p>This has been tracked by <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=300577\" rel=\"nofollow noreferrer\">bug 300577</a>, it has been solve in this <a href=\"https://stackoverflow.com/questions/2134338/java-user-home-is-being-set-to-userprofile-and-not-being-resolved\">other SO question</a>.</p>\n\n<hr>\n\n<h3>Debug mode</h3>\n\n<p>Wait, there's more than one setting file in Eclipse.<br>\nif you add to your <code>eclipse.ini</code> the option:</p>\n\n<pre><code>-debug\n</code></pre>\n\n<p>, you enable the <a href=\"http://www.eclipse.org/eclipse/platform-core/documents/3.1/debug.html\" rel=\"nofollow noreferrer\">debug mode</a> and Eclipse will look for <em>another</em> setting file: a <code>.options</code> file where you can specify some OSGI options.<br>\nAnd that is great when you are adding new plugins through the dropins folder.<br>\nAdd in your .options file the following settings, as described in this <a href=\"http://eclipser-blog.blogspot.com/2010/01/dropins-diagnosis.html\" rel=\"nofollow noreferrer\">blog post \"<strong>Dropins diagnosis</strong>\"</a>:</p>\n\n<pre><code>org.eclipse.equinox.p2.core/debug=true\norg.eclipse.equinox.p2.core/reconciler=true\n</code></pre>\n\n<blockquote>\n <p>P2 will inform you what bundles were found in <code>dropins/</code> folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start:</p>\n \n <ul>\n <li>was your bundle in the plan? </li>\n <li>Was it installation problem (P2 fault) </li>\n <li>or maybe it is just not optimal to include your feature?</li>\n </ul>\n</blockquote>\n\n<p>That comes from <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=264924\" rel=\"nofollow noreferrer\">Bug 264924 - [reconciler] No diagnosis of dropins problems</a>, which finally solves the following issue like:</p>\n\n<pre><code>Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse\nUnzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5\n</code></pre>\n\n<blockquote>\n <p>This is a problematic configuration since OCL depends on EMF which is missing.<br>\n 3.5M5 provides no diagnosis of this problem.</p>\n \n <p>Start eclipse.<br>\n No obvious problems. Nothing in Error Log.</p>\n \n <ul>\n <li><code>Help / About / Plugin</code> details shows <code>org.eclipse.ocl.doc</code>, but not <code>org.eclipse.ocl</code>.</li>\n <li><code>Help / About / Configuration</code> details has no (diagnostic) mention of\n <code>org.eclipse.ocl</code>.</li>\n <li><code>Help / Installation / Information Installed Software</code> has no mention of <code>org.eclipse.ocl</code>.</li>\n </ul>\n \n <p>Where are the nice error markers?</p>\n</blockquote>\n\n<hr>\n\n<h3>Manifest Classpath</h3>\n\n<p>See this <a href=\"http://lt-rider.blogspot.com/2010/05/jdt-manifest-classpath-classpath.html\" rel=\"nofollow noreferrer\">blog post</a>:</p>\n\n<blockquote>\n <ul>\n <li>In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party. </li>\n <li>In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution. </li>\n </ul>\n</blockquote>\n\n<p>That means some of your projects might no longer compile in Helios.<br>\nIf you want to revert to Galileo behavior, add:</p>\n\n<pre><code>-DresolveReferencedLibrariesForContainers=true\n</code></pre>\n\n<p>See <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037\" rel=\"nofollow noreferrer\">bug 305037</a>, <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=313965\" rel=\"nofollow noreferrer\">bug 313965</a> and <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=313890\" rel=\"nofollow noreferrer\">bug 313890</a> for references.</p>\n\n<hr>\n\n<h3>IPV4 stack</h3>\n\n<p>This <a href=\"https://stackoverflow.com/questions/1500646/eclipse-3-5-unable-to-install-plugins\">SO question</a> mentions a potential fix when not accessing to plugin update sites:</p>\n\n<pre><code>-Djava.net.preferIPv4Stack=true\n</code></pre>\n\n<p>Mentioned here just in case it could help in your configuration.</p>\n\n<hr>\n\n<h3>JVM1.7x64 potential optimizations</h3>\n\n<p><a href=\"http://nerds-central.blogspot.com/2009/09/tuning-jvm-for-unusual-uses-have-some.html\" rel=\"nofollow noreferrer\">This article</a> reports:</p>\n\n<blockquote>\n <p>For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are: </p>\n</blockquote>\n\n<pre><code>-Xincgc \n-XX:-DontCompileHugeMethods \n-XX:MaxInlineSize=1024 \n-XX:FreqInlineSize=1024 \n</code></pre>\n\n<blockquote>\n <p>But I am still working on it... </p>\n</blockquote>\n" }, { "answer_id": 3276567, "author": "Chris Dennett", "author_id": 87197, "author_profile": "https://Stackoverflow.com/users/87197", "pm_score": 2, "selected": false, "text": "<p>My own settings (Java 1.7, modify for 1.6):</p>\n\n<pre><code>-vm\nC:/Program Files (x86)/Java/jdk1.7.0/bin\n-startup\nplugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20100628\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-server\n-Dosgi.requiredJavaVersion=1.7\n-Xmn100m\n-Xss1m\n-XgcPrio:deterministic\n-XpauseTarget:20\n-XX:PermSize=400M\n-XX:MaxPermSize=500M\n-XX:CompileThreshold=10\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UnlockExperimentalVMOptions\n-XX:+DoEscapeAnalysis\n-XX:+UseG1GC\n-XX:+UseFastAccessorMethods\n-XX:+AggressiveOpts\n-Xms512m\n-Xmx512m\n</code></pre>\n" }, { "answer_id": 3354939, "author": "Paul Gregoire", "author_id": 127938, "author_profile": "https://Stackoverflow.com/users/127938", "pm_score": 2, "selected": false, "text": "<p>If youre like me and had problems with the current Oracle release of 1.6 then you might want to update your JDK or set <pre>-XX:MaxPermSize</pre>. More information is available here: <a href=\"http://java.dzone.com/articles/latest-java-update-fixes\" rel=\"nofollow noreferrer\">http://java.dzone.com/articles/latest-java-update-fixes</a></p>\n" }, { "answer_id": 7523852, "author": "CurlyBrackets", "author_id": 559686, "author_profile": "https://Stackoverflow.com/users/559686", "pm_score": 3, "selected": false, "text": "<p>Here's my own setting for my Eclipse running on i7 2630M 16GB RAM laptop, this setting has been using for a week, without a single crashing, and Eclipse 3.7 is running smoothly.</p>\n\n<pre><code>-startup\nplugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar\n--launcher.library\nplugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502\n-product\norg.eclipse.epp.package.jee.product\n--launcher.defaultAction\nopenFile\n--launcher.XXMaxPermSize\n256M\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-Dosgi.requiredJavaVersion=1.5\n-Xms1024m\n-Xmx4096m \n-XX:MaxPermSize=256m\n</code></pre>\n\n<p>Calculations:\nFor Win 7 x64</p>\n\n<ul>\n<li>Xms = Physical Memory / 16 </li>\n<li>Xmx = Physical Memory / 4 </li>\n<li>MaxPermSize = Same as default value, which is 256m</li>\n</ul>\n" }, { "answer_id": 7776565, "author": "A Null Pointer", "author_id": 371396, "author_profile": "https://Stackoverflow.com/users/371396", "pm_score": 3, "selected": false, "text": "<pre><code>-startup\n../../../plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar\n--launcher.library\n../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx_1.1.100.v20110502\n-showsplash\norg.eclipse.platform\n--launcher.XXMaxPermSize\n256m\n--launcher.defaultAction\nopenFile\n-vmargs\n-Xms128m\n-Xmx512m\n-XX:MaxPermSize=256m\n-Xdock:icon=../Resources/Eclipse.icns\n-XstartOnFirstThread\n-Dorg.eclipse.swt.internal.carbon.smallFonts\n-Dcom.sun.management.jmxremote\n-Declipse.p2.unsignedPolicy=allow\n</code></pre>\n\n<p>And these setting have worked like a charm for me. I am running OS X10.6 , Eclipse 3.7 Indigo , JDK1.6.0_24</p>\n" }, { "answer_id": 7822155, "author": "Mikko Rantalainen", "author_id": 334451, "author_profile": "https://Stackoverflow.com/users/334451", "pm_score": 4, "selected": false, "text": "<h1>Eclipse Indigo 3.7.2 settings (64 bit linux)</h1>\n\n<p>Settings for <strong>Sun/Oracle java</strong> version \"1.6.0_31\" and <strong>Eclipse 3.7</strong> running on x86-64 Linux:</p>\n\n<pre><code>-nosplash\n-vmargs\n-Xincgc\n-Xss500k\n-Dosgi.requiredJavaVersion=1.6\n-Xms64m\n-Xmx200m\n-XX:NewSize=8m\n-XX:PermSize=80m\n-XX:MaxPermSize=150m\n-XX:MaxPermHeapExpansion=10m\n-XX:+UseConcMarkSweepGC\n-XX:CMSInitiatingOccupancyFraction=70\n-XX:+UseCMSInitiatingOccupancyOnly\n-XX:+UseParNewGC\n-XX:+CMSConcurrentMTEnabled\n-XX:ConcGCThreads=2\n-XX:ParallelGCThreads=2\n-XX:+CMSIncrementalPacing\n-XX:CMSIncrementalDutyCycleMin=0\n-XX:CMSIncrementalDutyCycle=5\n-XX:GCTimeRatio=49\n-XX:MaxGCPauseMillis=20\n-XX:GCPauseIntervalMillis=1000\n-XX:+UseCMSCompactAtFullCollection\n-XX:+CMSClassUnloadingEnabled\n-XX:+DoEscapeAnalysis\n-XX:+UseCompressedOops\n-XX:+AggressiveOpts\n-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses\n</code></pre>\n\n<p>Note that this uses only 200 MB for the heap and 150 MB for the non-heap. If you're using\nhuge plugins, you might want to increase both the \"-Xmx200m\" and \"-XX:MaxPermSize=150m\" limits.</p>\n\n<p>The primary optimization target for these flags has been to <strong>minimize latency in all cases</strong> and as a secondary optimization target minimize the memory usage.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ]
What are the best JVM settings you have found for running Eclipse?
It is that time of year again: "eclipse.ini take 3" the settings strike back! Eclipse Helios 3.6 and 3.6.x settings ===================================== [alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png](http://www.eclipse.org/home/promotions/friends-helios/helios.png) After settings for [Eclipse Ganymede 3.4.x](https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349) and [Eclipse Galileo 3.5.x](https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/1409590#1409590), here is an in-depth look at an "optimized" **[eclipse.ini](http://wiki.eclipse.org/Eclipse.ini)** settings file for Eclipse Helios 3.6.x: * based on **[runtime options](http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html)**, * and using the **Sun-Oracle JVM 1.6u21 b7**, [released July, 27th](http://java.about.com/b/2010/07/27/java-6-update-21-build-07-released.htm) (~~some some Sun proprietary options may be involved~~). (by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7) Eclipse.ini ----------- ![alt text](https://www.eclipse.org/downloads/images/classic2.jpg) **WARNING**: for non-windows platform, use the Sun proprietary option `-XX:MaxPermSize` instead of the Eclipse proprietary option `--launcher.XXMaxPermSize`. That is: **Unless** you are using the latest **jdk6u21 build 7**. See the Oracle section below. ``` -data ../../workspace -showlocation -showsplash org.eclipse.platform --launcher.defaultAction openFile -vm C:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll -vmargs -Dosgi.requiredJavaVersion=1.6 -Declipse.p2.unsignedPolicy=allow -Xms128m -Xmx384m -Xss4m -XX:PermSize=128m -XX:MaxPermSize=384m -XX:CompileThreshold=5 -XX:MaxGCPauseMillis=10 -XX:MaxHeapFreeRatio=70 -XX:+CMSIncrementalPacing -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:+UseFastAccessorMethods -Dcom.sun.management.jmxremote -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons ``` Note: Adapt the `p2.reconciler.dropins.directory` to an external directory of your choice. See this [SO answer](https://stackoverflow.com/questions/2763843/eclipse-plugins-vs-features-vs-dropins/2763891#2763891). The idea is to be able to drop new plugins in a directory independently from any Eclipse installation. The following sections detail what are in this `eclipse.ini` file. --- The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes --------------------------------------------------------------- [Andrew Niefer](https://stackoverflow.com/users/84728/andrew-niefer) did alert me to this situation, and wrote a [blog post](http://aniefer.blogspot.com/2010/07/permgen-problems-and-running-eclipse-on.html), about a non-standard vm argument (**`-XX:MaxPermSize`**) and can cause vms from other vendors to not start at all. But the eclipse version of that option (**`--launcher.XXMaxPermSize`**) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below). The ~~final~~ solution is on the [Eclipse Wiki](http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Oracle.2FSun_VM_1.6.0_21_on_Windows), and **for Helios on Windows with 6u21 pre build 7** only: * **downloading the fixed [eclipse\_1308.dll](https://bugs.eclipse.org/bugs/attachment.cgi?id=174343)** (July 16th, 2010) * and place it into ``` (eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503 ``` That's it. No setting to tweak here (again, only for Helios **on Windows** with a **6u21 pre build 7**). For non-Windows platform, you need to revert to the Sun proprietary option `-XX:MaxPermSize`. The issue is based one a regression: [JVM identification fails due to Oracle rebranding in java.exe](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6969236), and triggered [bug 319514](https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514) on Eclipse. Andrew took care of [Bug 320005 - [launcher] `--launcher.XXMaxPermSize: isSunVM` should return true for Oracle](https://bugs.eclipse.org/bugs/show_bug.cgi?id=320005), but that will be only for Helios 3.6.1. [Francis Upton](http://dev.eclipse.org/blogs/francis/about/), another Eclipse committer, [reflects on the all situation](http://dev.eclipse.org/blogs/francis/2010/07/15/some-thoughts-on-the-java-u21-problem/). **Update u21b7, July, 27th**: **Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7**. If you use **[jdk6u21 build 7](http://www.oracle.com/technetwork/java/javase/downloads/index.html)**, you can revert to the **`--launcher.XXMaxPermSize`** (eclipse option) instead of **`-XX:MaxPermSize`** (the non-standard option). The [auto-detection happening in the C launcher shim `eclipse.exe`](http://www.infoq.com/news/2010/07/eclipse-java-6u21) will still look for the "`Sun Microsystems`" string, but with 6u21b7, it will now work - again. For now, I still keep the `-XX:MaxPermSize` version (because I have no idea when everybody will launch eclipse the *right* JDK). --- Implicit `-startup` and `--launcher.library` -------------------------------------------- Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases: * startup: If not specified, the executable will look in the plugins directory for the `org.eclipse.equinox.launcher` bundle with the highest version. * launcher.library: If not specified, the executable looks in the `plugins` directory for the appropriate `org.eclipse.equinox.launcher.[platform]` fragment with the highest version and uses the shared library named `eclipse_*` inside. --- Use JDK6 -------- The JDK6 is now explicitly required to launch Eclipse: ``` -Dosgi.requiredJavaVersion = 1.6 ``` This [SO question](https://stackoverflow.com/questions/2787055/using-the-android-sdk-on-a-mac-eclipse-is-really-slow-how-can-i-speed-it-up) reports a positive incidence for development on Mac OS. --- +UnlockExperimentalVMOptions ---------------------------- The following options are part of some of the experimental options of the Sun JVM. ``` -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:+UseFastAccessorMethods ``` They have been reported in this [blog post](http://ugosan.org/speeding-up-eclipse-a-bit-with-unlockexperimentalvmoptions/) to potentially speed up Eclipse. See all the [JVM options here](http://blogs.oracle.com/watt/resource/jvm-options-list.html) and also in the official [Java Hotspot options page](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp). Note: the [detailed list of those options](http://www.md.pp.ru/~eu/jdk6options.html) reports that `UseFastAccessorMethods` might be active by default. See also ["Update your JVM"](http://translate.googleusercontent.com/translate_c?hl=en&sl=fr&tl=en&u=http://blog.xebia.fr/2010/07/13/revue-de-presse-xebia-167/&rurl=translate.google.com&twu=1&usg=ALkJrhgLW58oZuCouEaFZBTA_u6ZTQwvGA#MettezjourvotreJVM): > > As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17. > > > --- Opening files in Eclipse from the command line ---------------------------------------------- See the [blog post](http://aniefer.blogspot.com/2010/05/opening-files-in-eclipse-from-command.html) from Andrew Niefer reporting this new option: ``` --launcher.defaultAction openFile ``` > > This tells the launcher that if it is called with a command line that only contains arguments that don't start with "`-`", then those arguments should be treated as if they followed "`--launcher.openFile`". > > > ``` eclipse myFile.txt ``` > > This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose "`Open With`" or "`Send To`" Eclipse. > > > [Relative paths](https://bugs.eclipse.org/bugs/show_bug.cgi?id=300532) will be resolved first against the current working directory, and second against the eclipse program directory. > > > See [bug 301033](https://bugs.eclipse.org/bugs/show_bug.cgi?id=301033) for reference. Originally [bug 4922](https://bugs.eclipse.org/bugs/show_bug.cgi?id=4922) (October 2001, fixed 9 years later). --- p2 and the Unsigned Dialog Prompt --------------------------------- If you are tired of this dialog box during the installation of your many plugins: ![alt text](https://aniszczyk.org/wp-content/uploads/2010/05/unsigneddialog.png) , add in your `eclipse.ini`: ``` -Declipse.p2.unsignedPolicy=allow ``` See this [blog post](http://aniszczyk.org/2010/05/20/p2-and-the-unsigned-dialog-prompt/) from [Chris Aniszczy](http://aniszczyk.org/about/), and the [bug report 235526](https://bugs.eclipse.org/bugs/show_bug.cgi?id=235526). > > I do want to say that security research supports the fact that less prompts are better. > > People ignore things that pop up in the flow of something they want to get done. > > > For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them. > > Instead, we should collect all the problems, do *not* install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called **['safe staging'](http://www.eecs.berkeley.edu/~tygar/papers/Safe_staging_for_computer_security.pdf)**. > > > [---------- http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif) [alt text http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif) [alt text http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif) Additional options ------------------- Those options are not directly in the `eclipse.ini` above, but can come in handy if needed. --- ### The `user.home` issue on Windows7 When eclipse starts, it will read its keystore file (where passwords are kept), a file located in `user.home`. If for some reason that `user.home` doesn't resolve itself properly to a full-fledge path, Eclipse won't start. Initially raised in [this SO question](https://stackoverflow.com/questions/2120160/eclipse-is-not-starting-on-windows-7/2120198#2120198), if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start) Add in your `eclipse.ini`: ``` -eclipse.keyring C:\eclipse\keyring.txt ``` This has been tracked by [bug 300577](https://bugs.eclipse.org/bugs/show_bug.cgi?id=300577), it has been solve in this [other SO question](https://stackoverflow.com/questions/2134338/java-user-home-is-being-set-to-userprofile-and-not-being-resolved). --- ### Debug mode Wait, there's more than one setting file in Eclipse. if you add to your `eclipse.ini` the option: ``` -debug ``` , you enable the [debug mode](http://www.eclipse.org/eclipse/platform-core/documents/3.1/debug.html) and Eclipse will look for *another* setting file: a `.options` file where you can specify some OSGI options. And that is great when you are adding new plugins through the dropins folder. Add in your .options file the following settings, as described in this [blog post "**Dropins diagnosis**"](http://eclipser-blog.blogspot.com/2010/01/dropins-diagnosis.html): ``` org.eclipse.equinox.p2.core/debug=true org.eclipse.equinox.p2.core/reconciler=true ``` > > P2 will inform you what bundles were found in `dropins/` folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start: > > > * was your bundle in the plan? > * Was it installation problem (P2 fault) > * or maybe it is just not optimal to include your feature? > > > That comes from [Bug 264924 - [reconciler] No diagnosis of dropins problems](https://bugs.eclipse.org/bugs/show_bug.cgi?id=264924), which finally solves the following issue like: ``` Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse Unzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5 ``` > > This is a problematic configuration since OCL depends on EMF which is missing. > > 3.5M5 provides no diagnosis of this problem. > > > Start eclipse. > > No obvious problems. Nothing in Error Log. > > > * `Help / About / Plugin` details shows `org.eclipse.ocl.doc`, but not `org.eclipse.ocl`. > * `Help / About / Configuration` details has no (diagnostic) mention of > `org.eclipse.ocl`. > * `Help / Installation / Information Installed Software` has no mention of `org.eclipse.ocl`. > > > Where are the nice error markers? > > > --- ### Manifest Classpath See this [blog post](http://lt-rider.blogspot.com/2010/05/jdt-manifest-classpath-classpath.html): > > * In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party. > * In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution. > > > That means some of your projects might no longer compile in Helios. If you want to revert to Galileo behavior, add: ``` -DresolveReferencedLibrariesForContainers=true ``` See [bug 305037](https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037), [bug 313965](https://bugs.eclipse.org/bugs/show_bug.cgi?id=313965) and [bug 313890](https://bugs.eclipse.org/bugs/show_bug.cgi?id=313890) for references. --- ### IPV4 stack This [SO question](https://stackoverflow.com/questions/1500646/eclipse-3-5-unable-to-install-plugins) mentions a potential fix when not accessing to plugin update sites: ``` -Djava.net.preferIPv4Stack=true ``` Mentioned here just in case it could help in your configuration. --- ### JVM1.7x64 potential optimizations [This article](http://nerds-central.blogspot.com/2009/09/tuning-jvm-for-unusual-uses-have-some.html) reports: > > For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are: > > > ``` -Xincgc -XX:-DontCompileHugeMethods -XX:MaxInlineSize=1024 -XX:FreqInlineSize=1024 ``` > > But I am still working on it... > > >
142,391
<p>I am making extensive use of <code>boost:shared_ptr</code> in my code. In fact, most of the objects that are allocated on the heap are held by a <code>shared_ptr</code>. Unfortunately this means that I can't pass <code>this</code> into any function that takes a <code>shared_ptr</code>. Consider this code:</p> <pre><code>void bar(boost::shared_ptr&lt;Foo&gt; pFoo) { ... } void Foo::someFunction() { bar(this); } </code></pre> <p>There are two problems here. First, this won't compile because the T* constructor for <code>shared_ptr</code> is explicit. Second, if I force it to build with <code>bar(boost::shared_ptr&lt;Foo&gt;(this))</code> I will have created a second shared pointer to my object that will eventually lead to a double-delete.</p> <p>This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?</p>
[ { "answer_id": 142397, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 4, "selected": false, "text": "<p>boost has a solution for this use case, check <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html\" rel=\"noreferrer\">enable_shared_from_this</a></p>\n" }, { "answer_id": 142401, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 8, "selected": true, "text": "<p>You can derive from <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html\" rel=\"noreferrer\">enable_shared_from_this</a> and then you can use \"shared_from_this()\" instead of \"this\" to spawn a shared pointer to your own self object.</p>\n\n<p>Example in the link:</p>\n\n<pre><code>#include &lt;boost/enable_shared_from_this.hpp&gt;\n\nclass Y: public boost::enable_shared_from_this&lt;Y&gt;\n{\npublic:\n\n shared_ptr&lt;Y&gt; f()\n {\n return shared_from_this();\n }\n}\n\nint main()\n{\n shared_ptr&lt;Y&gt; p(new Y);\n shared_ptr&lt;Y&gt; q = p-&gt;f();\n assert(p == q);\n assert(!(p &lt; q || q &lt; p)); // p and q must share ownership\n}\n</code></pre>\n\n<p>It's a good idea when spawning threads from a member function to boost::bind to a shared_from_this() instead of this. It will ensure that the object is not released.</p>\n" }, { "answer_id": 142440, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "<p>Are you really making more shared copies of pFoo inside bar? If you aren't doing anything crazy inside, just do this:</p>\n\n<pre><code>\nvoid bar(Foo &foo)\n{\n // ...\n}\n</code></pre>\n" }, { "answer_id": 142604, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 2, "selected": false, "text": "<p>The function accepting a pointer wants to do one of two behaviors:</p>\n\n<ul>\n<li><strong>Own the object</strong> being passed in, and delete it when it goes out of scope. In this case, you can just accept X* and immediately wrap a scoped_ptr around that object (in the function body). This will work to accept \"this\" or, in general, any heap-allocated object.</li>\n<li><strong>Share a pointer</strong> (don't own it) to the object being passed in. In this case you do <em>not</em> want to use a scoped_ptr at all, since you don't want to delete the object at the end of your function. In this case, what you theoretically want is a shared_ptr (I've seen it called a linked_ptr elsewhere). The boost library has <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm\" rel=\"nofollow noreferrer\">a version of shared_ptr</a>, and this is also recommended in Scott Meyers' Effective C++ book (item 18 in the 3rd edition).</li>\n</ul>\n\n<p><strong>Edit:</strong> Oops I slightly misread the question, and I now see this answer is not exactly addressing the question. I'll leave it up anyway, in case this might be helpful for anyone working on similar code.</p>\n" }, { "answer_id": 142945, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": false, "text": "<p>Just use a raw pointer for your function parameter instead of the shared_ptr. The purpose of a smart pointer is to control the lifetime of the object, but the object lifetime is already guaranteed by C++ scoping rules: it will exist for at least as long as the end of your function. That is, the calling code can't possibly delete the object before your function returns; thus the safety of a \"dumb\" pointer is guaranteed, as long as you don't try to delete the object inside your function.</p>\n\n<p>The only time you need to pass a shared_ptr into a function is when you want to pass ownership of the object to the function, or want the function to make a copy of the pointer.</p>\n" }, { "answer_id": 14030930, "author": "Johan Lundberg", "author_id": 1149664, "author_profile": "https://Stackoverflow.com/users/1149664", "pm_score": 3, "selected": false, "text": "<p>With C++11 <code>shared_ptr</code> and <code>enable_shared_from_this</code> is now in the standard library. The latter is, as the name suggests, for this case exactly. </p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\">http://en.cppreference.com/w/cpp/memory/shared_ptr</a></p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/memory/enable_shared_from_this\" rel=\"noreferrer\">http://en.cppreference.com/w/cpp/memory/enable_shared_from_this</a></p>\n\n<p>Example bases on that in the links above:</p>\n\n<pre><code>struct Good: std::enable_shared_from_this&lt;Good&gt;{\n std::shared_ptr&lt;Good&gt; getptr() {\n return shared_from_this();\n }\n};\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>std::shared_ptr&lt;Good&gt; gp1(new Good);\nstd::shared_ptr&lt;Good&gt; gp2 = gp1-&gt;getptr();\nstd::cout &lt;&lt; \"gp2.use_count() = \" &lt;&lt; gp2.use_count() &lt;&lt; '\\n';\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031/" ]
I am making extensive use of `boost:shared_ptr` in my code. In fact, most of the objects that are allocated on the heap are held by a `shared_ptr`. Unfortunately this means that I can't pass `this` into any function that takes a `shared_ptr`. Consider this code: ``` void bar(boost::shared_ptr<Foo> pFoo) { ... } void Foo::someFunction() { bar(this); } ``` There are two problems here. First, this won't compile because the T\* constructor for `shared_ptr` is explicit. Second, if I force it to build with `bar(boost::shared_ptr<Foo>(this))` I will have created a second shared pointer to my object that will eventually lead to a double-delete. This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?
You can derive from [enable\_shared\_from\_this](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html) and then you can use "shared\_from\_this()" instead of "this" to spawn a shared pointer to your own self object. Example in the link: ``` #include <boost/enable_shared_from_this.hpp> class Y: public boost::enable_shared_from_this<Y> { public: shared_ptr<Y> f() { return shared_from_this(); } } int main() { shared_ptr<Y> p(new Y); shared_ptr<Y> q = p->f(); assert(p == q); assert(!(p < q || q < p)); // p and q must share ownership } ``` It's a good idea when spawning threads from a member function to boost::bind to a shared\_from\_this() instead of this. It will ensure that the object is not released.
142,400
<p>I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0.</p> <p>Given the following xml:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;2300&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>It would be great to produce the resulting xml:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;23:00&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>However, if the source xml contains an invalid 24 hour time format, the resulting <em>dstTime</em> element should be blank.</p> <p>For example, when the invalid source xml is the following:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;NOON&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>The resulting xml should be:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>The question is, what's the <strong>best XSLT 1.0</strong> fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible).</p>
[ { "answer_id": 142416, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "<p>XSLT 1.0 does not have any standard support for date/time manipulation.</p>\n\n<p>You must write a simple parsing and formatting function. That's not going to be simple, and that's not going to be pretty.</p>\n\n<p>XSLT is really designed for tree transformations. This sort of text node manipulations are best done outside of XSLT.</p>\n" }, { "answer_id": 142560, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Have a look at:\n<a href=\"http://www.exslt.org/\" rel=\"nofollow noreferrer\">http://www.exslt.org/</a> specifically the \"dates and times\" section.\nI haven't dug deep into it but it looks like it may be what your looking for.</p>\n" }, { "answer_id": 142736, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>Even the exslt.org time() function won't help you here, because it expects its input to be in the proper format (xs:dateTime or xs:time).</p>\n\n<p>This is something that is best fixed outside of XSLT. I say this as someone who routinely uses XSLT to do things it wasn't really designed for and manages to get things working. It was <em>really</em> not designed to parse strings.</p>\n\n<p>The ideal solution is to fix whatever is producing the XML document so that it formats times using the international standard conveniently established just for that purpose, using the principle that you shouldn't persist or transmit crap data if you can avoid doing so. </p>\n\n<p>But if that's not possible, you should either fix the data before passing it to XSLT or fix it after generating the transform's output.</p>\n" }, { "answer_id": 144536, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<p>There aren't any regular expressions in XSLT 1.0, so I'm afraid that pattern matching isn't going to be possible.</p>\n\n<p>I'm not clear if <code>&lt;srcTime&gt;23:00&lt;/srcTime&gt;</code> is supposed to be legal or not? If it is, try:</p>\n\n<pre><code>&lt;dstTime&gt;\n &lt;xsl:if test=\"string-length(srcTime) = 4 or\n string-length(srcTime) = 5\"&gt;\n &lt;xsl:variable name=\"hour\" select=\"substring(srcTime, 1, 2)\" /&gt;\n &lt;xsl:if test=\"$hour &gt;= 0 and 24 &gt; $hour\"&gt;\n &lt;xsl:variable name=\"minute\"&gt;\n &lt;xsl:choose&gt;\n &lt;xsl:when test=\"string-length(srcTime) = 5 and\n substring(srcTime, 3, 1) = ':'\"&gt;\n &lt;xsl:value-of select=\"substring(srcTime, 4, 2)\" /&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:when test=\"string-length(srcTime) = 4\"&gt;\n &lt;xsl:value-of select=\"substring(srcTime, 3, 2)\" /&gt;\n &lt;/xsl:when&gt;\n &lt;/xsl:choose&gt;\n &lt;/xsl:variable&gt;\n &lt;xsl:if test=\"$minute &gt;= 0 and 60 &gt; $minute\"&gt;\n &lt;xsl:value-of select=\"concat($hour, ':', $minute)\" /&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:if&gt;\n&lt;/dstTime&gt;\n</code></pre>\n\n<p>If it isn't, and four digits is the only thing that's legal then:</p>\n\n<pre><code>&lt;dstTime&gt;\n &lt;xsl:if test=\"string-length(srcTime) = 4\"&gt;\n &lt;xsl:variable name=\"hour\" select=\"substring(srcTime, 1, 2)\" /&gt;\n &lt;xsl:if test=\"$hour &gt;= 0 and 24 &gt; $hour\"&gt;\n &lt;xsl:variable name=\"minute\" select=\"substring(srcTime, 3, 2)\" /&gt;\n &lt;xsl:if test=\"$minute &gt;= 0 and 60 &gt; $minute\"&gt;\n &lt;xsl:value-of select=\"concat($hour, ':', $minute)\" /&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:if&gt;\n&lt;/dstTime&gt;\n</code></pre>\n" }, { "answer_id": 155085, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 2, "selected": false, "text": "<p>Depending on the actual xslt processor used you could be able to do desired operations in custom extension function (which you would have to make yourself).</p>\n\n<p>Xalan has good support for <a href=\"http://xml.apache.org/xalan-j/extensions.html\" rel=\"nofollow noreferrer\">extension functions</a>, you can write them not only in Java but also in JavaScript or other languages supported by <a href=\"http://jakarta.apache.org/bsf/index.html\" rel=\"nofollow noreferrer\">Apache BSF</a>.</p>\n\n<p>Microsoft's XSLT engine supports custom extensions as well, as described in <a href=\"http://msdn.microsoft.com/en-us/library/6datxzsd.aspx\" rel=\"nofollow noreferrer\">.NET Framework Developer's Guide, Extending XSLT Style Sheets</a></p>\n" }, { "answer_id": 155091, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 1, "selected": false, "text": "<p>And to have the list complete, there is also <a href=\"http://xsltsl.sourceforge.net/date-time.html\" rel=\"nofollow noreferrer\">Date/Time processing module</a> part of XSLT Standard Library by Steve Ball.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0. Given the following xml: ``` <root> <srcTime>2300</srcTime> </root> ``` It would be great to produce the resulting xml: ``` <root> <dstTime>23:00</dstTime> </root> ``` However, if the source xml contains an invalid 24 hour time format, the resulting *dstTime* element should be blank. For example, when the invalid source xml is the following: ``` <root> <srcTime>NOON</srcTime> </root> ``` The resulting xml should be: ``` <root> <dstTime></dstTime> </root> ``` The question is, what's the **best XSLT 1.0** fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible).
There aren't any regular expressions in XSLT 1.0, so I'm afraid that pattern matching isn't going to be possible. I'm not clear if `<srcTime>23:00</srcTime>` is supposed to be legal or not? If it is, try: ``` <dstTime> <xsl:if test="string-length(srcTime) = 4 or string-length(srcTime) = 5"> <xsl:variable name="hour" select="substring(srcTime, 1, 2)" /> <xsl:if test="$hour >= 0 and 24 > $hour"> <xsl:variable name="minute"> <xsl:choose> <xsl:when test="string-length(srcTime) = 5 and substring(srcTime, 3, 1) = ':'"> <xsl:value-of select="substring(srcTime, 4, 2)" /> </xsl:when> <xsl:when test="string-length(srcTime) = 4"> <xsl:value-of select="substring(srcTime, 3, 2)" /> </xsl:when> </xsl:choose> </xsl:variable> <xsl:if test="$minute >= 0 and 60 > $minute"> <xsl:value-of select="concat($hour, ':', $minute)" /> </xsl:if> </xsl:if> </xsl:if> </dstTime> ``` If it isn't, and four digits is the only thing that's legal then: ``` <dstTime> <xsl:if test="string-length(srcTime) = 4"> <xsl:variable name="hour" select="substring(srcTime, 1, 2)" /> <xsl:if test="$hour >= 0 and 24 > $hour"> <xsl:variable name="minute" select="substring(srcTime, 3, 2)" /> <xsl:if test="$minute >= 0 and 60 > $minute"> <xsl:value-of select="concat($hour, ':', $minute)" /> </xsl:if> </xsl:if> </xsl:if> </dstTime> ```
142,407
<p>I am testing a Ruby Rails website and wanted to get started with Unit and Functional testing.</p>
[ { "answer_id": 142540, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://github.com/aslakhellesoy/cucumber/wikis\" rel=\"nofollow noreferrer\">Cucumber</a> and <a href=\"http://rspec.info/\" rel=\"nofollow noreferrer\">RSpec</a> are worth a look. They encourage testing in a <a href=\"http://behaviour-driven.org/\" rel=\"nofollow noreferrer\">behaviour-driven</a>, example-based style.</p>\n\n<p>RSpec is a library for unit-level testing:</p>\n\n<pre><code>describe \"hello_world\"\n it \"should say hello to the world\" do\n # RSpec comes with its own mock-object framework built in,\n # though it lets you use others if you prefer\n world = mock(\"World\", :population =&gt; 6e9)\n world.should_receive(:hello)\n hello_world(world)\n end\nend\n</code></pre>\n\n<p>It has special support for Rails (e.g. it can test models, views and controllers in isolation) and can replace the testing mechanisms built in to Rails.</p>\n\n<p>Cucumber (formerly known as the RSpec Story Runner) lets you write high-level acceptance tests in (fairly) plain English that you could show to (and agree with) a customer, then run them:</p>\n\n<pre><code>Story: Commenting on articles\n\n As a visitor to the blog\n I want to post comments on articles\n So that I can have my 15 minutes of fame\n\n Scenario: Post a new comment\n\n Given I am viewing an article\n When I add a comment \"Me too!\"\n And I fill in the CAPTCHA correctly\n Then I should see a comment \"Me too!\"\n</code></pre>\n" }, { "answer_id": 142544, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>My recommendation is (seriously) just bypass the built in rails unit/functional testing stuff, and go straight for <a href=\"http://www.rspec.info/\" rel=\"nofollow noreferrer\">RSpec</a>.</p>\n\n<p>The built in rails stuff uses the <code>Test::Unit</code> framework which ships with ruby, and which is more or less a straight port of JUnit/NUnit/AnyOtherUnit.<br>\nI found these frameworks all rather tedious and annoying, leading to general apathy about writing unit tests, which is obviously not what you're trying to acheive here.</p>\n\n<p>RSpec is a different beast, being centered around describing what your code <em>should</em> do, rather than asserting what it <em>already does</em>. It will change how you view testing, and you'll have a heck of a lot more fun doing it. </p>\n\n<p>If I sound like a bit of a fanboy, it's only because I really believe RSpec is that good. I went from being annoyed and tired of unit/functional testing, to a staunch believer in it, pretty much solely because of rspec.</p>\n" }, { "answer_id": 143353, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 2, "selected": false, "text": "<p>It sounds like you've already written your application, so I'm not sure you'll get a huge bonus from using <code>RSpec</code> over <code>Test::Unit</code>.</p>\n\n<p>Anyhow regardless of which one you choose, you'll quickly run into another issue: managing fixtures and mocks (i.e. your test \"data\"). So take a look at <a href=\"http://www.thoughtbot.com/projects/shoulda\" rel=\"nofollow noreferrer\">Shoulda</a> and <a href=\"http://giantrobots.thoughtbot.com/2008/6/6/waiting-for-a-factory-girl\" rel=\"nofollow noreferrer\">Factory Girl</a>.</p>\n" }, { "answer_id": 148870, "author": "Aaron", "author_id": 23459, "author_profile": "https://Stackoverflow.com/users/23459", "pm_score": 0, "selected": false, "text": "<p>Even if the app is already written, I would recommend using RSpec over Test::Unit for the simple fact that no application is ever finished. You're going to want to add features and refactor code. Getting the right test habit early on will help make these alterations less painful</p>\n" }, { "answer_id": 148885, "author": "danivovich", "author_id": 17583, "author_profile": "https://Stackoverflow.com/users/17583", "pm_score": 1, "selected": false, "text": "<p>You can also test out the web interface with a Firefox plug-in such as <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">http://selenium.openqa.org/</a></p>\n\n<p>It will record clicks and text entry and then plays back and will check the page for the correct display elements. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22883/" ]
I am testing a Ruby Rails website and wanted to get started with Unit and Functional testing.
[Cucumber](http://github.com/aslakhellesoy/cucumber/wikis) and [RSpec](http://rspec.info/) are worth a look. They encourage testing in a [behaviour-driven](http://behaviour-driven.org/), example-based style. RSpec is a library for unit-level testing: ``` describe "hello_world" it "should say hello to the world" do # RSpec comes with its own mock-object framework built in, # though it lets you use others if you prefer world = mock("World", :population => 6e9) world.should_receive(:hello) hello_world(world) end end ``` It has special support for Rails (e.g. it can test models, views and controllers in isolation) and can replace the testing mechanisms built in to Rails. Cucumber (formerly known as the RSpec Story Runner) lets you write high-level acceptance tests in (fairly) plain English that you could show to (and agree with) a customer, then run them: ``` Story: Commenting on articles As a visitor to the blog I want to post comments on articles So that I can have my 15 minutes of fame Scenario: Post a new comment Given I am viewing an article When I add a comment "Me too!" And I fill in the CAPTCHA correctly Then I should see a comment "Me too!" ```
142,417
<p>Recently, <a href="https://stackoverflow.com/users/5200/lee-baldwin">Lee Baldwin</a> showed how to write a <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689">generic, variable argument memoize function</a>. I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:</p> <pre><code>local function memoize(f) local cache = {} if select('#', ...) == 1 then return function (x) if cache[x] then return cache[x] else local y = f(x) cache[x] = y return y end end else return function (...) local al = varg_tostring(...) if cache[al] then return cache[al] else local y = f(...) cache[al] = y return y end end end end </code></pre> <p>Obviously, <code>select('#', ...)</code> fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside <strong>memoize</strong> how many arguments <strong>f</strong> expects? </p> <hr> <p>"No" is a fine answer if you know for sure. It's not a big deal to use two separate <strong>memoize</strong> functions.</p>
[ { "answer_id": 142424, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I guess you could go into the debug info and determine this from the source-code, but basically it's a \"no\", sorry.</p>\n" }, { "answer_id": 142429, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 2, "selected": false, "text": "<p>I'm pretty sure you can't do that in Lua.</p>\n" }, { "answer_id": 24216007, "author": "Tom Blodget", "author_id": 2226988, "author_profile": "https://Stackoverflow.com/users/2226988", "pm_score": 2, "selected": false, "text": "<p>Yes, for Lua functions but not C functions. It's a bit torturous and a little sketchy.</p>\n\n<p><code>debug.getlocal</code> works on called functions so you have to call the function in question. It doesn't show any hint of <code>...</code> unless the call passes enough parameters. The code below tries 20 parameters.</p>\n\n<p><code>debug.sethook</code> with the \"call\" event gives an opportunity to intercept the function before it runs any code.</p>\n\n<p>This algorithm works with Lua 5.2. Older versions would be similar but not the same:</p>\n\n<pre><code>assert(_VERSION==\"Lua 5.2\", \"Must be compatible with Lua 5.2\")\n</code></pre>\n\n<p>A little helper iterator (could be inlined for efficiency):</p>\n\n<pre><code>local function getlocals(l)\n local i = 0\n local direction = 1\n return function ()\n i = i + direction\n local k,v = debug.getlocal(l,i)\n if (direction == 1 and (k == nil or k.sub(k,1,1) == '(')) then \n i = -1 \n direction = -1 \n k,v = debug.getlocal(l,i) \n end\n return k,v\n end\nend\n</code></pre>\n\n<p>Returns the signature (but could return a parameter count and usesVarargs, instead):</p>\n\n<pre><code>local function dumpsig(f)\n assert(type(f) == 'function', \n \"bad argument #1 to 'dumpsig' (function expected)\")\n local p = {}\n pcall (function() \n local oldhook\n local hook = function(event, line)\n for k,v in getlocals(3) do \n if k == \"(*vararg)\" then \n table.insert(p,\"...\") \n break\n end \n table.insert(p,k) end\n debug.sethook(oldhook)\n error('aborting the call')\n end\n oldhook = debug.sethook(hook, \"c\")\n -- To test for vararg must pass a least one vararg parameter\n f(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)\n end)\n return \"function(\"..table.concat(p,\",\")..\")\" \nend\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
Recently, [Lee Baldwin](https://stackoverflow.com/users/5200/lee-baldwin) showed how to write a [generic, variable argument memoize function](https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689). I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt: ``` local function memoize(f) local cache = {} if select('#', ...) == 1 then return function (x) if cache[x] then return cache[x] else local y = f(x) cache[x] = y return y end end else return function (...) local al = varg_tostring(...) if cache[al] then return cache[al] else local y = f(...) cache[al] = y return y end end end end ``` Obviously, `select('#', ...)` fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside **memoize** how many arguments **f** expects? --- "No" is a fine answer if you know for sure. It's not a big deal to use two separate **memoize** functions.
I guess you could go into the debug info and determine this from the source-code, but basically it's a "no", sorry.
142,420
<p>I have a method lets say:</p> <pre><code>private static String drawCellValue( int maxCellLength, String cellValue, String align) { } </code></pre> <p>and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?</p> <p>Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.</p> <p>Any ideas?</p>
[ { "answer_id": 142428, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 7, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n if (align == Alignment.LEFT)\n {\n //Process it...\n }\n}\n</code></pre>\n" }, { "answer_id": 142435, "author": "Michael Bobick", "author_id": 3425, "author_profile": "https://Stackoverflow.com/users/3425", "pm_score": 1, "selected": false, "text": "<p>Sure, you could use an enum. Would something like the following work?</p>\n\n<pre><code>enum Alignment {\n LEFT,\n RIGHT\n}\n</code></pre>\n\n<p>private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }</p>\n\n<p>If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.</p>\n" }, { "answer_id": 143129, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 1, "selected": false, "text": "<p>You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.</p>\n" }, { "answer_id": 144571, "author": "Joshua DeWald", "author_id": 22752, "author_profile": "https://Stackoverflow.com/users/22752", "pm_score": 4, "selected": false, "text": "<p>Even cooler with enums you can use switch:</p>\n\n<pre><code>switch (align) {\n case LEFT: { \n // do stuff\n break;\n }\n case RIGHT: {\n // do stuff\n break;\n }\n default: { //added TOP_RIGHT but forgot about it?\n throw new IllegalArgumentException(\"Can't yet handle \" + align);\n\n }\n}\n</code></pre>\n\n<p>Enums are cool because the output of the exception will be the name of the enum value, rather than some arbitrary int value. </p>\n" }, { "answer_id": 263230, "author": "Zamir", "author_id": 21274, "author_profile": "https://Stackoverflow.com/users/21274", "pm_score": 3, "selected": false, "text": "<p>I like this a lot better. \nreduces the if/switch, just do. </p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT;\n\nvoid process() {\n//Process it...\n} \n}; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n align.process();\n}\n</code></pre>\n\n<p>of course, \nit can be: </p>\n\n<pre><code>String process(...) {\n//Process it...\n} \n</code></pre>\n" }, { "answer_id": 14930883, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": 1, "selected": false, "text": "<p>I am not too sure I would go and use an enum as a full fledged class - this is an object oriented language, and one of the most basic tenets of object orientation is that a class should do one thing and do it well.</p>\n\n<p>An enum is doing a pretty good job at being an enum, and a class is doing a good job as a class. Mixing the two I have a feeling will get you into trouble - for example, you can't pass an instance of an enum as a parameter to a method, primarily because you can't create an instance of an enum.</p>\n\n<p>So, even though you might be able to enum.process() does not mean that you should.</p>\n" }, { "answer_id": 41705363, "author": "Alex Pawelko", "author_id": 7297891, "author_profile": "https://Stackoverflow.com/users/7297891", "pm_score": 1, "selected": false, "text": "<p>You can use an enum in said parameters like this:</p>\n\n<pre><code>public enum Alignment { LEFT, RIGHT }\nprivate static String drawCellValue(\nint maxCellLength, String cellValue, Alignment align) {}\n</code></pre>\n\n<p>then you can use either a switch or if statement to actually do something with said parameter.</p>\n\n<pre><code>switch(align) {\ncase LEFT: //something\ncase RIGHT: //something\ndefault: //something\n}\n\nif(align == Alignment.RIGHT) { /*code*/}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6618/" ]
I have a method lets say: ``` private static String drawCellValue( int maxCellLength, String cellValue, String align) { } ``` and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how? Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use. Any ideas?
This should do it: ``` private enum Alignment { LEFT, RIGHT }; String drawCellValue (int maxCellLength, String cellValue, Alignment align){ if (align == Alignment.LEFT) { //Process it... } } ```
142,431
<p>I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. </p> <p>So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. </p> <p>I can write my own, but it seems silly to do so if there's already a good app out there that handles this....</p> <p>Thanks for the help.</p>
[ { "answer_id": 142428, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 7, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n if (align == Alignment.LEFT)\n {\n //Process it...\n }\n}\n</code></pre>\n" }, { "answer_id": 142435, "author": "Michael Bobick", "author_id": 3425, "author_profile": "https://Stackoverflow.com/users/3425", "pm_score": 1, "selected": false, "text": "<p>Sure, you could use an enum. Would something like the following work?</p>\n\n<pre><code>enum Alignment {\n LEFT,\n RIGHT\n}\n</code></pre>\n\n<p>private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }</p>\n\n<p>If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.</p>\n" }, { "answer_id": 143129, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 1, "selected": false, "text": "<p>You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.</p>\n" }, { "answer_id": 144571, "author": "Joshua DeWald", "author_id": 22752, "author_profile": "https://Stackoverflow.com/users/22752", "pm_score": 4, "selected": false, "text": "<p>Even cooler with enums you can use switch:</p>\n\n<pre><code>switch (align) {\n case LEFT: { \n // do stuff\n break;\n }\n case RIGHT: {\n // do stuff\n break;\n }\n default: { //added TOP_RIGHT but forgot about it?\n throw new IllegalArgumentException(\"Can't yet handle \" + align);\n\n }\n}\n</code></pre>\n\n<p>Enums are cool because the output of the exception will be the name of the enum value, rather than some arbitrary int value. </p>\n" }, { "answer_id": 263230, "author": "Zamir", "author_id": 21274, "author_profile": "https://Stackoverflow.com/users/21274", "pm_score": 3, "selected": false, "text": "<p>I like this a lot better. \nreduces the if/switch, just do. </p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT;\n\nvoid process() {\n//Process it...\n} \n}; \nString drawCellValue (int maxCellLength, String cellValue, Alignment align){\n align.process();\n}\n</code></pre>\n\n<p>of course, \nit can be: </p>\n\n<pre><code>String process(...) {\n//Process it...\n} \n</code></pre>\n" }, { "answer_id": 14930883, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": 1, "selected": false, "text": "<p>I am not too sure I would go and use an enum as a full fledged class - this is an object oriented language, and one of the most basic tenets of object orientation is that a class should do one thing and do it well.</p>\n\n<p>An enum is doing a pretty good job at being an enum, and a class is doing a good job as a class. Mixing the two I have a feeling will get you into trouble - for example, you can't pass an instance of an enum as a parameter to a method, primarily because you can't create an instance of an enum.</p>\n\n<p>So, even though you might be able to enum.process() does not mean that you should.</p>\n" }, { "answer_id": 41705363, "author": "Alex Pawelko", "author_id": 7297891, "author_profile": "https://Stackoverflow.com/users/7297891", "pm_score": 1, "selected": false, "text": "<p>You can use an enum in said parameters like this:</p>\n\n<pre><code>public enum Alignment { LEFT, RIGHT }\nprivate static String drawCellValue(\nint maxCellLength, String cellValue, Alignment align) {}\n</code></pre>\n\n<p>then you can use either a switch or if statement to actually do something with said parameter.</p>\n\n<pre><code>switch(align) {\ncase LEFT: //something\ncase RIGHT: //something\ndefault: //something\n}\n\nif(align == Alignment.RIGHT) { /*code*/}\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9950/" ]
I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. I can write my own, but it seems silly to do so if there's already a good app out there that handles this.... Thanks for the help.
This should do it: ``` private enum Alignment { LEFT, RIGHT }; String drawCellValue (int maxCellLength, String cellValue, Alignment align){ if (align == Alignment.LEFT) { //Process it... } } ```
142,452
<p>There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:</p> <pre><code>bool MyFunction( char* buffer, int* bufferSize ) </code></pre> <p>I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is <strong>best done in PowerShell 1.0</strong>. The fact that the function needing to be called <strong><em>is using pointers</em></strong> could affect the solution (yet I don't really know).</p> <p>So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?</p> <p><strong>Remember for PowerShell 1.0.</strong></p>
[ { "answer_id": 142510, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 1, "selected": false, "text": "<p>There isn't any mechanism in PowerShell 1.0 to directly call Win32 API's. You could of course write a C# or VB.NET helper class to do this for you and call that from PowerShell.</p>\n\n<p>Update: Take a look at -</p>\n\n<p><a href=\"http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx</a>\n<a href=\"http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx\" rel=\"nofollow noreferrer\">http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx</a></p>\n" }, { "answer_id": 142516, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 3, "selected": false, "text": "<p>To call unmanaged code from Powershell, use the Invoke-Win32 function created by Lee Holmes. You can find the source <a href=\"http://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx\" rel=\"noreferrer\">here</a>. There you can see an example of how to call a function that has pointers, but a more trivial usage would be: </p>\n\n<pre><code>PS C:\\&gt; Invoke-Win32 \"msvcrt.dll\" ([Int32]) \"puts\" ([String]) \"Test\"\nTest\n0\n</code></pre>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature: ``` bool MyFunction( char* buffer, int* bufferSize ) ``` I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is **best done in PowerShell 1.0**. The fact that the function needing to be called ***is using pointers*** could affect the solution (yet I don't really know). So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above? **Remember for PowerShell 1.0.**
To call unmanaged code from Powershell, use the Invoke-Win32 function created by Lee Holmes. You can find the source [here](http://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx). There you can see an example of how to call a function that has pointers, but a more trivial usage would be: ``` PS C:\> Invoke-Win32 "msvcrt.dll" ([Int32]) "puts" ([String]) "Test" Test 0 ```
142,508
<p>I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:</p> <pre><code>#ifdef OSisWindows // do Windows-specific stuff #else // do Unix-specific stuff #endif </code></pre> <p>Is there a way to do this? Is there a better way to do the same thing?</p>
[ { "answer_id": 142522, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>Some compilers will generate #defines that can help you with this. Read the compiler documentation to determine what they are. <a href=\"https://msdn.microsoft.com/en-us/library/b0084kay.aspx\" rel=\"nofollow noreferrer\">MSVC</a> defines one that's <code>__WIN32__</code>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html\" rel=\"nofollow noreferrer\">GCC</a> has some you can see with <code>touch foo.h; gcc -dM foo.h</code></p>\n" }, { "answer_id": 142524, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "<p>Use <code>#define OSsymbol</code> and <code>#ifdef OSsymbol</code>\nwhere OSsymbol is a <code>#define</code>'able symbol identifying your target OS.</p>\n\n<p>Typically you would include a central header file defining the selected OS symbol and use OS-specific include and library directories to compile and build.</p>\n\n<p>You did not specify your development environment, but I'm pretty sure your compiler provides global defines for common platforms and OSes.</p>\n\n<p>See also <a href=\"http://en.wikibooks.org/wiki/C_Programming/Preprocessor\" rel=\"nofollow noreferrer\">http://en.wikibooks.org/wiki/C_Programming/Preprocessor</a></p>\n" }, { "answer_id": 142529, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 3, "selected": false, "text": "<p>In most cases it is better to check whether a given functionality is present or not. For example: if the function <code>pipe()</code> exists or not.</p>\n" }, { "answer_id": 142539, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<h1>Microsoft C/C++ compiler (MSVC) Predefined Macros can be found <a href=\"https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2019\" rel=\"noreferrer\">here</a></h1>\n<p>I think you are looking for:</p>\n<blockquote>\n<ul>\n<li><code>_WIN32</code> - Defined as 1 when the compilation target is 32-bit ARM, 64-bit ARM, x86, or x64. Otherwise, undefined</li>\n<li><code>_WIN64</code> - Defined as 1 when the compilation target is 64-bit ARM or x64. Otherwise, undefined.</li>\n</ul>\n</blockquote>\n<h1>gcc compiler PreDefined MAcros can be found <a href=\"https://gcc.gnu.org/onlinedocs/cpp/Predefined-Macros.html\" rel=\"noreferrer\">here</a></h1>\n<p>I think you are looking for:</p>\n<blockquote>\n<ul>\n<li><code>__GNUC__</code></li>\n<li><code>__GNUC_MINOR__</code></li>\n<li><code>__GNUC_PATCHLEVEL__</code></li>\n</ul>\n</blockquote>\n<p>Do a google for your appropriate compilers pre-defined.</p>\n" }, { "answer_id": 142563, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>There is no standard macro that is set according to C standard. Some C compilers will set one on some platforms (e.g. Apple's patched GCC sets a macro to indicate that it is compiling on an Apple system and for the Darwin platform). Your platform and/or your C compiler might set something as well, but there is no general way.</p>\n\n<p>Like hayalci said, it's best to have these macros set in your build process somehow. It is easy to define a macro with most compilers without modifying the code. You can simply pass <code>-D MACRO</code> to GCC, i.e.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>gcc -D Windows\ngcc -D UNIX\n</code></pre>\n\n<p>And in your code:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>#if defined(Windows)\n// do some cool Windows stuff\n#elif defined(UNIX)\n// do some cool Unix stuff\n#else\n# error Unsupported operating system\n#endif\n</code></pre>\n" }, { "answer_id": 647640, "author": "qwer", "author_id": 78243, "author_profile": "https://Stackoverflow.com/users/78243", "pm_score": 6, "selected": false, "text": "<p>show GCC defines on Windows:</p>\n\n<pre><code>gcc -dM -E - &lt;NUL:\n</code></pre>\n\n<p>on Linux:</p>\n\n<pre><code>gcc -dM -E - &lt;/dev/null\n</code></pre>\n\n<p>Predefined macros in MinGW:</p>\n\n<pre><code>WIN32 _WIN32 __WIN32 __WIN32__ __MINGW32__ WINNT __WINNT __WINNT__ _X86_ i386 __i386\n</code></pre>\n\n<p>on UNIXes:</p>\n\n<pre><code>unix __unix__ __unix\n</code></pre>\n" }, { "answer_id": 8249232, "author": "Lambda Fairy", "author_id": 617159, "author_profile": "https://Stackoverflow.com/users/617159", "pm_score": 10, "selected": true, "text": "<p>The <strong><a href=\"https://sourceforge.net/p/predef/wiki/OperatingSystems/\" rel=\"noreferrer\">Predefined Macros for OS</a></strong> site has a very complete list of checks. Here are a few of them, with links to where they're found:</p>\n<h2><a href=\"http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx\" rel=\"noreferrer\">Windows</a></h2>\n<p><code>_WIN32</code>   Both 32 bit and 64 bit<br/>\n<code>_WIN64</code>   64 bit only<br/>\n<code>__CYGWIN__</code></p>\n<h2>Unix (Linux, *BSD, but not Mac OS X)</h2>\n<p>See this <a href=\"https://stackoverflow.com/questions/7063303/\">related question</a> on some of the pitfalls of using this check.</p>\n<p><code>unix</code><br/>\n<code>__unix</code><br/>\n<code>__unix__</code></p>\n<h2>Mac OS X</h2>\n<p><code>__APPLE__</code> Also used for classic<br/>\n<code>__MACH__</code></p>\n<p>Both are defined; checking for either should work.</p>\n<h2><a href=\"http://www.faqs.org/docs/Linux-HOWTO/GCC-HOWTO.html\" rel=\"noreferrer\">Linux</a></h2>\n<p><code>__linux__</code><br>\n<code>linux</code> Obsolete (not POSIX compliant)<br>\n<code>__linux</code> Obsolete (not POSIX compliant)</p>\n<h2><a href=\"http://www.freebsd.org/doc/en/books/porters-handbook/porting-versions.html\" rel=\"noreferrer\">FreeBSD</a></h2>\n<p><code>__FreeBSD__</code></p>\n<h2>Android</h2>\n<p><code>__ANDROID__</code></p>\n" }, { "answer_id": 21940094, "author": "Arjun Sreedharan", "author_id": 997813, "author_profile": "https://Stackoverflow.com/users/997813", "pm_score": 3, "selected": false, "text": "<pre><code>#ifdef _WIN32\n// do something for windows like include &lt;windows.h&gt;\n#elif defined __unix__\n// do something for unix like include &lt;unistd.h&gt;\n#elif defined __APPLE__\n// do something for mac\n#endif\n</code></pre>\n" }, { "answer_id": 31734195, "author": "Konstantin Burlachenko", "author_id": 1154447, "author_profile": "https://Stackoverflow.com/users/1154447", "pm_score": 2, "selected": false, "text": "<p>Sorry for the external reference, but I think it is suited to your question:</p>\n<p><a href=\"https://web.archive.org/web/20191012035921/http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system\" rel=\"nofollow noreferrer\">C/C++ tip: How to detect the operating system type using compiler predefined macros</a></p>\n" }, { "answer_id": 41896671, "author": "anakod", "author_id": 1315814, "author_profile": "https://Stackoverflow.com/users/1315814", "pm_score": 3, "selected": false, "text": "<p>On MinGW, the <code>_WIN32</code> define check isn't working. Here's a solution:</p>\n\n<pre><code>#if defined(_WIN32) || defined(__CYGWIN__)\n // Windows (x86 or x64)\n // ...\n#elif defined(__linux__)\n // Linux\n // ...\n#elif defined(__APPLE__) &amp;&amp; defined(__MACH__)\n // Mac OS\n // ...\n#elif defined(unix) || defined(__unix__) || defined(__unix)\n // Unix like OS\n // ...\n#else\n #error Unknown environment!\n#endif\n</code></pre>\n\n<p>For more information please look: <a href=\"https://sourceforge.net/p/predef/wiki/OperatingSystems/\" rel=\"noreferrer\">https://sourceforge.net/p/predef/wiki/OperatingSystems/</a></p>\n" }, { "answer_id": 42040445, "author": "PADYMKO", "author_id": 6003870, "author_profile": "https://Stackoverflow.com/users/6003870", "pm_score": 6, "selected": false, "text": "<p>Based on <a href=\"https://web.archive.org/web/20191012035921/http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system\" rel=\"noreferrer\">nadeausoftware</a> and <a href=\"https://stackoverflow.com/a/8249232/6003870\">Lambda Fairy's answer</a>.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\n/**\n * Determination a platform of an operation system\n * Fully supported supported only GNU GCC/G++, partially on Clang/LLVM\n */\n\n#if defined(_WIN32)\n #define PLATFORM_NAME &quot;windows&quot; // Windows\n#elif defined(_WIN64)\n #define PLATFORM_NAME &quot;windows&quot; // Windows\n#elif defined(__CYGWIN__) &amp;&amp; !defined(_WIN32)\n #define PLATFORM_NAME &quot;windows&quot; // Windows (Cygwin POSIX under Microsoft Window)\n#elif defined(__ANDROID__)\n #define PLATFORM_NAME &quot;android&quot; // Android (implies Linux, so it must come first)\n#elif defined(__linux__)\n #define PLATFORM_NAME &quot;linux&quot; // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other\n#elif defined(__unix__) || !defined(__APPLE__) &amp;&amp; defined(__MACH__)\n #include &lt;sys/param.h&gt;\n #if defined(BSD)\n #define PLATFORM_NAME &quot;bsd&quot; // FreeBSD, NetBSD, OpenBSD, DragonFly BSD\n #endif\n#elif defined(__hpux)\n #define PLATFORM_NAME &quot;hp-ux&quot; // HP-UX\n#elif defined(_AIX)\n #define PLATFORM_NAME &quot;aix&quot; // IBM AIX\n#elif defined(__APPLE__) &amp;&amp; defined(__MACH__) // Apple OSX and iOS (Darwin)\n #include &lt;TargetConditionals.h&gt;\n #if TARGET_IPHONE_SIMULATOR == 1\n #define PLATFORM_NAME &quot;ios&quot; // Apple iOS\n #elif TARGET_OS_IPHONE == 1\n #define PLATFORM_NAME &quot;ios&quot; // Apple iOS\n #elif TARGET_OS_MAC == 1\n #define PLATFORM_NAME &quot;osx&quot; // Apple OSX\n #endif\n#elif defined(__sun) &amp;&amp; defined(__SVR4)\n #define PLATFORM_NAME &quot;solaris&quot; // Oracle Solaris, Open Indiana\n#else\n #define PLATFORM_NAME NULL\n#endif\n\n// Return a name of platform, if determined, otherwise - an empty string\nconst char *get_platform_name() {\n return (PLATFORM_NAME == NULL) ? &quot;&quot; : PLATFORM_NAME;\n}\n\nint main(int argc, char *argv[]) {\n puts(get_platform_name());\n return 0;\n}\n</code></pre>\n<p>Tested with GCC and clang on:</p>\n<ul>\n<li>Debian 8</li>\n<li>Windows (MinGW)</li>\n<li>Windows (Cygwin)</li>\n</ul>\n" }, { "answer_id": 42686138, "author": "MD XF", "author_id": 7659995, "author_profile": "https://Stackoverflow.com/users/7659995", "pm_score": 2, "selected": false, "text": "<p>Just to sum it all up, here are a bunch of helpful links.</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros\" rel=\"nofollow noreferrer\">GCC Common Predefined Macros</a></li>\n<li><a href=\"https://sourceforge.net/p/predef/wiki/OperatingSystems/\" rel=\"nofollow noreferrer\">SourceForge predefined Operating Systems</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros\" rel=\"nofollow noreferrer\">MSDN Predefined Macros</a></li>\n<li><a href=\"http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system\" rel=\"nofollow noreferrer\">The Much-Linked NaudeaSoftware Page</a></li>\n<li><a href=\"http://en.wikibooks.org/wiki/C_Programming/Preprocessor\" rel=\"nofollow noreferrer\">Wikipedia!!!</a></li>\n<li><a href=\"http://predef.sourceforge.net/prestd.html\" rel=\"nofollow noreferrer\">SourceForge's &quot;Overview of pre-defined compiler macros for standards, compilers, operating systems, and hardware architectures.&quot;</a></li>\n<li><a href=\"https://www.freebsd.org/doc/en/books/porters-handbook/porting-versions.html\" rel=\"nofollow noreferrer\">FreeBSD's &quot;Differentiating Operating Systems&quot;</a></li>\n<li><a href=\"https://sourceforge.net/p/predef/wiki/Home/\" rel=\"nofollow noreferrer\">All kinds of predefined macros</a></li>\n<li><a href=\"https://github.com/aaronryank/libportable\" rel=\"nofollow noreferrer\"><code>libportable</code></a></li>\n</ul>\n" }, { "answer_id": 48196597, "author": "Haseeb Mir", "author_id": 6219626, "author_profile": "https://Stackoverflow.com/users/6219626", "pm_score": 0, "selected": false, "text": "<p>You can use <strong>pre-processor directives</strong> as <strong><em>warning or error</em></strong> to check at compile time you don't need to <strong>run</strong> this program at all just simply <strong>compile</strong> it .</p>\n\n<pre><code>#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)\n #error Windows_OS\n#elif defined(__linux__)\n #error Linux_OS\n#elif defined(__APPLE__) &amp;&amp; defined(__MACH__)\n #error Mach_OS\n#elif defined(unix) || defined(__unix__) || defined(__unix)\n #error Unix_OS\n#else\n #error Unknown_OS\n#endif\n\n#include &lt;stdio.h&gt;\nint main(void)\n{\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 52768132, "author": "TadejP", "author_id": 4292145, "author_profile": "https://Stackoverflow.com/users/4292145", "pm_score": 1, "selected": false, "text": "<p>I did not find <a href=\"https://www.haiku-os.org\" rel=\"nofollow noreferrer\" title=\"Haiku\">Haiku</a> definition here. To be complete, Haiku-os definition is simple <code>__HAIKU__</code></p>\n" }, { "answer_id": 52992284, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"https://www.boost.org/doc/libs/1_80_0/libs/predef/doc/index.html\" rel=\"nofollow noreferrer\"><code>Boost.Predef</code></a> which contains various predefined macros for the target platform including the OS (<code>BOOST_OS_*</code>). Yes boost is often thought as a C++ library, but this one is a preprocessor header that <strong>works with C as well!</strong></p>\n<blockquote>\n<p>This library defines a set of compiler, architecture, operating system, library, and other version numbers from the information it can gather of C, C++, Objective C, and Objective C++ predefined macros or those defined in generally available headers. The idea for this library grew out of a proposal to extend the Boost Config library to provide more, and consistent, information than the feature definitions it supports. What follows is an edited version of that brief proposal.</p>\n</blockquote>\n<p>For example</p>\n<pre><code>#include &lt;boost/predef.h&gt;\n// or just include the necessary header\n// #include &lt;boost/predef/os.h&gt;\n\n#if BOOST_OS_WINDOWS\n#elif BOOST_OS_ANDROID\n#elif BOOST_OS_LINUX\n#elif BOOST_OS_BSD\n#elif BOOST_OS_AIX\n#elif BOOST_OS_HAIKU\n...\n#endif\n</code></pre>\n<p>The full list can be found in <a href=\"https://www.boost.org/doc/libs/1_80_0/libs/predef/doc/index.html#_boost_os_operating_system_macros\" rel=\"nofollow noreferrer\"><code>BOOST_OS</code> operating system macros</a></p>\n<p><a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGIMxqkrgAyeAyYAHI%2BAEaYxBIAzKQADqgKhE4MHt6%2B/oGp6Y4CoeFRLLHxXEl2mA6ZQgRMxATZPn4Btpj2RQwNTQQlkTFxibaNza25HQrjA2FD5SNVAJS2qF7EyOwc5glhyN5YANQmCW7RqGkEAPTJxJhYVAB0CKfYJhoAgtfXRyRH2i8MyO%2B0OmCOBAQ4PCWwUCiaAE8jlCmFhiB9vr9dqCvMdTudLjNbvdHtc0i83hiMWECEdgJgCAB5IQQZZUgDsVi%2B2KoRwsjOZABUAPrM4UAdQAkhEACKM8VCDFHZUq5X3AgbBhHLhmU5cz67Lp4Xn8oWioTC4LSuQADSVqpV6s1RzMCT1VNdRpNAqEIrFFiEMvtDqOTuIWoSknd3M9tGNfJ9fotAFlPm5mcGHWGtZIAKzRg2xpSZ1XZo65gBsBcNDHwVA5Qa%2BHFWtE4ud4fg4WlIqE4bms1iOCnWm3Bux4pAImmbqwA1iBI09JGYuABOSQVySSDSu3NSfScSQd6c9zi8BQgQJTrvN0hwWAwRAoVAsZJ0OLkShoV/v%2BIAN2QZJkmFP812FBIzGFVRNz4OgCDiC8IGiE9ojCRFOAnb82EERkGFoBETywFhDGAcQb1IfB7jqP9MAvcjMFUWovHgjDeBpLoTzjaJiERDwsBPAhiDwFhWNWKgDGABQADU8EwAB3RlkkYViZEEEQxHYfd%2BEERQVHUcjdC4fQSJQAdLH0PBogvWBmDYEALiuUgaP/QDZ2AZZVlQZIejo65GS4I5rnFI8UkMSJWHYcUwnQVA5IUTpukyFxa0mPwKzMIJa0GMoKhAaQCgyARUpAdKUjSQqGGy4Z4mkGo6gEPoJk8NoSoyuqekauZSmqvKxn6YrSpmfoqsWGrVmHDYtj0QTMG2HgWzbY9yN7KLa1i%2BLry0VYICQb833oMgKAgPbfxAFg8GSBRK0kLpYNoeDiEQ5DyNQ5hiAI7heCwxgmTwj7uyIkiyIBvAqMcGi6O7BimJY8j2NbciuJ496%2BO2btBOE0S%2BAk6TZIUpTOwnbThFEcQtNkXS1BPXQK2MoxTMsawLKs%2BAIFs9gHJmJyRm4dlVxnHtvMyOiAFp/KOEXxTEWgJfFBjBKYXhkjCiIIpAEovFUBLah6ZL3Ga3I80y9ARtypICp6YqjYtzJTZGaouh1%2BpZit3Ntfq3pZjt%2BJqhdg2/CNobmm9hdxpHKajJmubbwR9tSE7btew1rXNoFlE0UoOc8q4JcuHSgAOStcwCPmzDdhGQpE3NAgT3hew4c9punbbHx258fwOz9jpffaRiaFg/3zkWDhIrguA0IyaHuhDKGe7tXvQz7SG%2BnC/sIzBiKMYHeEop2IZPaHkGY6PyEEDjEcs5GEVRgShJEz6xJxmT5MU5Sl%2BJ9SyekYnKf07tdGkAYemphGbmS4tZKA7N7KEgINzeIvN%2BYeUFj5TgYszCy2lrLeWPEJbjHpLSVQ%2BcKzCk3CLJgQF6Ai3QE0OSYQpDDyAcAJWKs1bEWQMyd2usICuGKkZEI8wcpLDKoUTIvDhEVRDkZdqzt%2Br%2Bz0NIhqXsBE9SkX7HIfhVHDWUaNCQYdJqaUnPcaOC0OBx1rqeNhHDU7bV2j3X8XcToHRAOgbQwBgDJHZB0KeD0nooTQu9FSK9fr4XXpvUiaMd6gz3rRA%2BjEj6wwnPDTil9eIYAiYYzGD9sZMEks/fGb8iayE/ppb%2BFMlBUwMiAVcdNjBmRsOA1mUDOawOchhPmAsvIoI4GgjBtAZaS2wYrUKpQ1ZyiEJwpK3CUpyL4VlbRuUjI2yKjM8RPRJETMUbI9R8jHYe06usoOLQVmHMkXo0c00jFY1jktROIAxmTmbqsdOIxWQHg4JXEA1d44nnro3K8jzSDzgrLmJ4uZ2T5w0LmBIuZcyrnZJuQubyEg3LrmeB5N4kEIzMCi08Dd0VbVWM5dIzhJBAA\" rel=\"nofollow noreferrer\">Demo on Godbolt</a></p>\n<p>See also <a href=\"https://stackoverflow.com/q/46090534/995714\">How to get platform IDs from boost?</a></p>\n" }, { "answer_id": 53267287, "author": "Abraham Calf", "author_id": 7602110, "author_profile": "https://Stackoverflow.com/users/7602110", "pm_score": -1, "selected": false, "text": "<p>I wrote an <a href=\"https://github.com/abranhe/os.c\" rel=\"nofollow noreferrer\">small library</a> to get the operating system you are on, it can be installed using <a href=\"https://clibs.org\" rel=\"nofollow noreferrer\">clib</a> (The C package manager), so it is really simple to use it as a dependency for your projects.</p>\n\n<h3>Install</h3>\n\n<pre><code>$ clib install abranhe/os.c\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include \"os.h\"\n\nint main()\n{\n printf(\"%s\\n\", operating_system());\n // macOS\n return 0;\n}\n</code></pre>\n\n<p>It returns a string (<code>char*</code>) with the name of the operating system you are using, for further information about this project check it out <a href=\"https://github.com/abranhe/os.c/blob/master/readme.md#api\" rel=\"nofollow noreferrer\">the documentation on Github</a>.</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10601/" ]
I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this: ``` #ifdef OSisWindows // do Windows-specific stuff #else // do Unix-specific stuff #endif ``` Is there a way to do this? Is there a better way to do the same thing?
The **[Predefined Macros for OS](https://sourceforge.net/p/predef/wiki/OperatingSystems/)** site has a very complete list of checks. Here are a few of them, with links to where they're found: [Windows](http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx) ----------------------------------------------------------------------- `_WIN32`   Both 32 bit and 64 bit `_WIN64`   64 bit only `__CYGWIN__` Unix (Linux, \*BSD, but not Mac OS X) ------------------------------------- See this [related question](https://stackoverflow.com/questions/7063303/) on some of the pitfalls of using this check. `unix` `__unix` `__unix__` Mac OS X -------- `__APPLE__` Also used for classic `__MACH__` Both are defined; checking for either should work. [Linux](http://www.faqs.org/docs/Linux-HOWTO/GCC-HOWTO.html) ------------------------------------------------------------ `__linux__` `linux` Obsolete (not POSIX compliant) `__linux` Obsolete (not POSIX compliant) [FreeBSD](http://www.freebsd.org/doc/en/books/porters-handbook/porting-versions.html) ------------------------------------------------------------------------------------- `__FreeBSD__` Android ------- `__ANDROID__`
142,527
<p>Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text <em>selected</em>?</p>
[ { "answer_id": 7599199, "author": "Julien L", "author_id": 690236, "author_profile": "https://Stackoverflow.com/users/690236", "pm_score": 4, "selected": false, "text": "<p>Try this piece of code I wrote this morning, it will highlight a defined set of words:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;!-- Load jQuery --&gt;\n &lt;script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;!-- The javascript xontaining the plugin and the code to init the plugin --&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(function() {\n // let's init the plugin, that we called \"highlight\".\n // We will highlight the words \"hello\" and \"world\", \n // and set the input area to a widht and height of 500 and 250 respectively.\n $(\"#container\").highlight({\n words: [\"hello\",\"world\"],\n width: 500,\n height: 250\n });\n });\n\n // the plugin that would do the trick\n (function($){\n $.fn.extend({\n highlight: function() {\n // the main class\n var pluginClass = function() {};\n // init the class\n // Bootloader\n pluginClass.prototype.__init = function (element) {\n try {\n this.element = element;\n } catch (err) {\n this.error(err);\n }\n };\n // centralized error handler\n pluginClass.prototype.error = function (e) {\n // manage error and exceptions here\n //console.info(\"error!\",e);\n };\n // Centralized routing function\n pluginClass.prototype.execute = function (fn, options) {\n try {\n options = $.extend({},options);\n if (typeof(this[fn]) == \"function\") {\n var output = this[fn].apply(this, [options]);\n } else {\n this.error(\"undefined_function\");\n }\n } catch (err) {\n this.error(err);\n }\n };\n // **********************\n // Plugin Class starts here\n // **********************\n // init the component\n pluginClass.prototype.init = function (options) {\n try {\n // the element's reference ( $(\"#container\") ) is stored into \"this.element\"\n var scope = this;\n this.options = options;\n\n // just find the different elements we'll need\n this.highlighterContainer = this.element.find('#highlighterContainer');\n this.inputContainer = this.element.find('#inputContainer');\n this.textarea = this.inputContainer.find('textarea');\n this.highlighter = this.highlighterContainer.find('#highlighter');\n\n // apply the css\n this.element.css('position','relative');\n\n // place both the highlight container and the textarea container\n // on the same coordonate to superpose them.\n this.highlighterContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px dashed #ff0000',\n 'width': this.options.width,\n 'height': this.options.height,\n 'cursor': 'text'\n });\n this.inputContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px solid #000000'\n });\n // now let's make sure the highlit div and the textarea will superpose,\n // by applying the same font size and stuffs.\n // the highlighter must have a white text so it will be invisible\n this.highlighter.css({\n\n 'padding': '7px',\n 'color': '#eeeeee',\n 'background-color': '#ffffff',\n 'margin': '0px',\n 'font-size': '11px',\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n // the textarea must have a transparent background so we can see the highlight div behind it\n this.textarea.css({\n 'background-color': 'transparent',\n 'padding': '5px',\n 'margin': '0px',\n 'font-size': '11px',\n 'width': this.options.width,\n 'height': this.options.height,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n\n // apply the hooks\n this.highlighterContainer.bind('click', function() {\n scope.textarea.focus();\n });\n this.textarea.bind('keyup', function() {\n // when we type in the textarea, \n // we want the text to be processed and re-injected into the div behind it.\n scope.applyText($(this).val());\n });\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n pluginClass.prototype.applyText = function (text) {\n try {\n var scope = this;\n\n // parse the text:\n // replace all the line braks by &lt;br/&gt;, and all the double spaces by the html version &amp;nbsp;\n text = this.replaceAll(text,'\\n','&lt;br/&gt;');\n text = this.replaceAll(text,' ','&amp;nbsp;&amp;nbsp;');\n\n // replace the words by a highlighted version of the words\n for (var i=0;i&lt;this.options.words.length;i++) {\n text = this.replaceAll(text,this.options.words[i],'&lt;span style=\"background-color: #D8DFEA;\"&gt;'+this.options.words[i]+'&lt;/span&gt;');\n }\n\n // re-inject the processed text into the div\n this.highlighter.html(text);\n\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n // \"replace all\" function\n pluginClass.prototype.replaceAll = function(txt, replace, with_this) {\n return txt.replace(new RegExp(replace, 'g'),with_this);\n }\n\n // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.\n //**********************\n // process\n var fn;\n var options;\n if (arguments.length == 0) {\n fn = \"init\";\n options = {};\n } else if (arguments.length == 1 &amp;&amp; typeof(arguments[0]) == 'object') {\n fn = \"init\";\n options = $.extend({},arguments[0]);\n } else {\n fn = arguments[0];\n options = $.extend({},arguments[1]);\n }\n\n $.each(this, function(idx, item) {\n // if the component is not yet existing, create it.\n if ($(item).data('highlightPlugin') == null) {\n $(item).data('highlightPlugin', new pluginClass());\n $(item).data('highlightPlugin').__init($(item));\n }\n $(item).data('highlightPlugin').execute(fn, options);\n });\n return this;\n }\n });\n\n })(jQuery);\n\n\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n\n &lt;div id=\"container\"&gt;\n &lt;div id=\"highlighterContainer\"&gt;\n &lt;div id=\"highlighter\"&gt;\n\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"inputContainer\"&gt;\n &lt;textarea cols=\"30\" rows=\"10\"&gt;\n\n &lt;/textarea&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for.</p>\n" }, { "answer_id": 10562853, "author": "mhausi", "author_id": 1390913, "author_profile": "https://Stackoverflow.com/users/1390913", "pm_score": 0, "selected": false, "text": "<p>Improved version from above, also works with Regex and more TextArea fields:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;!-- Load jQuery --&gt;\n &lt;script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;!-- The javascript xontaining the plugin and the code to init the plugin --&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(function() {\n // let's init the plugin, that we called \"highlight\".\n // We will highlight the words \"hello\" and \"world\", \n // and set the input area to a widht and height of 500 and 250 respectively.\n $(\"#container0\").highlight({\n words: [[\"hello\",\"hello\"],[\"world\",\"world\"],[\"(\\\\[b])(.+?)(\\\\[/b])\",\"$1$2$3\"]],\n width: 500,\n height: 125,\n count:0\n });\n $(\"#container1\").highlight({\n words: [[\"hello\",\"hello\"],[\"world\",\"world\"],[\"(\\\\[b])(.+?)(\\\\[/b])\",\"$1$2$3\"]],\n width: 500,\n height: 125,\n count: 1\n });\n });\n\n // the plugin that would do the trick\n (function($){\n $.fn.extend({\n highlight: function() {\n // the main class\n var pluginClass = function() {};\n // init the class\n // Bootloader\n pluginClass.prototype.__init = function (element) {\n try {\n this.element = element;\n } catch (err) {\n this.error(err);\n }\n };\n // centralized error handler\n pluginClass.prototype.error = function (e) {\n // manage error and exceptions here\n //console.info(\"error!\",e);\n };\n // Centralized routing function\n pluginClass.prototype.execute = function (fn, options) {\n try {\n options = $.extend({},options);\n if (typeof(this[fn]) == \"function\") {\n var output = this[fn].apply(this, [options]);\n } else {\n this.error(\"undefined_function\");\n }\n } catch (err) {\n this.error(err);\n }\n };\n // **********************\n // Plugin Class starts here\n // **********************\n // init the component\n pluginClass.prototype.init = function (options) {\n try {\n // the element's reference ( $(\"#container\") ) is stored into \"this.element\"\n var scope = this;\n this.options = options;\n\n // just find the different elements we'll need\n\n this.highlighterContainer = this.element.find('#highlighterContainer'+this.options.count);\n this.inputContainer = this.element.find('#inputContainer'+this.options.count);\n this.textarea = this.inputContainer.find('textarea');\n this.highlighter = this.highlighterContainer.find('#highlighter'+this.options.count);\n\n // apply the css\n this.element.css({'position':'relative',\n 'overflow':'auto',\n 'background':'none repeat scroll 0 0 #FFFFFF',\n 'height':this.options.height+2,\n 'width':this.options.width+19,\n 'border':'1px solid'\n });\n\n // place both the highlight container and the textarea container\n // on the same coordonate to superpose them.\n this.highlighterContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '1px dashed #ff0000', \n 'width': this.options.width,\n 'height': this.options.height,\n 'cursor': 'text',\n 'z-index': '1'\n });\n this.inputContainer.css({\n 'position': 'absolute',\n 'left': '0',\n 'top': '0',\n 'border': '0px solid #000000',\n 'z-index': '2',\n 'background': 'none repeat scroll 0 0 transparent'\n });\n // now let's make sure the highlit div and the textarea will superpose,\n // by applying the same font size and stuffs.\n // the highlighter must have a white text so it will be invisible\n var isWebKit = navigator.userAgent.indexOf(\"WebKit\") &gt; -1,\n isOpera = navigator.userAgent.indexOf(\"Opera\") &gt; -1,\nisIE /*@cc_on = true @*/,\nisIE6 = isIE &amp;&amp; !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7\n\nif (isIE || isOpera){\nvar padding = '6px 5px';\n}\nelse {\nvar padding = '5px 6px';\n}\n this.highlighter.css({\n 'padding': padding,\n 'color': '#eeeeee',\n 'background-color': '#ffffff',\n 'margin': '0px',\n 'font-size': '11px' ,\n 'line-height': '12px' ,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif'\n });\n\n // the textarea must have a transparent background so we can see the highlight div behind it\n this.textarea.css({\n 'background-color': 'transparent',\n 'padding': '5px',\n 'margin': '0px',\n 'width': this.options.width,\n 'height': this.options.height,\n 'font-size': '11px',\n 'line-height': '12px' ,\n 'font-family': '\"lucida grande\",tahoma,verdana,arial,sans-serif',\n 'overflow': 'hidden',\n 'border': '0px solid #000000'\n });\n\n // apply the hooks\n this.highlighterContainer.bind('click', function() {\n scope.textarea.focus();\n });\n this.textarea.bind('keyup', function() {\n // when we type in the textarea, \n // we want the text to be processed and re-injected into the div behind it.\n scope.applyText($(this).val());\n });\n\n scope.applyText(this.textarea.val());\n\n } catch (err) {\n this.error(err)\n }\n return true;\n };\n pluginClass.prototype.applyText = function (text) {\n try {\n var scope = this;\n\n // parse the text:\n // replace all the line braks by &lt;br/&gt;, and all the double spaces by the html version &amp;nbsp;\n text = this.replaceAll(text,'\\n','&lt;br/&gt;');\n text = this.replaceAll(text,' ','&amp;nbsp;&amp;nbsp;');\n text = this.replaceAll(text,' ','&amp;nbsp;');\n\n // replace the words by a highlighted version of the words\n for (var i=0;i&lt;this.options.words.length;i++) {\n text = this.replaceAll(text,this.options.words[i][0],'&lt;span style=\"background-color: #D8DFEA;\"&gt;'+this.options.words[i][1]+'&lt;/span&gt;');\n //text = this.replaceAll(text,'(\\\\[b])(.+?)(\\\\[/b])','&lt;span style=\"font-weight:bold;background-color: #D8DFEA;\"&gt;$1$2$3&lt;/span&gt;');\n }\n\n // re-inject the processed text into the div\n this.highlighter.html(text);\n if (this.highlighter[0].clientHeight &gt; this.options.height) {\n // document.getElementById(\"highlighter0\")\n this.textarea[0].style.height=this.highlighter[0].clientHeight +19+\"px\";\n }\n else {\n this.textarea[0].style.height=this.options.height;\n }\n\n } catch (err) {\n this.error(err);\n }\n return true;\n };\n // \"replace all\" function\n pluginClass.prototype.replaceAll = function(txt, replace, with_this) {\n return txt.replace(new RegExp(replace, 'g'),with_this);\n }\n\n // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.\n //**********************\n // process\n var fn;\n var options;\n if (arguments.length == 0) {\n fn = \"init\";\n options = {};\n } else if (arguments.length == 1 &amp;&amp; typeof(arguments[0]) == 'object') {\n fn = \"init\";\n options = $.extend({},arguments[0]);\n } else {\n fn = arguments[0];\n options = $.extend({},arguments[1]);\n }\n\n $.each(this, function(idx, item) {\n // if the component is not yet existing, create it.\n if ($(item).data('highlightPlugin') == null) {\n $(item).data('highlightPlugin', new pluginClass());\n $(item).data('highlightPlugin').__init($(item));\n }\n $(item).data('highlightPlugin').execute(fn, options);\n });\n return this;\n }\n });\n\n })(jQuery);\n\n\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n &lt;div id=\"container0\"&gt;\n &lt;div id=\"highlighterContainer0\"&gt;\n &lt;div id=\"highlighter0\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"inputContainer0\"&gt;\n &lt;textarea id=\"text1\" cols=\"30\" rows=\"15\"&gt;hello world&lt;/textarea&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;h1&gt; haus &lt;/h1&gt;\n &lt;div id=\"container1\"&gt;\n &lt;div id=\"highlighterContainer1\"&gt;\n &lt;div id=\"highlighter1\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"inputContainer1\"&gt;\n &lt;textarea cols=\"30\" rows=\"15\"&gt;hipp hipp\n hurra, \n [b]ich hab es jetzt![/b]&lt;/textarea&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 18282831, "author": "Shlomi Hassid", "author_id": 1486486, "author_profile": "https://Stackoverflow.com/users/1486486", "pm_score": 2, "selected": false, "text": "<p>Easy script I wrote for this: <a href=\"http://jsfiddle.net/ZbTkJ/\" rel=\"nofollow\"><strong>Jsfiddle</strong></a></p>\n\n<p><strong>OPTIONS:</strong></p>\n\n<ol>\n<li>Optional char counter.</li>\n<li>Highlight several patterns with different colors.</li>\n<li>Regex.</li>\n<li>Collect matches to other containers.</li>\n<li>Easy styling: fonts color and face, backgrounds, border radius and lineheight.</li>\n<li><p>Ctrl+Shift for direction change.</p>\n\n<pre><code>//include function like in the fiddle!\n\n//CREATE ELEMENT:\n\ncreate_bind_textarea_highlight({ \n eleId:\"wrap_all_highlighter\",\n width:400,\n height:110,\n padding:5, \n background:'white',\n backgroundControls:'#585858',\n radius:5,\n fontFamilly:'Arial',\n fontSize:13,\n lineHeight:18,\n counterlettres:true,\n counterFont:'red',\n matchpatterns:[[\"(#[0-9A-Za-z]{0,})\",\"$1\"],[\"(@[0-9A-Za-z]{0,})\",\"$1\"]],\n hightlightsColor:['#00d2ff','#FFBF00'],\n objectsCopy:[\"copy_hashes\",\"copy_at\"]\n //PRESS Ctrl + SHIFT for direction swip!\n });\n\n //HTML EXAMPLE:\n &lt;div id=\"wrap_all_highlighter\" placer='1'&gt;&lt;/div&gt;\n &lt;div id='copy_hashes'&gt;&lt;/div&gt;&lt;!--Optional--&gt;\n &lt;div id='copy_at'&gt;&lt;/div&gt;&lt;!--Optional--&gt;\n</code></pre></li>\n</ol>\n\n<p>Have Fun!</p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text *selected*?
Try this piece of code I wrote this morning, it will highlight a defined set of words: ``` <html> <head> <title></title> <!-- Load jQuery --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <!-- The javascript xontaining the plugin and the code to init the plugin --> <script type="text/javascript"> $(function() { // let's init the plugin, that we called "highlight". // We will highlight the words "hello" and "world", // and set the input area to a widht and height of 500 and 250 respectively. $("#container").highlight({ words: ["hello","world"], width: 500, height: 250 }); }); // the plugin that would do the trick (function($){ $.fn.extend({ highlight: function() { // the main class var pluginClass = function() {}; // init the class // Bootloader pluginClass.prototype.__init = function (element) { try { this.element = element; } catch (err) { this.error(err); } }; // centralized error handler pluginClass.prototype.error = function (e) { // manage error and exceptions here //console.info("error!",e); }; // Centralized routing function pluginClass.prototype.execute = function (fn, options) { try { options = $.extend({},options); if (typeof(this[fn]) == "function") { var output = this[fn].apply(this, [options]); } else { this.error("undefined_function"); } } catch (err) { this.error(err); } }; // ********************** // Plugin Class starts here // ********************** // init the component pluginClass.prototype.init = function (options) { try { // the element's reference ( $("#container") ) is stored into "this.element" var scope = this; this.options = options; // just find the different elements we'll need this.highlighterContainer = this.element.find('#highlighterContainer'); this.inputContainer = this.element.find('#inputContainer'); this.textarea = this.inputContainer.find('textarea'); this.highlighter = this.highlighterContainer.find('#highlighter'); // apply the css this.element.css('position','relative'); // place both the highlight container and the textarea container // on the same coordonate to superpose them. this.highlighterContainer.css({ 'position': 'absolute', 'left': '0', 'top': '0', 'border': '1px dashed #ff0000', 'width': this.options.width, 'height': this.options.height, 'cursor': 'text' }); this.inputContainer.css({ 'position': 'absolute', 'left': '0', 'top': '0', 'border': '1px solid #000000' }); // now let's make sure the highlit div and the textarea will superpose, // by applying the same font size and stuffs. // the highlighter must have a white text so it will be invisible this.highlighter.css({ 'padding': '7px', 'color': '#eeeeee', 'background-color': '#ffffff', 'margin': '0px', 'font-size': '11px', 'font-family': '"lucida grande",tahoma,verdana,arial,sans-serif' }); // the textarea must have a transparent background so we can see the highlight div behind it this.textarea.css({ 'background-color': 'transparent', 'padding': '5px', 'margin': '0px', 'font-size': '11px', 'width': this.options.width, 'height': this.options.height, 'font-family': '"lucida grande",tahoma,verdana,arial,sans-serif' }); // apply the hooks this.highlighterContainer.bind('click', function() { scope.textarea.focus(); }); this.textarea.bind('keyup', function() { // when we type in the textarea, // we want the text to be processed and re-injected into the div behind it. scope.applyText($(this).val()); }); } catch (err) { this.error(err); } return true; }; pluginClass.prototype.applyText = function (text) { try { var scope = this; // parse the text: // replace all the line braks by <br/>, and all the double spaces by the html version &nbsp; text = this.replaceAll(text,'\n','<br/>'); text = this.replaceAll(text,' ','&nbsp;&nbsp;'); // replace the words by a highlighted version of the words for (var i=0;i<this.options.words.length;i++) { text = this.replaceAll(text,this.options.words[i],'<span style="background-color: #D8DFEA;">'+this.options.words[i]+'</span>'); } // re-inject the processed text into the div this.highlighter.html(text); } catch (err) { this.error(err); } return true; }; // "replace all" function pluginClass.prototype.replaceAll = function(txt, replace, with_this) { return txt.replace(new RegExp(replace, 'g'),with_this); } // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here. //********************** // process var fn; var options; if (arguments.length == 0) { fn = "init"; options = {}; } else if (arguments.length == 1 && typeof(arguments[0]) == 'object') { fn = "init"; options = $.extend({},arguments[0]); } else { fn = arguments[0]; options = $.extend({},arguments[1]); } $.each(this, function(idx, item) { // if the component is not yet existing, create it. if ($(item).data('highlightPlugin') == null) { $(item).data('highlightPlugin', new pluginClass()); $(item).data('highlightPlugin').__init($(item)); } $(item).data('highlightPlugin').execute(fn, options); }); return this; } }); })(jQuery); </script> </head> <body> <div id="container"> <div id="highlighterContainer"> <div id="highlighter"> </div> </div> <div id="inputContainer"> <textarea cols="30" rows="10"> </textarea> </div> </div> </body> </html> ``` This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for.
142,545
<p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p> <p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
[ { "answer_id": 142561, "author": "awatts", "author_id": 22847, "author_profile": "https://Stackoverflow.com/users/22847", "pm_score": 1, "selected": false, "text": "<p>This sounds like modifying the <code>__builtin__</code> name space. To do it:</p>\n\n<pre><code>import __builtin__\n__builtin__.foo = 'some-value'\n</code></pre>\n\n<p>Do not use the <code>__builtins__</code> directly (notice the extra \"s\") - apparently this can be a dictionary or a module. Thanks to ΤΖΩΤΖΙΟΥ for pointing this out, more can be found <a href=\"http://groups.google.com/group/comp.lang.python/browse_thread/thread/1907d5e660444c08/69c29c4ec0c4d3ec\" rel=\"nofollow noreferrer\" title=\"here\">here</a>.</p>\n\n<p>Now <code>foo</code> is available for use everywhere.</p>\n\n<p>I don't recommend doing this generally, but the use of this is up to the programmer.</p>\n\n<p>Assigning to it must be done as above, just setting <code>foo = 'some-other-value'</code> will only set it in the current namespace.</p>\n" }, { "answer_id": 142566, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "<p>I don't endorse this solution in any way, shape or form. But if you add a variable to the <code>__builtin__</code> module, it will be accessible as if a global from any other module that includes <code>__builtin__</code> -- which is all of them, by default.</p>\n\n<p>a.py contains</p>\n\n<pre><code>print foo\n</code></pre>\n\n<p>b.py contains</p>\n\n<pre><code>import __builtin__\n__builtin__.foo = 1\nimport a\n</code></pre>\n\n<p>The result is that \"1\" is printed.</p>\n\n<p><strong>Edit:</strong> The <code>__builtin__</code> module is available as the local symbol <code>__builtins__</code> -- that's the reason for the discrepancy between two of these answers. Also note that <code>__builtin__</code> has been renamed to <code>builtins</code> in python3.</p>\n" }, { "answer_id": 142581, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 5, "selected": false, "text": "<p>Define a module ( call it \"globalbaz\" ) and have the variables defined inside it. All the modules using this \"pseudoglobal\" should import the \"globalbaz\" module, and refer to it using \"globalbaz.var_name\"</p>\n\n<p>This works regardless of the place of the change, you can change the variable before or after the import. The imported module will use the latest value. (I tested this in a toy example)</p>\n\n<p>For clarification, globalbaz.py looks just like this:</p>\n\n<pre><code>var_name = \"my_useful_string\"\n</code></pre>\n" }, { "answer_id": 142601, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "<p>If you need a global cross-module variable maybe just simple global module-level variable will suffice. </p>\n\n<p>a.py:</p>\n\n<pre><code>var = 1\n</code></pre>\n\n<p>b.py:</p>\n\n<pre><code>import a\nprint a.var\nimport c\nprint a.var\n</code></pre>\n\n<p>c.py:</p>\n\n<pre><code>import a\na.var = 2\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>$ python b.py\n# -&gt; 1 2\n</code></pre>\n\n<p>Real-world example: <a href=\"https://github.com/django/django/blob/master/django/conf/global_settings.py\" rel=\"noreferrer\">Django's global_settings.py</a> (though in Django apps settings are used by importing the <em>object</em> <a href=\"http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code\" rel=\"noreferrer\"><code>django.conf.settings</code></a>).</p>\n" }, { "answer_id": 142669, "author": "spiv", "author_id": 22701, "author_profile": "https://Stackoverflow.com/users/22701", "pm_score": 3, "selected": false, "text": "<p>Global variables are usually a bad idea, but you can do this by assigning to <code>__builtins__</code>:</p>\n\n<pre><code>__builtins__.foo = 'something'\nprint foo\n</code></pre>\n\n<p>Also, modules themselves are variables that you can access from any module. So if you define a module called <code>my_globals.py</code>:</p>\n\n<pre><code># my_globals.py\nfoo = 'something'\n</code></pre>\n\n<p>Then you can use that from anywhere as well:</p>\n\n<pre><code>import my_globals\nprint my_globals.foo\n</code></pre>\n\n<p>Using modules rather than modifying <code>__builtins__</code> is generally a cleaner way to do globals of this sort.</p>\n" }, { "answer_id": 3269974, "author": "user394430", "author_id": 394430, "author_profile": "https://Stackoverflow.com/users/394430", "pm_score": 4, "selected": false, "text": "<p>You can pass the globals of one module to onother:</p>\n\n<p>In Module A:</p>\n\n<pre><code>import module_b\nmy_var=2\nmodule_b.do_something_with_my_globals(globals())\nprint my_var\n</code></pre>\n\n<p>In Module B:</p>\n\n<pre><code>def do_something_with_my_globals(glob): # glob is simply a dict.\n glob[\"my_var\"]=3\n</code></pre>\n" }, { "answer_id": 3911089, "author": "intuited", "author_id": 192812, "author_profile": "https://Stackoverflow.com/users/192812", "pm_score": 3, "selected": false, "text": "<p>You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.</p>\n\n<p>It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it. </p>\n" }, { "answer_id": 10158462, "author": "Brian Arsuaga", "author_id": 1038218, "author_profile": "https://Stackoverflow.com/users/1038218", "pm_score": 1, "selected": false, "text": "<p>I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.</p>\n\n<pre><code>def builtin_find(f, x, d=None):\n for i in x:\n if f(i):\n return i\n return d\n\nimport __builtin__\n__builtin__.find = builtin_find\n</code></pre>\n\n<p>Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.</p>\n\n<pre><code>find(lambda i: i &lt; 0, [1, 3, 0, -5, -10]) # Yields -5, the first negative.\n</code></pre>\n\n<p><strong>Note:</strong> You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.</p>\n" }, { "answer_id": 15035172, "author": "David Vanderschel", "author_id": 2101245, "author_profile": "https://Stackoverflow.com/users/2101245", "pm_score": 5, "selected": false, "text": "<p>I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them.</p>\n\n<p>When there is only one such module, I name it \"g\". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use \"from g import var\", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the \"g.\" serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules. </p>\n\n<p>If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment.</p>\n\n<p>Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters. </p>\n\n<p>It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.</p>\n" }, { "answer_id": 20331768, "author": "foudfou", "author_id": 421846, "author_profile": "https://Stackoverflow.com/users/421846", "pm_score": 1, "selected": false, "text": "<p>I could achieve cross-module modifiable (or <strong>mutable</strong>) variables by using a dictionary:</p>\n\n<pre><code># in myapp.__init__\nTimeouts = {} # cross-modules global mutable variables for testing purpose\nTimeouts['WAIT_APP_UP_IN_SECONDS'] = 60\n\n# in myapp.mod1\nfrom myapp import Timeouts\n\ndef wait_app_up(project_name, port):\n # wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']\n # ...\n\n# in myapp.test.test_mod1\nfrom myapp import Timeouts\n\ndef test_wait_app_up_fail(self):\n timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']\n Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3\n with self.assertRaises(hlp.TimeoutException) as cm:\n wait_app_up(PROJECT_NAME, PROJECT_PORT)\n self.assertEqual(\"Timeout while waiting for App to start\", str(cm.exception))\n Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak\n</code></pre>\n\n<p>When launching <code>test_wait_app_up_fail</code>, the actual timeout duration is 3 seconds.</p>\n" }, { "answer_id": 31737507, "author": "Jonathan", "author_id": 1689770, "author_profile": "https://Stackoverflow.com/users/1689770", "pm_score": 2, "selected": false, "text": "<p>I wanted to post an answer that there is a case where the variable won't be found.</p>\n\n<p>Cyclical imports may break the module behavior.</p>\n\n<p>For example:</p>\n\n<p>first.py</p>\n\n<pre><code>import second\nvar = 1\n</code></pre>\n\n<p>second.py</p>\n\n<pre><code>import first\nprint(first.var) # will throw an error because the order of execution happens before var gets declared.\n</code></pre>\n\n<p>main.py</p>\n\n<pre><code>import first\n</code></pre>\n\n<p>On this is example it should be obvious, but in a large code-base, this can be really confusing.</p>\n" }, { "answer_id": 49830730, "author": "robertofbaycot", "author_id": 9473313, "author_profile": "https://Stackoverflow.com/users/9473313", "pm_score": 2, "selected": false, "text": "<p>I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">http://wiki.c2.com/?GlobalVariablesAreBad</a>) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below. </p>\n\n<p>The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces. </p>\n\n<p>wall.py</p>\n\n<pre><code># Note no definition of global variables\n\nclass router:\n \"\"\" Empty class \"\"\"\n</code></pre>\n\n<p>I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.</p>\n\n<p>source.py</p>\n\n<pre><code>import wall\ndef sourcefn():\n msg = 'Hello world!'\n wall.msg = msg\n wall.router.msg = msg\n</code></pre>\n\n<p>This module imports wall and defines a single function <code>sourcefn</code> which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables <code>wall.msg</code> and <code>wall.router.message</code> are defined here for the first time in their respective namespaces.</p>\n\n<p>dest.py</p>\n\n<pre><code>import wall\ndef destfn():\n\n if hasattr(wall, 'msg'):\n print 'global: ' + wall.msg\n del wall.msg\n else:\n print 'global: ' + 'no message'\n\n if hasattr(wall.router, 'msg'):\n print 'router: ' + wall.router.msg\n del wall.router.msg\n else:\n print 'router: ' + 'no message'\n</code></pre>\n\n<p>This module defines a function <code>destfn</code> which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. <code>destfn</code> also deletes the variables once they have been displayed.</p>\n\n<p>main.py</p>\n\n<pre><code>import source, dest\n\nsource.sourcefn()\n\ndest.destfn() # variables deleted after this call\ndest.destfn()\n</code></pre>\n\n<p>This module calls the previously defined functions in sequence. After the first call to <code>dest.destfn</code> the variables <code>wall.msg</code> and <code>wall.router.msg</code> no longer exist.</p>\n\n<p>The output from the program is:</p>\n\n<p>global: Hello world!<br>\nrouter: Hello world!<br>\nglobal: no message<br>\nrouter: no message </p>\n\n<p>The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical. </p>\n\n<p>If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism. </p>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/142545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ]
The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.
I don't endorse this solution in any way, shape or form. But if you add a variable to the `__builtin__` module, it will be accessible as if a global from any other module that includes `__builtin__` -- which is all of them, by default. a.py contains ``` print foo ``` b.py contains ``` import __builtin__ __builtin__.foo = 1 import a ``` The result is that "1" is printed. **Edit:** The `__builtin__` module is available as the local symbol `__builtins__` -- that's the reason for the discrepancy between two of these answers. Also note that `__builtin__` has been renamed to `builtins` in python3.
142,633
<p>I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something?</p> <pre><code>&lt;asp:updatepanel id="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;cc1:ModalPopupExtender ID="ModalDialog" runat="server" TargetControlID="OpenDialogLinkButton" PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton" BackgroundCssClass="ModalBackground"&gt; &lt;/cc1:ModalPopupExtender&gt; &lt;asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server"&gt; ... &lt;asp:Button ID="ModalOKButton" runat="server" Text="OK" onclick="ModalOKButton_Click" /&gt; &lt;/asp:Panel&gt; &lt;/ContentTemplate&gt; &lt;/asp:updatepanel&gt; </code></pre>
[ { "answer_id": 142656, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 3, "selected": false, "text": "<p>It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click event. I tested this out by removing the </p>\n\n<pre><code>OkControlID=\"ModalOKButton\"\n</code></pre>\n\n<p>from the ModalPopupExtender tag, and the button click fires. I'll need to figure out another way to send the data to the server.</p>\n" }, { "answer_id": 383911, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 3, "selected": false, "text": "<p>I was just searching for a solution for this :)</p>\n\n<p>it appears that you can't have <strong>OkControlID</strong> assign to a control if you want to that control fires an event, just removing this property I got everything working again.</p>\n\n<p>my code (working):</p>\n\n<pre><code>&lt;asp:Panel ID=\"pnlResetPanelsView\" CssClass=\"modalPopup\" runat=\"server\" Style=\"display:none;\"&gt;\n &lt;h2&gt;\n Warning&lt;/h2&gt;\n &lt;p&gt;\n Do you really want to reset the panels to the default view?&lt;/p&gt;\n &lt;div style=\"text-align: center;\"&gt;\n &lt;asp:Button ID=\"btnResetPanelsViewOK\" Width=\"60\" runat=\"server\" Text=\"Yes\" \n CssClass=\"buttonSuperOfficeLayout\" OnClick=\"btnResetPanelsViewOK_Click\" /&gt;&amp;nbsp;\n &lt;asp:Button ID=\"btnResetPanelsViewCancel\" Width=\"60\" runat=\"server\" Text=\"No\" CssClass=\"buttonSuperOfficeLayout\" /&gt;\n &lt;/div&gt;\n&lt;/asp:Panel&gt;\n&lt;ajax:ModalPopupExtender ID=\"mpeResetPanelsView\" runat=\"server\" TargetControlID=\"btnResetView\"\n PopupControlID=\"pnlResetPanelsView\" BackgroundCssClass=\"modalBackground\" DropShadow=\"true\"\n CancelControlID=\"btnResetPanelsViewCancel\" /&gt;\n</code></pre>\n" }, { "answer_id": 487272, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 2, "selected": false, "text": "<p>None of the previous answers worked for me. I called the postback of the button on the OnOkScript event.</p>\n\n<pre><code>&lt;div&gt;\n &lt;cc1:ModalPopupExtender PopupControlID=\"Panel1\" \n ID=\"ModalPopupExtender1\"\n runat=\"server\" TargetControlID=\"LinkButton1\" OkControlID=\"Ok\" \n OnOkScript=\"__doPostBack('Ok','')\"&gt;\n &lt;/cc1:ModalPopupExtender&gt;\n\n &lt;asp:LinkButton ID=\"LinkButton1\" runat=\"server\"&gt;LinkButton&lt;/asp:LinkButton&gt; \n&lt;/div&gt; \n\n\n&lt;asp:Panel ID=\"Panel1\" runat=\"server\"&gt;\n &lt;asp:Button ID=\"Ok\" runat=\"server\" Text=\"Ok\" onclick=\"Ok_Click\" /&gt; \n&lt;/asp:Panel&gt; \n</code></pre>\n" }, { "answer_id": 975237, "author": "Johan Leino", "author_id": 83283, "author_profile": "https://Stackoverflow.com/users/83283", "pm_score": 3, "selected": false, "text": "<p>It could also be that the button needs to have <strong><em>CausesValidation=\"false\".</em></strong> That worked for me.</p>\n" }, { "answer_id": 1166869, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>Aspx</p>\n\n<pre><code>&lt;ajax:ModalPopupExtender runat=\"server\" ID=\"modalPop\" \n PopupControlID=\"pnlpopup\" \n TargetControlID=\"btnGo\"\n BackgroundCssClass=\"modalBackground\"\n DropShadow=\"true\"\n CancelControlID=\"btnCancel\" X=\"470\" Y=\"300\" /&gt;\n\n\n//Codebehind \nprotected void OkButton_Clicked(object sender, EventArgs e)\n {\n\n modalPop.Hide();\n //Do something in codebehind\n }\n</code></pre>\n\n<p><b>And don't set the OK button as OkControlID.</b></p>\n" }, { "answer_id": 2253002, "author": "Stefan Weiss", "author_id": 271949, "author_profile": "https://Stackoverflow.com/users/271949", "pm_score": 3, "selected": false, "text": "<p>Put into the Button-Control the Attribute \"UseSubmitBehavior=false\".</p>\n" }, { "answer_id": 4270107, "author": "user519205", "author_id": 519205, "author_profile": "https://Stackoverflow.com/users/519205", "pm_score": 2, "selected": false, "text": "<p>I often use a blank label as the TargetControlID. ex. <code>&lt;asp:Label ID=\"lblghost\" runat=\"server\" Text=\"\" /&gt;</code> </p>\n\n<p>I've seen two things that cause the click event not fire:<br>\n1. you have to remove the OKControlID (as others have mentioned) <br>\n2. If you are using field validators you should add CausesValidation=\"false\" on the button.</p>\n\n<p>Both scenarios behaved the same way for me. </p>\n" }, { "answer_id": 37715348, "author": "Fandango68", "author_id": 2181188, "author_profile": "https://Stackoverflow.com/users/2181188", "pm_score": 1, "selected": false, "text": "<p>I've found a way to validate a modalpopup without a postback.</p>\n\n<p>In the ModalPopupExtender I set the OnOkScript to a function e.g ValidateBeforePostBack(), then in the function I call Page_ClientValidate for the validation group I want, do a check and if it fails, keep the modalpopup showing. If it passes, I call <code>__doPostBack</code>.</p>\n\n<pre><code>function ValidateBeforePostBack(){ \n Page_ClientValidate('MyValidationGroupName'); \n if (Page_IsValid) { __doPostBack('',''); } \n else { $find('mpeBehaviourID').show(); } \n}\n</code></pre>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21461/" ]
I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something? ``` <asp:updatepanel id="UpdatePanel1" runat="server"> <ContentTemplate> <cc1:ModalPopupExtender ID="ModalDialog" runat="server" TargetControlID="OpenDialogLinkButton" PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton" BackgroundCssClass="ModalBackground"> </cc1:ModalPopupExtender> <asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server"> ... <asp:Button ID="ModalOKButton" runat="server" Text="OK" onclick="ModalOKButton_Click" /> </asp:Panel> </ContentTemplate> </asp:updatepanel> ```
Aspx ``` <ajax:ModalPopupExtender runat="server" ID="modalPop" PopupControlID="pnlpopup" TargetControlID="btnGo" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancel" X="470" Y="300" /> //Codebehind protected void OkButton_Clicked(object sender, EventArgs e) { modalPop.Hide(); //Do something in codebehind } ``` **And don't set the OK button as OkControlID.**
142,708
<p>I can't seem to find any <em>useful</em> documentation from Microsoft about how one would use the <code>Delimiter</code> and <code>InheritsFromParent</code> attributes in the <code>UserMacro</code> element when defining user Macros in <code>.vsprops</code> property sheet files for Visual Studio.</p> <p>Here's sample usage:</p> <pre><code>&lt;UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc" InheritsFromParent="TRUE" Delimiter=";"/&gt; </code></pre> <p>From the above example, I'm guessing that <em>"inherit"</em> really means <em>"a) if definition is non-empty then append delimiter, and b) append new definition"</em> where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio <code>.vsprops</code> files and macros?</p> <p>NOTE: this is <em>not</em> the same as the <code>InheritedPropertySheets</code> attribute of the <code>VisualStudioPropertySheet</code> element, for example:</p> <pre><code>&lt;VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops"&gt; </code></pre> <p>In this case <em>"inherit"</em> basically means <em>"include"</em>.</p>
[ { "answer_id": 144032, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "<p>There's documentation on the UI version of this <a href=\"http://msdn.microsoft.com/en-us/library/a2zdt10t.aspx\" rel=\"nofollow noreferrer\">here</a>.\nA lot of the XML files seem somewhat undocumented, often just giving a <a href=\"http://msdn.microsoft.com/en-us/library/ak4435es.aspx\" rel=\"nofollow noreferrer\">schema file</a>. Your guess as to how they function is pretty much right.</p>\n" }, { "answer_id": 145260, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": true, "text": "<p><em>[Answering my own question]</em></p>\n\n<p><code>InheritsFromParent</code> means prepend. To verify this, I did an experiment that reveals how User Macros work in Visual Studio 2008. Here's the setup:</p>\n\n<ul>\n<li>Project <code>p.vcproj</code> includes the property sheet file <code>d.vsprops</code> ('d' for <em>derived</em>) using the <code>InheritedPropertySheets</code> tag.</li>\n<li><code>d.vsprops</code> includes the property sheet file <code>b.vsprops</code> ('b' for <em>base</em>.)</li>\n<li><code>p.vcproj</code> also defines a Pre-Build Event which dumps the environment.</li>\n<li>Both <code>.vsprops</code> files contain User Macro definitions.</li>\n</ul>\n\n<p><strong>b.vsprops</strong></p>\n\n<pre><code>...\n&lt;UserMacro Name=\"NOENV\" Value=\"B\"/&gt;\n&lt;UserMacro Name=\"OVERRIDE\" Value=\"B\" PerformEnvironmentSet=\"true\"/&gt;\n&lt;UserMacro Name=\"PREPEND\" Value=\"B\" PerformEnvironmentSet=\"true\"/&gt;\n...\n</code></pre>\n\n<p><strong>d.vsprops</strong></p>\n\n<pre><code>...\n&lt;VisualStudioPropertySheet ... InheritedPropertySheets=\".\\b.vsprops\"&gt;\n&lt;UserMacro Name=\"ENV\" Value=\"$(NOENV)\" PerformEnvironmentSet=\"true\"/&gt;\n&lt;UserMacro Name=\"OVERRIDE\" Value=\"D\" PerformEnvironmentSet=\"true\"/&gt;\n&lt;UserMacro Name=\"PREPEND\" Value=\"D\" InheritsFromParent=\"true\"\n Delimiter=\"+\" PerformEnvironmentSet=\"true\"/&gt;\n...\n</code></pre>\n\n<p><strong>p.vcproj</strong></p>\n\n<pre><code>...\n&lt;Configuration ... InheritedPropertySheets=\".\\d.vsprops\"&gt;\n&lt;Tool Name=\"VCPreBuildEventTool\" CommandLine=\"set | sort\"/&gt;\n...\n</code></pre>\n\n<p><strong>build output</strong></p>\n\n<pre><code>...\nENV=B\nOVERRIDE=D\nPREPEND=D+B\n...\n</code></pre>\n\n<p>From these results we can conclude the following:</p>\n\n<ol>\n<li><code>PerformEnvironmentSet=\"true\"</code> is necessary for User Macros to be defined in the environment used for build events. Proof: <code>NOENV</code> not shown in build output.</li>\n<li>User Macros are <strong><em>always</em></strong> inherited from included property sheets regardless of <code>PerformEnvironmentSet</code> or <code>InheritsFromParent</code>. Proof: in <code>b.vsprops</code>, <code>NOENV</code> is not set in the environment and in <code>d.vsprops</code> it is used without need of <code>InheritsFromParent</code>.</li>\n<li>Simple redefinition of a User Macro <strong><em>overrides</em></strong> any previous definition. Proof: <code>OVERRIDE</code> is set to <code>D</code> although it was earlier defined as <code>B</code>.</li>\n<li>Redefinition of a User Macro with <code>InheritsFromParent=\"true\"</code> <strong><em>prepends</em></strong> the new definition to any previous definition, separated by a specified <code>Delimiter</code>. Proof: <code>PREPEND</code> is set to <code>D+B</code> (not <code>D</code> or <code>B+D</code>.)</li>\n</ol>\n\n<p>Here are some additional resources I found for explanation of Visual Studio <code>.vsprops</code> files and related topics, it's from a few years back but it is still helpful:</p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/02/03/66965.aspx\" rel=\"noreferrer\">understanding the VC project system part I: files and tools</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/02/04/67705.aspx\" rel=\"noreferrer\">understanding the VC project system part II: configurations and the project property pages dialog</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/02/05/68366.aspx\" rel=\"noreferrer\">understanding the VC project system part III: macros, environment variables and sharing</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/02/09/70335.aspx\" rel=\"noreferrer\">understanding the VC project system part IV: properties and property inheritance</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/02/13/72844.aspx\" rel=\"noreferrer\">understanding the VC project system part V: building, tools and dependencies</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/03/02/83035.aspx\" rel=\"noreferrer\">understanding the VC project system part VI: custom build steps and build events</a></p>\n\n<p><a href=\"http://blogs.msdn.com/josh_/archive/2004/05/18/134638.aspx\" rel=\"noreferrer\">understanding the VC project system part VII: \"makefile\" projects and (re-)using environments</a></p>\n" }, { "answer_id": 5003855, "author": "P. Copissa", "author_id": 617786, "author_profile": "https://Stackoverflow.com/users/617786", "pm_score": 0, "selected": false, "text": "<p>It is not the whole story. </p>\n\n<ul>\n<li>Delimiters are not inherited. Only\nthe list of items they delimit are inherited: The same user macros can have different delimiters in different property sheets but only the last encountered delimiter is used. (I write \"last encountered\" because at project level, we cannot specify a delimiter and what gets used there is the last property sheet that specified inheritance for that macro)</li>\n<li>Delimiters works only if made of a\nsingle character. A delimiter longer\nthan one character may have its\nfirst and/or last character stripped\nin some cases, in a mistaken attempt\nto \"join\" the list of values.</li>\n<li>$(Inherit) appears to work inside\nuser macros. Like for aggregate<br>\nproperties, it works as a placeholder for<br>\nthe parent's values, and it can appear multiple times. When no $(Inherit) is found, it is implied at the beginning if the inheritance flag is set.</li>\n<li>$(NoInherit) also appears to work in user's macros(makes VC behaves as if the checkbox was unticked).</li>\n<li>User macros (and some built-ins) appears\nto work when used for constructing a property sheet's path (VC's own project converter uses that feature). The value\ntaken by user's macros in this situation is not\nalways intuitive, though, especially if it gets redefined in other included property sheets.</li>\n<li>In general, what gets \"inherited\" or concatenated are formulae and not values (ie. you cannot use a user macro to take a snapshot the local value of (say) $(IntDir) in a property sheet and hope to \"bubble up\" that value through inheritance, because what gets inherited is actually the formula \"$(IntDir)\", whose value will eventually be resolved at the project/config/file level).</li>\n<li>A property sheet already loaded is ignored (seem to avoid that the same property sheet has its user macros aggregated twice)</li>\n<li>Both \"/\" and \"\\\" appear to work in\nproperty sheet paths (and in most\nplaces where VS expects a path).</li>\n<li>A property sheet path starting with\n\"/\" (after macros have been resolved) is assumed to be in \"./\", where '.' is the location of the\ncalling sheet/project). Same if the path does not start with \"./\", \"../\" or \"drive:/\" (dunno about UNC).</li>\n</ul>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
I can't seem to find any *useful* documentation from Microsoft about how one would use the `Delimiter` and `InheritsFromParent` attributes in the `UserMacro` element when defining user Macros in `.vsprops` property sheet files for Visual Studio. Here's sample usage: ``` <UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc" InheritsFromParent="TRUE" Delimiter=";"/> ``` From the above example, I'm guessing that *"inherit"* really means *"a) if definition is non-empty then append delimiter, and b) append new definition"* where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio `.vsprops` files and macros? NOTE: this is *not* the same as the `InheritedPropertySheets` attribute of the `VisualStudioPropertySheet` element, for example: ``` <VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops"> ``` In this case *"inherit"* basically means *"include"*.
*[Answering my own question]* `InheritsFromParent` means prepend. To verify this, I did an experiment that reveals how User Macros work in Visual Studio 2008. Here's the setup: * Project `p.vcproj` includes the property sheet file `d.vsprops` ('d' for *derived*) using the `InheritedPropertySheets` tag. * `d.vsprops` includes the property sheet file `b.vsprops` ('b' for *base*.) * `p.vcproj` also defines a Pre-Build Event which dumps the environment. * Both `.vsprops` files contain User Macro definitions. **b.vsprops** ``` ... <UserMacro Name="NOENV" Value="B"/> <UserMacro Name="OVERRIDE" Value="B" PerformEnvironmentSet="true"/> <UserMacro Name="PREPEND" Value="B" PerformEnvironmentSet="true"/> ... ``` **d.vsprops** ``` ... <VisualStudioPropertySheet ... InheritedPropertySheets=".\b.vsprops"> <UserMacro Name="ENV" Value="$(NOENV)" PerformEnvironmentSet="true"/> <UserMacro Name="OVERRIDE" Value="D" PerformEnvironmentSet="true"/> <UserMacro Name="PREPEND" Value="D" InheritsFromParent="true" Delimiter="+" PerformEnvironmentSet="true"/> ... ``` **p.vcproj** ``` ... <Configuration ... InheritedPropertySheets=".\d.vsprops"> <Tool Name="VCPreBuildEventTool" CommandLine="set | sort"/> ... ``` **build output** ``` ... ENV=B OVERRIDE=D PREPEND=D+B ... ``` From these results we can conclude the following: 1. `PerformEnvironmentSet="true"` is necessary for User Macros to be defined in the environment used for build events. Proof: `NOENV` not shown in build output. 2. User Macros are ***always*** inherited from included property sheets regardless of `PerformEnvironmentSet` or `InheritsFromParent`. Proof: in `b.vsprops`, `NOENV` is not set in the environment and in `d.vsprops` it is used without need of `InheritsFromParent`. 3. Simple redefinition of a User Macro ***overrides*** any previous definition. Proof: `OVERRIDE` is set to `D` although it was earlier defined as `B`. 4. Redefinition of a User Macro with `InheritsFromParent="true"` ***prepends*** the new definition to any previous definition, separated by a specified `Delimiter`. Proof: `PREPEND` is set to `D+B` (not `D` or `B+D`.) Here are some additional resources I found for explanation of Visual Studio `.vsprops` files and related topics, it's from a few years back but it is still helpful: [understanding the VC project system part I: files and tools](http://blogs.msdn.com/josh_/archive/2004/02/03/66965.aspx) [understanding the VC project system part II: configurations and the project property pages dialog](http://blogs.msdn.com/josh_/archive/2004/02/04/67705.aspx) [understanding the VC project system part III: macros, environment variables and sharing](http://blogs.msdn.com/josh_/archive/2004/02/05/68366.aspx) [understanding the VC project system part IV: properties and property inheritance](http://blogs.msdn.com/josh_/archive/2004/02/09/70335.aspx) [understanding the VC project system part V: building, tools and dependencies](http://blogs.msdn.com/josh_/archive/2004/02/13/72844.aspx) [understanding the VC project system part VI: custom build steps and build events](http://blogs.msdn.com/josh_/archive/2004/03/02/83035.aspx) [understanding the VC project system part VII: "makefile" projects and (re-)using environments](http://blogs.msdn.com/josh_/archive/2004/05/18/134638.aspx)
142,740
<p>I want to do something like the following in spring:</p> <pre><code>&lt;beans&gt; ... &lt;bean id="bean1" ... /&gt; &lt;bean id="bean2"&gt; &lt;property name="propName" value="bean1.foo" /&gt; ... </code></pre> <p>I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.</p>
[ { "answer_id": 142765, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": -1, "selected": false, "text": "<p>I think you have to inject bean1, then get <code>foo</code> manually because of a timing issue. When does the framework resolve the value of the target bean?</p>\n\n<p>You could create a pointer bean and configure that.</p>\n\n<pre><code>class SpringRef {\n private String targetProperty;\n private Object targetBean;\n\n //getters/setters\n\n public Object getValue() {\n //resolve the value of the targetProperty on targetBean. \n }\n}\n</code></pre>\n\n<p><a href=\"http://commons.apache.org/beanutils/\" rel=\"nofollow noreferrer\">Common-BeanUtils</a> should be helpful.</p>\n" }, { "answer_id": 142784, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 3, "selected": false, "text": "<p>You need to use <a href=\"http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/PropertyPathFactoryBean.html\" rel=\"noreferrer\">PropertyPathFactoryBean</a>:</p>\n\n<pre>\n &lt;bean id=\"bean2\" depends-on=\"bean1\"&gt;\n &lt;property name=\"propName\"&gt;\n &lt;bean class=\"org.springframework.beans.factory.config.PropertyPathFactoryBean\"&gt;\n &lt;property name=\"targetBeanName\" value=\"bean1\"/&gt;\n &lt;property name=\"propertyPath\" value=\"foo\"/&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n &lt;/bean&gt;\n</pre>\n" }, { "answer_id": 142796, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 4, "selected": true, "text": "<p>What I understood:</p>\n\n<ol>\n<li>You have a bean (bean1) with a\nproperty called \"foo\"</li>\n<li>You have another bean (bean2) with a\nproperty named \"propName\", wich also\nhas to have the same \"foo\" that in\nbean1.</li>\n</ol>\n\n<p>why not doing this:</p>\n\n<pre><code>&lt;beans&gt;\n...\n&lt;bean id=\"foo\" class=\"foopackage.foo\"/&gt;\n&lt;bean id=\"bean1\" class=\"foopackage.bean1\"&gt;\n &lt;property name=\"foo\" ref=\"foo\"/&gt;\n&lt;/bean&gt; \n&lt;bean id=\"bean2\" class=\"foopackage.bean2\"&gt;\n &lt;property name=\"propName\" ref=\"foo\"/&gt;\n&lt;/bean&gt;\n....\n&lt;/beans&gt;\n</code></pre>\n\n<p>Doing this, your bean2 is not coupled to bean1 like in your example. You can change bean1 and bean2 without affecting each other.</p>\n\n<p>If you <strong>REALLY</strong> need to do the injection you proposed, you can use:</p>\n\n<pre><code>&lt;util:property-path id=\"propName\" path=\"bean1.foo\"/&gt;\n</code></pre>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
I want to do something like the following in spring: ``` <beans> ... <bean id="bean1" ... /> <bean id="bean2"> <property name="propName" value="bean1.foo" /> ... ``` I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.
What I understood: 1. You have a bean (bean1) with a property called "foo" 2. You have another bean (bean2) with a property named "propName", wich also has to have the same "foo" that in bean1. why not doing this: ``` <beans> ... <bean id="foo" class="foopackage.foo"/> <bean id="bean1" class="foopackage.bean1"> <property name="foo" ref="foo"/> </bean> <bean id="bean2" class="foopackage.bean2"> <property name="propName" ref="foo"/> </bean> .... </beans> ``` Doing this, your bean2 is not coupled to bean1 like in your example. You can change bean1 and bean2 without affecting each other. If you **REALLY** need to do the injection you proposed, you can use: ``` <util:property-path id="propName" path="bean1.foo"/> ```
142,750
<p>I'm trying to get either CreateProcess or CreateProcessW to execute a process with a name &lt; MAX&#95;PATH characters but in a path that's greater than MAX&#95;PATH characters. According to the docs at: <a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms682425.aspx</a></a>, I need to make sure lpApplicationName isn't NULL and then lpCommandLine can be up to 32,768 characters.</p> <p>I tried that, but I get ERROR&#95;PATH&#95;NOT&#95;FOUND.</p> <p>I changed to CreateProcessW, but still get the same error. When I prefix lpApplicationName with \\?\ as described in <a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></a> when calling CreateProcessW I get a different error that makes me think I'm a bit closer: ERROR&#95;SXS&#95;CANT&#95;GEN&#95;ACTCTX.</p> <p>My call to CreateProcessW is:</p> <p><code> CreateProcessW(w&#95;argv0,arg_string,NULL,NULL,0,NULL,NULL,&amp;si,&amp;ipi); </code></p> <p>where w_argv0 is <code>\\?\&lt;long absolute path&gt;\foo.exe.</code></p> <p>arg_string contains "&lt;long absolute path&gt;\foo.exe" foo </p> <p>si is set as follows:</p> <pre> memset(&si,0,sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;> </pre> <p>and pi is empty, as in:</p> <pre> memset(&pi,0,sizeof(pi)); </pre> <p>I looked in the system event log and there's a new entry each time I try this with event id 59, source SideBySide: Generate Activation Context failed for .Manifest. Reference error message: The operation completed successfully.</p> <p>The file I'm trying to execute runs fine in a path &lt; MAX_PATH characters.</p> <p>To clarify, no one component of &lt;long absolute path&gt; is greater than MAX&#95;PATH characters. The name of the executable itself certainly isn't, even with .manifest on the end. But, the entire path together is greater than MAX&#95;PATH characters long.</p> <p>I get the same error whether I embed its manifest or not. The manifest is named foo.exe.manifest and lives in the same directory as the executable when it's not embedded. It contains:</p> <pre> &lt;?xml version='1.0' encoding='UTF-8' standalone='yes'?> &lt;assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> &lt;dependency> &lt;dependentAssembly> &lt;assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> &lt;/dependentAssembly> &lt;/dependency> &lt;/assembly> </pre> <p>Anyone know how to get this to work? Possibly:</p> <ul> <li><p>some other way to call CreateProcess or CreateProcessW to execute a process in a path > MAX_PATH characters</p></li> <li><p>something I can do in the manifest file</p></li> </ul> <p>I'm building with Visual Studio 2005 on XP SP2 and running native.</p> <p>Thanks for your help.</p>
[ { "answer_id": 143399, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 1, "selected": false, "text": "<p>I don't see any reference in the CreateProcess documentation saying that the '\\\\?\\' syntax is valid for the module name. The page on \"Naming a File or Directory\" also does not state that CreateProcess supports it, while functions such as CreateFile link to the \"Naming a File\" page.</p>\n\n<p>I <em>do</em> see that you can't use a module name longer than <code>MAX_PATH</code> in <code>lpCommandLine</code>, which suggests that CreateProcess does not support extra long filenames. The error message also suggests that an error is occurring while attempting to append \".manifest\" to your application path (that is, the length is now exceeding MAX_PATH).</p>\n\n<p>GetShortPathName() may be of some help here, though it does not guarantee to return a name less than MAX_PATH (it does explicitly state that '\\\\?\\' syntax is valid, though). Otherwise, you could try adjusting the <code>PATH</code> environment variable and passing it to CreateProcess() in <code>lpEnvironment</code>. Or you could use SetCurrentDirectory() and pass only the executable name.</p>\n" }, { "answer_id": 144932, "author": "dbyron", "author_id": 9572, "author_profile": "https://Stackoverflow.com/users/9572", "pm_score": 2, "selected": false, "text": "<p>Embedding the manifest and using GetShortPathNameW did it for me. One or the other on their own wasn't enough.</p>\n\n<p>Before calling CreateProcessW using the \\\\?-prefixed absolute path name of the process to execute as the first argument, I check:</p>\n\n<pre>\nwchar&#95;t *w_argv0;\nwchar&#95;t *w_short_argv0;\n\n...\n\nif (wcslen(w&#95;argv0) >= MAX&#95;PATH)\n{\n num&#95;chars = GetShortPathNameW(w&#95;argv0,NULL,0);\n if (num&#95;chars == 0) {\n syslog(LOG&#95;ERR,\"GetShortPathName(%S) to get size failed (%d)\",<br/> w&#95;argv0,GetLastError());\n /*\n ** Might as well keep going and try with the long name\n */\n } else {\n w&#95;short&#95;argv0 = malloc(num&#95;chars * sizeof(wchar&#95;t));\n memset(w&#95;short&#95;argv0,0,num&#95;chars * sizeof(wchar&#95;t));\n if (GetShortPathNameW(w&#95;argv0,w&#95;short&#95;argv0,num&#95;chars) == 0) {\n syslog(LOG&#95;ERR,\"GetShortPathName(%S) failed (%d)\",w&#95;argv0,<br/> GetLastError());\n free(w&#95;short&#95;argv0);\n w&#95;short&#95;argv0 = NULL;\n } else {\n syslog(LOG_DEBUG,\"using short name %S for %S\",w&#95;short&#95;argv0,<br/> w&#95;argv0);\n }\n }\n}\n</pre>\n\n<p>and then call CreateProcessW(w&#95;short&#95;argv0 ? w&#95;short&#95;argv0 : w&#95;argv0...);</p>\n\n<p>remembering to free(w&#95;short&#95;argv0); afterwards.</p>\n\n<p>This may not solve every case, but it lets me spawn more child processes than I could before.</p>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9572/" ]
I'm trying to get either CreateProcess or CreateProcessW to execute a process with a name < MAX\_PATH characters but in a path that's greater than MAX\_PATH characters. According to the docs at: [<http://msdn.microsoft.com/en-us/library/ms682425.aspx>](http://msdn.microsoft.com/en-us/library/ms682425.aspx), I need to make sure lpApplicationName isn't NULL and then lpCommandLine can be up to 32,768 characters. I tried that, but I get ERROR\_PATH\_NOT\_FOUND. I changed to CreateProcessW, but still get the same error. When I prefix lpApplicationName with \\?\ as described in [<http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx>](http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx) when calling CreateProcessW I get a different error that makes me think I'm a bit closer: ERROR\_SXS\_CANT\_GEN\_ACTCTX. My call to CreateProcessW is: `CreateProcessW(w_argv0,arg_string,NULL,NULL,0,NULL,NULL,&si,&ipi);` where w\_argv0 is `\\?\<long absolute path>\foo.exe.` arg\_string contains "<long absolute path>\foo.exe" foo si is set as follows: ``` memset(&si,0,sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;> ``` and pi is empty, as in: ``` memset(π,0,sizeof(pi)); ``` I looked in the system event log and there's a new entry each time I try this with event id 59, source SideBySide: Generate Activation Context failed for .Manifest. Reference error message: The operation completed successfully. The file I'm trying to execute runs fine in a path < MAX\_PATH characters. To clarify, no one component of <long absolute path> is greater than MAX\_PATH characters. The name of the executable itself certainly isn't, even with .manifest on the end. But, the entire path together is greater than MAX\_PATH characters long. I get the same error whether I embed its manifest or not. The manifest is named foo.exe.manifest and lives in the same directory as the executable when it's not embedded. It contains: ``` <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> ``` Anyone know how to get this to work? Possibly: * some other way to call CreateProcess or CreateProcessW to execute a process in a path > MAX\_PATH characters * something I can do in the manifest file I'm building with Visual Studio 2005 on XP SP2 and running native. Thanks for your help.
Embedding the manifest and using GetShortPathNameW did it for me. One or the other on their own wasn't enough. Before calling CreateProcessW using the \\?-prefixed absolute path name of the process to execute as the first argument, I check: ``` wchar_t *w_argv0; wchar_t *w_short_argv0; ... if (wcslen(w_argv0) >= MAX_PATH) { num_chars = GetShortPathNameW(w_argv0,NULL,0); if (num_chars == 0) { syslog(LOG_ERR,"GetShortPathName(%S) to get size failed (%d)", w_argv0,GetLastError()); /* ** Might as well keep going and try with the long name */ } else { w_short_argv0 = malloc(num_chars * sizeof(wchar_t)); memset(w_short_argv0,0,num_chars * sizeof(wchar_t)); if (GetShortPathNameW(w_argv0,w_short_argv0,num_chars) == 0) { syslog(LOG_ERR,"GetShortPathName(%S) failed (%d)",w_argv0, GetLastError()); free(w_short_argv0); w_short_argv0 = NULL; } else { syslog(LOG_DEBUG,"using short name %S for %S",w_short_argv0, w_argv0); } } } ``` and then call CreateProcessW(w\_short\_argv0 ? w\_short\_argv0 : w\_argv0...); remembering to free(w\_short\_argv0); afterwards. This may not solve every case, but it lets me spawn more child processes than I could before.
142,772
<p>What is the difference between the Project and SVN workingDirectory Config Blocks in CruiseControl.NET?</p> <p>I setup Subversion and now I'm working on CruiseControl.NET and noticed there are two workingDirectory blocks in the config files. I've looked through their google groups and documentation and maybe I missed something but I did not see a clear example of how they are used during the build process.</p> <p>The partial config below is taken from their Project file example page <a href="http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server" rel="nofollow noreferrer">http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server</a></p> <pre><code>&lt;cruisecontrol&gt; &lt;queue name="Q1" duplicates="ApplyForceBuildsReplace"/&gt; &lt;project name="MyProject" queue="Q1" queuePriority="1"&gt; &lt;webURL&gt;http://mybuildserver/ccnet/&lt;/webURL&gt; &lt;workingDirectory&gt;C:\Integration\MyProject\WorkingDirectory&lt;/workingDirectory&gt; &lt;artifactDirectory&gt;C:\Integration\MyProject\Artifacts&lt;/artifactDirectory&gt; &lt;modificationDelaySeconds&gt;10&lt;/modificationDelaySeconds&gt; &lt;triggers&gt; &lt;intervalTrigger seconds="60" name="continuous" /&gt; &lt;/triggers&gt; &lt;sourcecontrol type="cvs"&gt; &lt;executable&gt;c:\putty\cvswithplinkrsh.bat&lt;/executable&gt; &lt;workingDirectory&gt;c:\fromcvs\myrepo&lt;/workingDirectory&gt; &lt;cvsroot&gt;:ext:mycvsserver:/cvsroot/myrepo&lt;/cvsroot&gt; &lt;/sourcecontrol&gt; &lt;/project&gt; &lt;/cruisecontrol&gt; </code></pre>
[ { "answer_id": 142795, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block\" rel=\"nofollow noreferrer\">Project Configuration Block</a> and <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Subversion+Source+Control+Block\" rel=\"nofollow noreferrer\">Subversion Source Control Block</a>. The Project working directory is for the project as a whole, The Source Control working directory designates where the source will be <em>checked out</em> to. This may be different (if so, likely a sub-directory) of your project working directory.</p>\n" }, { "answer_id": 142803, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": true, "text": "<p>I think the project working directory is used as the root folder for all commands in the CruiseControl block. So if I have a Nant task/script with relative folders, it will be appended to this root folder for actual execution. </p>\n\n<blockquote>\n <p>The Working Directory for the project\n (this is used by other blocks).\n Relative paths are relative to a\n directory called the project Name in\n the directory where the\n CruiseControl.NET server was launched\n from. The Working Directory is meant\n to contain the checked out version of\n the project under integration.</p>\n</blockquote>\n\n<p>The SourceControl working directory is where your SVN or CVS will check out files, when invoked. So this would be the 'Src' subdirectory under your project folder for instance.</p>\n\n<blockquote>\n <p>The folder that the source has been\n checked out into.</p>\n</blockquote>\n\n<p>Quoted Sources:</p>\n\n<ul>\n<li><a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block\" rel=\"nofollow noreferrer\">http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block</a></li>\n<li><a href=\"http://confluence.public.thoughtworks.org/display/CCNET/CVS+Source+Control+Block\" rel=\"nofollow noreferrer\">http://confluence.public.thoughtworks.org/display/CCNET/CVS+Source+Control+Block</a></li>\n</ul>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
What is the difference between the Project and SVN workingDirectory Config Blocks in CruiseControl.NET? I setup Subversion and now I'm working on CruiseControl.NET and noticed there are two workingDirectory blocks in the config files. I've looked through their google groups and documentation and maybe I missed something but I did not see a clear example of how they are used during the build process. The partial config below is taken from their Project file example page <http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server> ``` <cruisecontrol> <queue name="Q1" duplicates="ApplyForceBuildsReplace"/> <project name="MyProject" queue="Q1" queuePriority="1"> <webURL>http://mybuildserver/ccnet/</webURL> <workingDirectory>C:\Integration\MyProject\WorkingDirectory</workingDirectory> <artifactDirectory>C:\Integration\MyProject\Artifacts</artifactDirectory> <modificationDelaySeconds>10</modificationDelaySeconds> <triggers> <intervalTrigger seconds="60" name="continuous" /> </triggers> <sourcecontrol type="cvs"> <executable>c:\putty\cvswithplinkrsh.bat</executable> <workingDirectory>c:\fromcvs\myrepo</workingDirectory> <cvsroot>:ext:mycvsserver:/cvsroot/myrepo</cvsroot> </sourcecontrol> </project> </cruisecontrol> ```
I think the project working directory is used as the root folder for all commands in the CruiseControl block. So if I have a Nant task/script with relative folders, it will be appended to this root folder for actual execution. > > The Working Directory for the project > (this is used by other blocks). > Relative paths are relative to a > directory called the project Name in > the directory where the > CruiseControl.NET server was launched > from. The Working Directory is meant > to contain the checked out version of > the project under integration. > > > The SourceControl working directory is where your SVN or CVS will check out files, when invoked. So this would be the 'Src' subdirectory under your project folder for instance. > > The folder that the source has been > checked out into. > > > Quoted Sources: * <http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block> * <http://confluence.public.thoughtworks.org/display/CCNET/CVS+Source+Control+Block>
142,789
<p>From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). </p> <p>I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.</p>
[ { "answer_id": 142792, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function <code>on_event()</code> and data pointers to a framework function <code>watch_events()</code> (for example). When an event happens, your function is called with your data and some event-specific data.</p>\n\n<p>Callbacks are also used in GUI programming. The <a href=\"http://library.gnome.org/devel/gtk-tutorial/stable/\" rel=\"nofollow noreferrer\">GTK+ tutorial</a> has a nice section on the <a href=\"http://library.gnome.org/devel/gtk-tutorial/stable/x159.html\" rel=\"nofollow noreferrer\">theory of signals and callbacks</a>.</p>\n" }, { "answer_id": 142793, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 0, "selected": false, "text": "<p>Usually this can be done by using a function pointer, that is a special variable that points to the memory location of a function. You can then use this to call the function with specific arguments. So there will probably be a function that sets the callback function. This will accept a function pointer and then store that address somewhere where it can be used. After that when the specified event is triggered, it will call that function.</p>\n" }, { "answer_id": 142798, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 2, "selected": false, "text": "<p>This <a href=\"http://en.wikipedia.org/wiki/Callback_(computer_science)\" rel=\"nofollow noreferrer\">wikipedia article</a> has an example in C.</p>\n\n<p>A good example is that new modules written to augment the Apache Web server register with the main apache process by passing them function pointers so those functions are called back to process web page requests.</p>\n" }, { "answer_id": 142809, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 9, "selected": true, "text": "<p>There is no \"callback\" in C - not more than any other generic programming concept.</p>\n\n<p>They're implemented using function pointers. Here's an example:</p>\n\n<pre><code>void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))\n{\n for (size_t i=0; i&lt;arraySize; i++)\n array[i] = getNextValue();\n}\n\nint getNextRandomValue(void)\n{\n return rand();\n}\n\nint main(void)\n{\n int myarray[10];\n populate_array(myarray, 10, getNextRandomValue);\n ...\n}\n</code></pre>\n\n<p>Here, the <code>populate_array</code> function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback <code>getNextRandomValue</code>, which returns a random-ish value, and passed a pointer to it to <code>populate_array</code>. <code>populate_array</code> will call our callback function 10 times and assign the returned values to the elements in the given array.</p>\n" }, { "answer_id": 147241, "author": "Russell Bryant", "author_id": 23224, "author_profile": "https://Stackoverflow.com/users/23224", "pm_score": 7, "selected": false, "text": "<p>Here is an example of callbacks in C.</p>\n\n<p>Let's say you want to write some code that allows registering callbacks to be called when some event occurs.</p>\n\n<p>First define the type of function used for the callback:</p>\n\n<pre><code>typedef void (*event_cb_t)(const struct event *evt, void *userdata);\n</code></pre>\n\n<p>Now, define a function that is used to register a callback:</p>\n\n<pre><code>int event_cb_register(event_cb_t cb, void *userdata);\n</code></pre>\n\n<p>This is what code would look like that registers a callback:</p>\n\n<pre><code>static void my_event_cb(const struct event *evt, void *data)\n{\n /* do stuff and things with the event */\n}\n\n...\n event_cb_register(my_event_cb, &amp;my_custom_data);\n...\n</code></pre>\n\n<p>In the internals of the event dispatcher, the callback may be stored in a struct that looks something like this:</p>\n\n<pre><code>struct event_cb {\n event_cb_t cb;\n void *data;\n};\n</code></pre>\n\n<p>This is what the code looks like that executes a callback.</p>\n\n<pre><code>struct event_cb *callback;\n\n...\n\n/* Get the event_cb that you want to execute */\n\ncallback-&gt;cb(event, callback-&gt;data);\n</code></pre>\n" }, { "answer_id": 13580715, "author": "Gautham Kantharaju", "author_id": 1855959, "author_profile": "https://Stackoverflow.com/users/1855959", "pm_score": 5, "selected": false, "text": "<p>A simple call back program. Hope it answers your question.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;string.h&gt;\n#include \"../../common_typedef.h\"\n\ntypedef void (*call_back) (S32, S32);\n\nvoid test_call_back(S32 a, S32 b)\n{\n printf(\"In call back function, a:%d \\t b:%d \\n\", a, b);\n}\n\nvoid call_callback_func(call_back back)\n{\n S32 a = 5;\n S32 b = 7;\n\n back(a, b);\n}\n\nS32 main(S32 argc, S8 *argv[])\n{\n S32 ret = SUCCESS;\n\n call_back back;\n\n back = test_call_back;\n\n call_callback_func(back);\n\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 32429847, "author": "daemondave", "author_id": 4603962, "author_profile": "https://Stackoverflow.com/users/4603962", "pm_score": 4, "selected": false, "text": "<p>A callback function in C is the equivalent of a function parameter / variable assigned to be used within another function.<a href=\"https://en.wikipedia.org/wiki/Callback_%28computer_programming%29\" rel=\"noreferrer\">Wiki Example</a></p>\n\n<p>In the code below, </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n/* The calling function takes a single callback as a parameter. */\nvoid PrintTwoNumbers(int (*numberSource)(void)) {\n printf(\"%d and %d\\n\", numberSource(), numberSource());\n}\n\n/* A possible callback */\nint overNineThousand(void) {\n return (rand() % 1000) + 9001;\n}\n\n/* Another possible callback. */\nint meaningOfLife(void) {\n return 42;\n}\n\n/* Here we call PrintTwoNumbers() with three different callbacks. */\nint main(void) {\n PrintTwoNumbers(&amp;rand);\n PrintTwoNumbers(&amp;overNineThousand);\n PrintTwoNumbers(&amp;meaningOfLife);\n return 0;\n}\n</code></pre>\n\n<p>The function (*numberSource) inside the function call PrintTwoNumbers is a function to \"call back\" / execute from inside PrintTwoNumbers as dictated by the code as it runs. </p>\n\n<p>So if you had something like a pthread function you could assign another function to run inside the loop from its instantiation.</p>\n" }, { "answer_id": 49072888, "author": "Richard Chambers", "author_id": 1466970, "author_profile": "https://Stackoverflow.com/users/1466970", "pm_score": 3, "selected": false, "text": "<p>A callback in C is a function that is provided to another function to &quot;call back to&quot; at some point when the other function is doing its task.</p>\n<p>There are <a href=\"https://en.wikipedia.org/wiki/Callback_(computer_programming)\" rel=\"nofollow noreferrer\">two ways that a callback is used</a>: synchronous callback and asynchronous callback. A synchronous callback is provided to another function which is going to do some task and then return to the caller with the task completed. An asynchronous callback is provided to another function which is going to start a task and then return to the caller with the task possibly not completed.</p>\n<p><strong>Synchronous callback</strong></p>\n<p>A synchronous callback is typically used to provide a delegate to another function to which the other function delegates some step of the task. Classic examples of this delegation are the functions <code>bsearch()</code> and <code>qsort()</code> from the C Standard Library. Both of these functions take a callback which is used during the task the function is providing so that the type of the data being searched, in the case of <code>bsearch()</code>, or sorted, in the case of <code>qsort()</code>, does not need to be known by the function being used.</p>\n<p>For example, here is a small sample program with <code>bsearch()</code> using different comparison functions, demonstrating synchronous callbacks. By allowing us to delegate the data comparison to a callback function, the <code>bsearch()</code> function allows us to decide at run time what kind of comparison we want to use. This is synchronous because when the <code>bsearch()</code> function returns the task is complete.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\ntypedef struct {\n int iValue;\n int kValue;\n char label[6];\n} MyData;\n\nint cmpMyData_iValue (MyData *item1, MyData *item2)\n{\n if (item1-&gt;iValue &lt; item2-&gt;iValue) return -1;\n if (item1-&gt;iValue &gt; item2-&gt;iValue) return 1;\n return 0;\n}\n\nint cmpMyData_kValue (MyData *item1, MyData *item2)\n{\n if (item1-&gt;kValue &lt; item2-&gt;kValue) return -1;\n if (item1-&gt;kValue &gt; item2-&gt;kValue) return 1;\n return 0;\n}\n\nint cmpMyData_label (MyData *item1, MyData *item2)\n{\n return strcmp (item1-&gt;label, item2-&gt;label);\n}\n\nvoid bsearch_results (MyData *srch, MyData *found)\n{\n if (found) {\n printf (&quot;found - iValue = %d, kValue = %d, label = %s\\n&quot;, found-&gt;iValue, found-&gt;kValue, found-&gt;label);\n } else {\n printf (&quot;item not found, iValue = %d, kValue = %d, label = %s\\n&quot;, srch-&gt;iValue, srch-&gt;kValue, srch-&gt;label);\n }\n}\n\nint main ()\n{\n MyData dataList[256] = {0};\n\n {\n int i;\n for (i = 0; i &lt; 20; i++) {\n dataList[i].iValue = i + 100;\n dataList[i].kValue = i + 1000;\n sprintf (dataList[i].label, &quot;%2.2d&quot;, i + 10);\n }\n }\n\n// ... some code then we do a search\n {\n MyData srchItem = { 105, 1018, &quot;13&quot;};\n MyData *foundItem = bsearch (&amp;srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );\n\n bsearch_results (&amp;srchItem, foundItem);\n\n foundItem = bsearch (&amp;srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );\n bsearch_results (&amp;srchItem, foundItem);\n\n foundItem = bsearch (&amp;srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );\n bsearch_results (&amp;srchItem, foundItem);\n }\n}\n</code></pre>\n<p><strong>Asynchronous callback</strong></p>\n<p>An asynchronous callback is different in that when the called function to which we provide a callback returns, the task may not be completed. This type of callback is often used with asynchronous I/O in which an I/O operation is started and then when it is completed, the callback is invoked.</p>\n<p>In the following program we create a socket to listen for TCP connection requests and when a request is received, the function doing the listening then invokes the callback function provided. This simple application can be exercised by running it in one window while using the <code>telnet</code> utility or a web browser to attempt to connect in another window.</p>\n<p>I lifted most of the WinSock code from the example Microsoft provides with the <code>accept()</code> function at <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx</a></p>\n<p>This application starts a <code>listen()</code> on the local host, 127.0.0.1, using port 8282 so you could use either <code>telnet 127.0.0.1 8282</code> or <code>http://127.0.0.1:8282/</code>.</p>\n<p>This sample application was created as a console application with Visual Studio 2017 Community Edition and it is using the Microsoft WinSock version of sockets. For a Linux application the WinSock functions would need to be replaced with the Linux alternatives and the Windows threads library would use <code>pthreads</code> instead.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;winsock2.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n#include &lt;Windows.h&gt;\n\n// Need to link with Ws2_32.lib\n#pragma comment(lib, &quot;Ws2_32.lib&quot;)\n\n// function for the thread we are going to start up with _beginthreadex().\n// this function/thread will create a listen server waiting for a TCP\n// connection request to come into the designated port.\n// _stdcall modifier required by _beginthreadex().\nint _stdcall ioThread(void (*pOutput)())\n{\n //----------------------\n // Initialize Winsock.\n WSADATA wsaData;\n int iResult = WSAStartup(MAKEWORD(2, 2), &amp;wsaData);\n if (iResult != NO_ERROR) {\n printf(&quot;WSAStartup failed with error: %ld\\n&quot;, iResult);\n return 1;\n }\n //----------------------\n // Create a SOCKET for listening for\n // incoming connection requests.\n SOCKET ListenSocket;\n ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (ListenSocket == INVALID_SOCKET) {\n wprintf(L&quot;socket failed with error: %ld\\n&quot;, WSAGetLastError());\n WSACleanup();\n return 1;\n }\n //----------------------\n // The sockaddr_in structure specifies the address family,\n // IP address, and port for the socket that is being bound.\n struct sockaddr_in service;\n service.sin_family = AF_INET;\n service.sin_addr.s_addr = inet_addr(&quot;127.0.0.1&quot;);\n service.sin_port = htons(8282);\n\n if (bind(ListenSocket, (SOCKADDR *)&amp; service, sizeof(service)) == SOCKET_ERROR) {\n printf(&quot;bind failed with error: %ld\\n&quot;, WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n //----------------------\n // Listen for incoming connection requests.\n // on the created socket\n if (listen(ListenSocket, 1) == SOCKET_ERROR) {\n printf(&quot;listen failed with error: %ld\\n&quot;, WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n //----------------------\n // Create a SOCKET for accepting incoming requests.\n SOCKET AcceptSocket;\n printf(&quot;Waiting for client to connect...\\n&quot;);\n\n //----------------------\n // Accept the connection.\n AcceptSocket = accept(ListenSocket, NULL, NULL);\n if (AcceptSocket == INVALID_SOCKET) {\n printf(&quot;accept failed with error: %ld\\n&quot;, WSAGetLastError());\n closesocket(ListenSocket);\n WSACleanup();\n return 1;\n }\n else\n pOutput (); // we have a connection request so do the callback\n\n // No longer need server socket\n closesocket(ListenSocket);\n\n WSACleanup();\n return 0;\n}\n\n// our callback which is invoked whenever a connection is made.\nvoid printOut(void)\n{\n printf(&quot;connection received.\\n&quot;);\n}\n\n#include &lt;process.h&gt;\n\nint main()\n{\n // start up our listen server and provide a callback\n _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);\n // do other things while waiting for a connection. In this case\n // just sleep for a while.\n Sleep(30000);\n}\n</code></pre>\n" }, { "answer_id": 53622778, "author": "Asif", "author_id": 8638742, "author_profile": "https://Stackoverflow.com/users/8638742", "pm_score": 1, "selected": false, "text": "<p>It is lot easier to understand an idea through example.\nWhat have been told about callback function in C so far are great answers, but probably the biggest benefit of using the feature is to keep the code clean and uncluttered.</p>\n\n<h1>Example</h1>\n\n<p>The following C code implements quick sorting.\nThe most interesting line in the code below is this one, where we can see the callback function in action:</p>\n\n<pre><code>qsort(arr,N,sizeof(int),compare_s2b);\n</code></pre>\n\n<p>The compare_s2b is the name of function which qsort() is using to call the function. This keeps qsort() so uncluttered (hence easier to maintain). You just call a function by name from inside another function (of course, the function prototype declaration, at the least, must precde before it can be called from another function).</p>\n\n<h1>The Complete Code</h1>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint arr[]={56,90,45,1234,12,3,7,18};\n//function prototype declaration \n\nint compare_s2b(const void *a,const void *b);\n\nint compare_b2s(const void *a,const void *b);\n\n//arranges the array number from the smallest to the biggest\nint compare_s2b(const void* a, const void* b)\n{\n const int* p=(const int*)a;\n const int* q=(const int*)b;\n\n return *p-*q;\n}\n\n//arranges the array number from the biggest to the smallest\nint compare_b2s(const void* a, const void* b)\n{\n const int* p=(const int*)a;\n const int* q=(const int*)b;\n\n return *q-*p;\n}\n\nint main()\n{\n printf(\"Before sorting\\n\\n\");\n\n int N=sizeof(arr)/sizeof(int);\n\n for(int i=0;i&lt;N;i++)\n {\n printf(\"%d\\t\",arr[i]);\n }\n\n printf(\"\\n\");\n\n qsort(arr,N,sizeof(int),compare_s2b);\n\n printf(\"\\nSorted small to big\\n\\n\");\n\n for(int j=0;j&lt;N;j++)\n {\n printf(\"%d\\t\",arr[j]);\n }\n\n qsort(arr,N,sizeof(int),compare_b2s);\n\n printf(\"\\nSorted big to small\\n\\n\");\n\n for(int j=0;j&lt;N;j++)\n {\n printf(\"%d\\t\",arr[j]);\n }\n\n exit(0);\n}\n</code></pre>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22913/" ]
From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.
There is no "callback" in C - not more than any other generic programming concept. They're implemented using function pointers. Here's an example: ``` void populate_array(int *array, size_t arraySize, int (*getNextValue)(void)) { for (size_t i=0; i<arraySize; i++) array[i] = getNextValue(); } int getNextRandomValue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getNextRandomValue); ... } ``` Here, the `populate_array` function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback `getNextRandomValue`, which returns a random-ish value, and passed a pointer to it to `populate_array`. `populate_array` will call our callback function 10 times and assign the returned values to the elements in the given array.
142,813
<p>I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. </p> <p>Example:</p> <pre> 2748 to "ABC" </pre>
[ { "answer_id": 142819, "author": "Muxa", "author_id": 10793, "author_profile": "https://Stackoverflow.com/users/10793", "pm_score": 3, "selected": true, "text": "<p>try</p>\n\n<pre><code>2748.ToString(\"X\")\n</code></pre>\n" }, { "answer_id": 142822, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 1, "selected": false, "text": "<p>Note: This assumes that you're using a custom, 12-bit representation. If you're just using an int/uint, then Muxa's solution is the best.</p>\n\n<p>Every four bits corresponds to a hexadecimal digit.</p>\n\n<p>Therefore, just match the first four digits to a letter, then >> 4 the input, and repeat.</p>\n" }, { "answer_id": 142828, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>The easy C solution may be adaptable:</p>\n\n<pre><code>char hexCharacters[17] = \"0123456789ABCDEF\";\nvoid toHex(char * outputString, long input)\n{\n outputString[0] = hexCharacters[(input &gt;&gt; 8) &amp; 0x0F];\n outputString[1] = hexCharacters[(input &gt;&gt; 4) &amp; 0x0F];\n outputString[2] = hexCharacters[input &amp; 0x0F];\n}\n</code></pre>\n\n<p>You could also do it in a loop, but this is pretty straightforward, and loop has pretty high overhead for only three conversions.</p>\n\n<p>I expect C# has a library function of some sort for this sort of thing, though. You could even use sprintf in C, and I'm sure C# has an analog to this functionality.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 143478, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>If you want exactly 3 characters and are sure the number is in range, use:</p>\n\n<pre><code>i.ToString(\"X3\")\n</code></pre>\n\n<p>If you aren't sure if the number is in range, this will give you more than 3 digits. You could do something like:</p>\n\n<pre><code>(i % 0x1000).ToString(\"X3\")\n</code></pre>\n\n<p>Use a lower case \"x3\" if you want lower-case letters.</p>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. Example: ``` 2748 to "ABC" ```
try ``` 2748.ToString("X") ```
142,820
<p>I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write </p> <pre><code>myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction); </code></pre> <p>this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.</p>
[ { "answer_id": 142823, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": "<p>Make sure your events are exposed as public. For example...</p>\n\n<pre><code>[Browsable(true)]\npublic event EventHandler MyCustomEvent;\n</code></pre>\n" }, { "answer_id": 41104603, "author": "Pierre-Olivier Pignon", "author_id": 969741, "author_profile": "https://Stackoverflow.com/users/969741", "pm_score": 0, "selected": false, "text": "<p>A solution using delegate. For example i used for a custom ListView which handle item added event : \nDeclare your delegate :</p>\n\n<pre><code> public delegate void ItemAddedHandler(object sender, ItemEventArgs e)\n</code></pre>\n\n<p>then declare the event which use the delegate :</p>\n\n<pre><code> [Browsable(true)]\n public event ItemAddedHandler ItemAdded;\n</code></pre>\n\n<p>Note : ItemEventArgs is a custom EventArgs</p>\n\n<p>Hope can help you, works fine for me</p>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403/" ]
I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write ``` myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction); ``` this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.
Make sure your events are exposed as public. For example... ``` [Browsable(true)] public event EventHandler MyCustomEvent; ```
142,826
<p>I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.</p> <p>I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.</p> <p>Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.</p> <p>I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.</p>
[ { "answer_id": 142833, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming\" rel=\"noreferrer\">Threading in C#</a> ebook summarises Thread.Suspend and Thread.Resume thusly:</p>\n\n<blockquote>\n <p>The deprecated Suspend and Resume methods have two modes – dangerous and useless!</p>\n</blockquote>\n\n<p>The book recommends using a synchronization construct such as an <a href=\"http://www.albahari.com/threading/part2.aspx#_AutoResetEvent\" rel=\"noreferrer\">AutoResetEvent</a> or <a href=\"http://www.albahari.com/threading/part4.aspx#_Wait_and_Pulse\" rel=\"noreferrer\">Monitor.Wait</a> to perform thread suspending and resuming.</p>\n" }, { "answer_id": 143153, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 8, "selected": true, "text": "<p>Never, ever use <code>Thread.Suspend</code>. The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API: <code>SuspendThread</code> and <code>ResumeThread</code>. The following docs for <code>SuspendThread</code> give a nice summary of the dangers of the API:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx</a></p>\n\n<blockquote>\n <p>This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.</p>\n</blockquote>\n\n<p>The proper way to suspend a thread indefinitely is to use a <code>ManualResetEvent</code>. The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread \"check\" the event each iteration, like so:</p>\n\n<pre><code>while (true)\n{\n _suspendEvent.WaitOne(Timeout.Infinite);\n\n // Do some work...\n}\n</code></pre>\n\n<p>You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off.</p>\n\n<p>You would create the event like so:</p>\n\n<pre><code>ManualResetEvent _suspendEvent = new ManualResetEvent(true);\n</code></pre>\n\n<p>The <code>true</code> parameter tells the event to start out in the signaled state.</p>\n\n<p>When you want to pause the thread, you do the following:</p>\n\n<pre><code>_suspendEvent.Reset();\n</code></pre>\n\n<p>And to resume the thread:</p>\n\n<pre><code>_suspendEvent.Set();\n</code></pre>\n\n<p>You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled.</p>\n\n<p>Just for fun I'll provide a complete example:</p>\n\n<pre><code>public class Worker\n{\n ManualResetEvent _shutdownEvent = new ManualResetEvent(false);\n ManualResetEvent _pauseEvent = new ManualResetEvent(true);\n Thread _thread;\n\n public Worker() { }\n\n public void Start()\n {\n _thread = new Thread(DoWork);\n _thread.Start();\n }\n\n public void Pause()\n {\n _pauseEvent.Reset();\n }\n\n public void Resume()\n {\n _pauseEvent.Set();\n }\n\n public void Stop()\n {\n // Signal the shutdown event\n _shutdownEvent.Set();\n\n // Make sure to resume any paused threads\n _pauseEvent.Set();\n\n // Wait for the thread to exit\n _thread.Join();\n }\n\n public void DoWork()\n {\n while (true)\n {\n _pauseEvent.WaitOne(Timeout.Infinite);\n\n if (_shutdownEvent.WaitOne(0))\n break;\n\n // Do the work here..\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 143358, "author": "Lex Li", "author_id": 11182, "author_profile": "https://Stackoverflow.com/users/11182", "pm_score": 0, "selected": false, "text": "<p>Beside suggestions above, I'd like to add one tip. In some cases, use BackgroundWorker can simplify your code (especially when you use anonymous method to define DoWork and other events of it).</p>\n" }, { "answer_id": 199775, "author": "Bruce", "author_id": 6310, "author_profile": "https://Stackoverflow.com/users/6310", "pm_score": 0, "selected": false, "text": "<p>In line with what the others said - don't do it. What you really want to do is to \"pause work\", and let your threads roam free. Can you give us some more details about the thread(s) you want to suspend? If you didn't start the thread, you definitely shouldn't even consider suspending it - its not yours. If it is your thread, then I suggest instead of suspending it, you just have it sit, waiting for more work to do. Brannon has some excellent suggestions for this option in his response. Alternatively, just let it end; and spin up a new one when you need it.</p>\n" }, { "answer_id": 8836334, "author": "ThunderGr", "author_id": 1145669, "author_profile": "https://Stackoverflow.com/users/1145669", "pm_score": -1, "selected": false, "text": "<p>The Suspend() and Resume() may be depricated, however they are in no way useless.\nIf, for example, you have a thread doing a lengthy work altering data, and the user wishes to stop it, he clicks on a button. Of course, you need to ask for verification, but, at the same time you do not want that thread to continue altering data, if the user decides that he really wants to abort.\nSuspending the Thread while waiting for the user to click that Yes or No button at the confirmation dialog is the <em>only</em> way to prevent it from altering the data, before you signal the designated abort event that will allow it to stop.\nEvents may be nice for simple threads having one loop, but complicated threads with complex processing is another issue.\nCertainly, Suspend() must <em>never</em> be used for syncronising, since its usefulness is not for this function.</p>\n\n<p>Just my opinion.</p>\n" }, { "answer_id": 11320956, "author": "Matthias", "author_id": 568266, "author_profile": "https://Stackoverflow.com/users/568266", "pm_score": 1, "selected": false, "text": "<p>I just implemented a <code>LoopingThread</code> class which loops an action passed to the constructor. It is based on Brannon's post. I've put some other stuff into that like <code>WaitForPause()</code>, <code>WaitForStop()</code>, and a <code>TimeBetween</code> property, that indicates the time that should be waited before next looping.</p>\n\n<p>I also decided to change the while-loop to an do-while-loop. This will give us a deterministic behavior for a successive <code>Start()</code> and <code>Pause()</code>. With deterministic I mean, that the action is executed at least once after a <code>Start()</code> command. In Brannon's implementation this might not be the case.</p>\n\n<p><em>I omitted some things for the root of the matter. Things like \"check if the thread was already started\", or the <code>IDisposable</code> pattern.</em></p>\n\n<pre><code>public class LoopingThread\n{\n private readonly Action _loopedAction;\n private readonly AutoResetEvent _pauseEvent;\n private readonly AutoResetEvent _resumeEvent;\n private readonly AutoResetEvent _stopEvent;\n private readonly AutoResetEvent _waitEvent;\n\n private readonly Thread _thread;\n\n public LoopingThread (Action loopedAction)\n {\n _loopedAction = loopedAction;\n _thread = new Thread (Loop);\n _pauseEvent = new AutoResetEvent (false);\n _resumeEvent = new AutoResetEvent (false);\n _stopEvent = new AutoResetEvent (false);\n _waitEvent = new AutoResetEvent (false);\n }\n\n public void Start ()\n {\n _thread.Start();\n }\n\n public void Pause (int timeout = 0)\n {\n _pauseEvent.Set();\n _waitEvent.WaitOne (timeout);\n }\n\n public void Resume ()\n {\n _resumeEvent.Set ();\n }\n\n public void Stop (int timeout = 0)\n {\n _stopEvent.Set();\n _resumeEvent.Set();\n _thread.Join (timeout);\n }\n\n public void WaitForPause ()\n {\n Pause (Timeout.Infinite);\n }\n\n public void WaitForStop ()\n {\n Stop (Timeout.Infinite);\n }\n\n public int PauseBetween { get; set; }\n\n private void Loop ()\n {\n do\n {\n _loopedAction ();\n\n if (_pauseEvent.WaitOne (PauseBetween))\n {\n _waitEvent.Set ();\n _resumeEvent.WaitOne (Timeout.Infinite);\n }\n } while (!_stopEvent.WaitOne (0));\n }\n}\n</code></pre>\n" }, { "answer_id": 40420796, "author": "Alberto", "author_id": 2987314, "author_profile": "https://Stackoverflow.com/users/2987314", "pm_score": 2, "selected": false, "text": "<p>If there are no synchronization requirements:</p>\n\n<p><code>Thread.Sleep(Timeout.Infinite);</code></p>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread. I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework. Is there any good general purpose way to indefinitely pause a worker thread in C# .NET. I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.
Never, ever use `Thread.Suspend`. The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API: `SuspendThread` and `ResumeThread`. The following docs for `SuspendThread` give a nice summary of the dangers of the API: <http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx> > > This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately. > > > The proper way to suspend a thread indefinitely is to use a `ManualResetEvent`. The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread "check" the event each iteration, like so: ``` while (true) { _suspendEvent.WaitOne(Timeout.Infinite); // Do some work... } ``` You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off. You would create the event like so: ``` ManualResetEvent _suspendEvent = new ManualResetEvent(true); ``` The `true` parameter tells the event to start out in the signaled state. When you want to pause the thread, you do the following: ``` _suspendEvent.Reset(); ``` And to resume the thread: ``` _suspendEvent.Set(); ``` You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled. Just for fun I'll provide a complete example: ``` public class Worker { ManualResetEvent _shutdownEvent = new ManualResetEvent(false); ManualResetEvent _pauseEvent = new ManualResetEvent(true); Thread _thread; public Worker() { } public void Start() { _thread = new Thread(DoWork); _thread.Start(); } public void Pause() { _pauseEvent.Reset(); } public void Resume() { _pauseEvent.Set(); } public void Stop() { // Signal the shutdown event _shutdownEvent.Set(); // Make sure to resume any paused threads _pauseEvent.Set(); // Wait for the thread to exit _thread.Join(); } public void DoWork() { while (true) { _pauseEvent.WaitOne(Timeout.Infinite); if (_shutdownEvent.WaitOne(0)) break; // Do the work here.. } } } ```
142,844
<p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p> <p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
[ { "answer_id": 142854, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 7, "selected": true, "text": "<p>Sure. From a <a href=\"http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/\" rel=\"noreferrer\">mindless technology article called \"Make Python Scripts Droppable in Windows\"</a>, you can add a drop handler by adding a registry key:</p>\n\n<blockquote>\n <p>Here’s a registry import file that you can use to do this. Copy the\n following into a .reg file and run it\n (Make sure that your .py extensions\n are mapped to Python.File).</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Python.File\\shellex\\DropHandler]\n@=\"{60254CA5-953B-11CF-8C96-00AA00B8708C}\"\n</code></pre>\n</blockquote>\n\n<p>This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with <code>86C86720-42A0-1069-A2E8-08002B30309D</code>.</p>\n\n<p>A comment in that post indicates that one can enable dropping on \"no console Python files (<code>.pyw</code>)\" or \"compiled Python files (<code>.pyc</code>)\" by using the <code>Python.NoConFile</code> and <code>Python.CompiledFile</code> classes.</p>\n" }, { "answer_id": 4486506, "author": "Evan", "author_id": 548149, "author_profile": "https://Stackoverflow.com/users/548149", "pm_score": 3, "selected": false, "text": "<p>Try using py2exe. Use py2exe to convert your python script into a windows executable. You should then be able to drag and drop input files to your script in Windows Explorer. You should also be able to create a shortcut on your desktop and drop input files onto it. And if your python script can take a file list you should be able to drag and drop multiple files on your script (or shortcut).</p>\n" }, { "answer_id": 10246159, "author": "marco", "author_id": 1346520, "author_profile": "https://Stackoverflow.com/users/1346520", "pm_score": 5, "selected": false, "text": "<p>write a simple shell script (<code>file.bat</code>)</p>\n\n<pre><code>\"C:\\python27\\python.exe\" yourprogram.py %*\n</code></pre>\n\n<p>where <code>%*</code> stands for the all arguments you pass to the script.</p>\n\n<p>Now drag &amp; drop your target files on the <code>file.bat</code> icon.</p>\n" }, { "answer_id": 21840490, "author": "horta", "author_id": 1824979, "author_profile": "https://Stackoverflow.com/users/1824979", "pm_score": 2, "selected": false, "text": "<p>Create a shortcut of the file. In case you don't have python open .py files by default, go into the properties of the shortcut and edit the target of the shortcut to include the python version you're using. For example:</p>\n\n<p>Target: C:\\Python26\\python.exe &lt; shortcut target path></p>\n\n<p>I'm posting this because I didn't want to edit the Registry and the .bat workaround didn't work for me.</p>\n" }, { "answer_id": 45617351, "author": "halanson", "author_id": 1984396, "author_profile": "https://Stackoverflow.com/users/1984396", "pm_score": 4, "selected": false, "text": "<p>With an installed python - at least 2.6.1 - you can just drag and drop any file on a python script.</p>\n\n<pre><code>import sys\ndroppedFile = sys.argv[1]\nprint droppedFile\n</code></pre>\n\n<p><code>sys.argv[0]</code> is the script itself. <code>sys.argv[n+1]</code> are the files you have dropped.</p>\n" }, { "answer_id": 53586688, "author": "Puddle", "author_id": 9312988, "author_profile": "https://Stackoverflow.com/users/9312988", "pm_score": 2, "selected": false, "text": "<p>1). create shortcut of .py<br>\n2). right click -> properties<br>\n3). prefix \"Target:\" with \"python\" so it runs the .py as an argument into the python command<br>\nor<br>\n1). create a .bat<br>\n2). python some.py %*</p>\n\n<p>these shortcut versions are simplest for me to do what i'm doing<br>\notherwise i'd convert it to a .exe, but would rather just use java or c/c++</p>\n" }, { "answer_id": 65873279, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 2, "selected": false, "text": "<p>Late answer but none of the answers on this page worked for me.<br />\nI managed to enable/fix the drag and drop onto <code>.py</code> scripts using:</p>\n<ol>\n<li><p><code>HKEY_CLASSES_ROOT\\.py</code> -&gt; Set default value to <code>Python.File</code></p>\n</li>\n<li><p><code>HKEY_CLASSES_ROOT\\Python.File\\Shell\\Open</code> -&gt; Create a key called <code>Command</code> with default value <code>&quot;C:\\Windows\\py.exe&quot; &quot;%1&quot; %*</code></p>\n</li>\n<li><p><code>CLASSES_ROOT\\Applications\\py.exe\\open\\command</code> -&gt; Create keys if the don't exist and set the default value to <code>&quot;C:\\Windows\\py.exe&quot; &quot;%1&quot; %*</code></p>\n</li>\n<li><p><code>CLASSES_ROOT\\Python.File\\ShellEx</code> -&gt; create key <code>DropHandler</code> with default value <code>{86C86720-42A0-1069-A2E8-08002B30309D}</code></p>\n</li>\n</ol>\n<p>That's it. Test it by dragging a file onto the python script:</p>\n<pre><code>import sys\n\nargs = sys.argv\nprint(args)\n</code></pre>\n" }, { "answer_id": 66023395, "author": "redfishleo", "author_id": 8426713, "author_profile": "https://Stackoverflow.com/users/8426713", "pm_score": 0, "selected": false, "text": "<p>For those who use argv in .py script but still can't drag files to execute,\nthis could be solved by simply <em>using Python Launcher (with rocket icon)</em></p>\n<p>the script property &quot;Open File&quot; was set as python.exe,\nwhich has no knowledge that the script needs command-line arguments &quot;%*&quot;</p>\n<p>Refer to: <a href=\"https://bugs.python.org/issue40253\" rel=\"nofollow noreferrer\">https://bugs.python.org/issue40253</a></p>\n" } ]
2008/09/27
[ "https://Stackoverflow.com/questions/142844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4859/" ]
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target. Is there some kind of configuration that needs to be done somewhere for this work?
Sure. From a [mindless technology article called "Make Python Scripts Droppable in Windows"](http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/), you can add a drop handler by adding a registry key: > > Here’s a registry import file that you can use to do this. Copy the > following into a .reg file and run it > (Make sure that your .py extensions > are mapped to Python.File). > > > > ``` > Windows Registry Editor Version 5.00 > > [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] > @="{60254CA5-953B-11CF-8C96-00AA00B8708C}" > > ``` > > This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with `86C86720-42A0-1069-A2E8-08002B30309D`. A comment in that post indicates that one can enable dropping on "no console Python files (`.pyw`)" or "compiled Python files (`.pyc`)" by using the `Python.NoConFile` and `Python.CompiledFile` classes.