qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
20,952
<p>I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx" rel="noreferrer">System.Configuration.Configuration</a> for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:</p> <pre><code>Configuration testConfig = new Configuration("&lt;?xml version=\"1.0\"?&gt;&lt;configuration&gt;...&lt;/configuration&gt;"); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section != null); </code></pre> <p>However, it looks like <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">ConfigurationManager</a> will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?</p>
[ { "answer_id": 21005, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>Looking at the members of the class, I'd say the answer is probably no*. I'm not sure why you'd want to do this anyway, rather than create your own XML configuration file.</p>\n\n<p>*That's no, excluding messy reflection hacks</p>\n" }, { "answer_id": 24938, "author": "Nicholas", "author_id": 2658, "author_profile": "https://Stackoverflow.com/users/2658", "pm_score": 1, "selected": false, "text": "<p>I think what you're looking for is ConfigurationManager.<a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration.aspx\" rel=\"nofollow noreferrer\">OpenMappedExeConfiguration</a></p>\n\n<p>It allows you to open a configuration file that you specify with a file path (wrapped inside a <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.execonfigurationfilemap.aspx\" rel=\"nofollow noreferrer\">ExeConfigurationFileMap</a>)</p>\n\n<p>If what the other poster said is true, and you don't wish to create a whole new XML file for testing, then I'd recommend you put your Configuration edits in the Test method itself, then run your tests against the freshly changed configuration data.</p>\n" }, { "answer_id": 704817, "author": "Oliver Pearmain", "author_id": 334395, "author_profile": "https://Stackoverflow.com/users/334395", "pm_score": 5, "selected": true, "text": "<p>There is actually a way I've discovered....</p>\n\n<p>You need to define a new class inheriting from your original configuration section as follows:</p>\n\n<pre><code>public class MyXmlCustomConfigSection : MyCustomConfigSection\n{\n public MyXmlCustomConfigSection (string configXml)\n {\n XmlTextReader reader = new XmlTextReader(new StringReader(configXml));\n DeserializeSection(reader);\n }\n}\n</code></pre>\n\n<p><br/>\nYou can then instantiate your ConfigurationSection object as follows:</p>\n\n<pre><code>string configXml = \"&lt;?xml version=\\\"1.0\\\"?&gt;&lt;configuration&gt;...&lt;/configuration&gt;\";\nMyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);\n</code></pre>\n\n<p>Hope it helps someone :-)</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338/" ]
I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a [System.Configuration.Configuration](http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx) for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this: ``` Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>"); MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection"); Assert.That(section != null); ``` However, it looks like [ConfigurationManager](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx) will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?
There is actually a way I've discovered.... You need to define a new class inheriting from your original configuration section as follows: ``` public class MyXmlCustomConfigSection : MyCustomConfigSection { public MyXmlCustomConfigSection (string configXml) { XmlTextReader reader = new XmlTextReader(new StringReader(configXml)); DeserializeSection(reader); } } ``` You can then instantiate your ConfigurationSection object as follows: ``` string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>"; MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml); ``` Hope it helps someone :-)
20,959
<p>How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.</p> <p>It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.</p>
[ { "answer_id": 20970, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>Looks like <code>AppDomain.CurrentDomain.GetAssemblies();</code> will do the trick :)</p>\n" }, { "answer_id": 20974, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 5, "selected": true, "text": "<pre><code>using System;\nusing System.Reflection;\nusing System.Windows.Forms;\n\npublic class MyAppDomain\n{\n public static void Main(string[] args)\n {\n AppDomain ad = AppDomain.CurrentDomain;\n Assembly[] loadedAssemblies = ad.GetAssemblies();\n\n Console.WriteLine(\"Here are the assemblies loaded in this appdomain\\n\");\n foreach(Assembly a in loadedAssemblies)\n {\n Console.WriteLine(a.FullName);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 20975, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 2, "selected": false, "text": "<p>Either that, or System.Reflection.Assembly.GetLoadedModules().</p>\n\n<p>Note that AppDomain.GetAssemblies will only iterate assemblies in the <em>current</em> AppDomain. It's possible for an application to have more than one AppDomain, so that may or may not do what you want.</p>\n" }, { "answer_id": 21108, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 0, "selected": false, "text": "<p>For all DLLs including unmanaged, you could pinvoke EnumProcessModules to get the module handles and then use GetModuleFileName for each handle to get the name.</p>\n\n<p>See <a href=\"http://pinvoke.net/default.aspx/psapi.EnumProcessModules\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/psapi.EnumProcessModules</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx</a> (pinvoke.net does not have the signature for this but it's easy to figure out).</p>\n\n<p><em>For 64 bit you need to use EnumProcessModulesEx</em></p>\n" }, { "answer_id": 5847255, "author": "bernd_k", "author_id": 522317, "author_profile": "https://Stackoverflow.com/users/522317", "pm_score": 2, "selected": false, "text": "<p><strong>PowerShell Version:</strong></p>\n\n<pre><code>[System.AppDomain]::CurrentDomain.GetAssemblies()\n</code></pre>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC. It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.
``` using System; using System.Reflection; using System.Windows.Forms; public class MyAppDomain { public static void Main(string[] args) { AppDomain ad = AppDomain.CurrentDomain; Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("Here are the assemblies loaded in this appdomain\n"); foreach(Assembly a in loadedAssemblies) { Console.WriteLine(a.FullName); } } } ```
20,998
<p>When I try to create a SQL Server Login by saying</p> <pre><code>CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; </code></pre> <p>I get this error</p> <blockquote> <p>The server principal 'ourdomain\SQLAccessGroup' already exists.</p> </blockquote> <p>However, when I try this code</p> <pre><code>DROP LOGIN [ourdomain\SQLAccessGroup] </code></pre> <p>I get this error</p> <blockquote> <p>Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.</p> </blockquote> <p>The user that I am executing this code as is a sysadmin. Additionally, the user <code>ourdomain\SQLAccessGroup</code> does not show up in this query</p> <pre><code>select * from sys.server_principals </code></pre> <p>Does anyone have any ideas?</p>
[ { "answer_id": 21074, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 4, "selected": true, "text": "<p>We are still struggling to understand the <em>HOW</em> of this issue, but it seems that [ourdomain\\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game.</p>\n\n<p>Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error:</p>\n\n<pre><code>The login already has an account under a different user name.\n</code></pre>\n\n<p>So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time... :-)</p>\n" }, { "answer_id": 21115, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 2, "selected": false, "text": "<p>is this when you are restoring from a backup or something? I've found that the following works for me in situations when I'm having problems with user accounts in sql</p>\n\n<pre><code>EXEC sp_change_users_login ‘Auto_Fix’, ‘user_in_here’\n</code></pre>\n" }, { "answer_id": 55786743, "author": "Shadi Alnamrouti", "author_id": 3380497, "author_profile": "https://Stackoverflow.com/users/3380497", "pm_score": 0, "selected": false, "text": "<p>This happened to me when I installed SQL Server using a Windows username and then I renamed the computer name and the Windows username from Windows. SQL server still has the old \"Computername\\Username\" in its node of Server->Security->Logins.</p>\n\n<p>The solution is to go to Server->Security-><strong>Logins</strong> and right-click -> <strong>rename</strong> the old Windows user and use the new <strong>MachineName\\Username</strong>.</p>\n" }, { "answer_id": 56605391, "author": "OneGhana", "author_id": 10754903, "author_profile": "https://Stackoverflow.com/users/10754903", "pm_score": 0, "selected": false, "text": "<p>I faced similar issue and i believe the issue was as a result of trying to recreate a login account after deleting an existing one with same name.\nJust go through the various databases on the server using SQL Studio.\nExample steps:</p>\n\n<p>DBName ->Security->users</p>\n\n<p>at this level for each of the databases, you may see the name of the user account there. Delete all occurrence in each Database as well as its occurrence in the top level Security settings at </p>\n\n<p>Security->Logins</p>\n\n<p>When done, try recreating the login account again and you should be fine.</p>\n" }, { "answer_id": 57805923, "author": "Kuba D", "author_id": 4314825, "author_profile": "https://Stackoverflow.com/users/4314825", "pm_score": 0, "selected": false, "text": "<p>I had the same story as Shadi.\nOn the top I can add that it can be also done by query: </p>\n\n<pre><code>ALTER LOGIN \"oldname\\RMS\" WITH name=\"currentname\\RMS\"\n</code></pre>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/20998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76/" ]
When I try to create a SQL Server Login by saying ``` CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS; ``` I get this error > > The server principal 'ourdomain\SQLAccessGroup' already exists. > > > However, when I try this code ``` DROP LOGIN [ourdomain\SQLAccessGroup] ``` I get this error > > Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission. > > > The user that I am executing this code as is a sysadmin. Additionally, the user `ourdomain\SQLAccessGroup` does not show up in this query ``` select * from sys.server_principals ``` Does anyone have any ideas?
We are still struggling to understand the *HOW* of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game. Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error: ``` The login already has an account under a different user name. ``` So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time... :-)
21,052
<p>When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:</p> <pre><code>&lt;%#((MyType)Container.DataItem).PropertyOfMyType%&gt; </code></pre> <p>The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.</p> <pre><code>&lt;%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%&gt; </code></pre> <p>Is there any kind of <code>using</code> directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?</p>
[ { "answer_id": 21056, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 7, "selected": true, "text": "<p>I believe you can add something like:</p>\n\n<pre><code>&lt;%@ Import Namespace=\"RootNamespace.SubNamespace1\" %&gt; \n</code></pre>\n\n<p>At the top of the page.</p>\n" }, { "answer_id": 21057, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<p>What you're looking for is the <a href=\"http://msdn.microsoft.com/en-us/library/eb44kack(v=VS.80).aspx\" rel=\"nofollow noreferrer\" title=\"MSDN\">@Import page directive</a>.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following: ``` <%#((MyType)Container.DataItem).PropertyOfMyType%> ``` The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified. ``` <%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%> ``` Is there any kind of `using` directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?
I believe you can add something like: ``` <%@ Import Namespace="RootNamespace.SubNamespace1" %> ``` At the top of the page.
21,060
<p>I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)</p> <p>Do you know if there's some setting I could touch for this not to happen?</p>
[ { "answer_id": 21056, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 7, "selected": true, "text": "<p>I believe you can add something like:</p>\n\n<pre><code>&lt;%@ Import Namespace=\"RootNamespace.SubNamespace1\" %&gt; \n</code></pre>\n\n<p>At the top of the page.</p>\n" }, { "answer_id": 21057, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<p>What you're looking for is the <a href=\"http://msdn.microsoft.com/en-us/library/eb44kack(v=VS.80).aspx\" rel=\"nofollow noreferrer\" title=\"MSDN\">@Import page directive</a>.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups) Do you know if there's some setting I could touch for this not to happen?
I believe you can add something like: ``` <%@ Import Namespace="RootNamespace.SubNamespace1" %> ``` At the top of the page.
21,078
<p>What's the most efficient way to concatenate strings?</p>
[ { "answer_id": 21084, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 2, "selected": false, "text": "<p>The most efficient is to use StringBuilder, like so:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nsb.Append(\"string1\");\nsb.Append(\"string2\");\n...etc...\nString strResult = sb.ToString();\n</code></pre>\n\n<p>@jonezy: String.Concat is fine if you have a couple of small things. But if you're concatenating megabytes of data, your program will likely tank.</p>\n" }, { "answer_id": 21093, "author": "TheEmirOfGroofunkistan", "author_id": 1874, "author_profile": "https://Stackoverflow.com/users/1874", "pm_score": 8, "selected": true, "text": "<p>The <code>StringBuilder.Append()</code> method is much better than using the <code>+</code> operator. But I've found that, when executing 1000 concatenations or less, <code>String.Join()</code> is even more efficient than <code>StringBuilder</code>.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nsb.Append(someString);\n</code></pre>\n\n<p>The only problem with <code>String.Join</code> is that you have to concatenate the strings with a common delimiter.</p>\n\n<p><strong>Edit:</strong> as <em>@ryanversaw</em> pointed out, you can make the delimiter <code>string.Empty</code>.</p>\n\n<pre><code>string key = String.Join(\"_\", new String[] \n{ \"Customers_Contacts\", customerID, database, SessionID });\n</code></pre>\n" }, { "answer_id": 21097, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>For just two strings, you definitely do not want to use StringBuilder. There is some threshold above which the StringBuilder overhead is less than the overhead of allocating multiple strings.</p>\n\n<p>So, for more that 2-3 strings, use <a href=\"https://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c#21084\">DannySmurf's code</a>. Otherwise, just use the + operator.</p>\n" }, { "answer_id": 21113, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"http://www.chinhdo.com/20070224/stringbuilder-is-not-always-faster/\" rel=\"noreferrer\">Chinh Do - StringBuilder is not always faster</a>:</p>\n\n<p><strong>Rules of Thumb</strong></p>\n\n<ul>\n<li><p>When concatenating <strong>three</strong> dynamic string values or less, use traditional string concatenation.</p></li>\n<li><p>When concatenating <strong>more than three</strong> dynamic string values, use <code>StringBuilder</code>.</p></li>\n<li><p>When building a big string from several string literals, use either the <code>@</code> string literal or the inline + operator.</p></li>\n</ul>\n\n<p><em>Most</em> of the time <code>StringBuilder</code> is your best bet, but there are cases as shown in that post that you should at least think about each situation.</p>\n" }, { "answer_id": 21114, "author": "Jon Dewees", "author_id": 1365, "author_profile": "https://Stackoverflow.com/users/1365", "pm_score": 0, "selected": false, "text": "<p>It would depend on the code. \nStringBuilder is more efficient generally, but if you're only concatenating a few strings and doing it all in one line, code optimizations will likely take care of it for you. It's important to think about how the code looks too: for larger sets StringBuilder will make it easier to read, for small ones StringBuilder will just add needless clutter.</p>\n" }, { "answer_id": 21118, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 4, "selected": false, "text": "<p>If you're operating in a loop, <code>StringBuilder</code> is probably the way to go; it saves you the overhead of creating new strings regularly. In code that'll only run once, though, <code>String.Concat</code> is probably fine.</p>\n\n<p>However, Rico Mariani (.NET optimization guru) <a href=\"http://blogs.msdn.com/ricom/archive/2004/03/12/performance-quiz-1-of-a-series.aspx\" rel=\"nofollow noreferrer\">made up a quiz</a> in which he stated at the end that, in most cases, he recommends <code>String.Format</code>.</p>\n" }, { "answer_id": 21131, "author": "Lee", "author_id": 1954, "author_profile": "https://Stackoverflow.com/users/1954", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://blogs.msdn.microsoft.com/ricom/\" rel=\"noreferrer\">Rico Mariani</a>, the .NET Performance guru, had <a href=\"https://blogs.msdn.microsoft.com/ricom/2003/12/15/more-stringbuilder-advice/\" rel=\"noreferrer\">an article</a> on this very subject. It's not as simple as one might suspect. The basic advice is this:</p>\n\n<blockquote>\n <p>If your pattern looks like:</p>\n \n <p><code>x = f1(...) + f2(...) + f3(...) + f4(...)</code></p>\n \n <p>that's one concat and it's zippy, StringBuilder probably won't help.</p>\n \n <p>If your pattern looks like: </p>\n \n <p><code>if (...) x += f1(...)</code><br>\n <code>if (...) x += f2(...)</code><br>\n <code>if (...) x += f3(...)</code><br>\n <code>if (...) x += f4(...)</code> </p>\n \n <p>then you probably want StringBuilder.</p>\n</blockquote>\n\n<p><a href=\"http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/\" rel=\"noreferrer\">Yet another article to support this claim</a> comes from Eric Lippert where he describes the optimizations performed on one line <code>+</code> concatenations in a detailed manner.</p>\n" }, { "answer_id": 164074, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 3, "selected": false, "text": "<p>From this <a href=\"http://msdn.microsoft.com/en-us/library/ms973839.aspx\" rel=\"nofollow noreferrer\">MSDN article</a>:</p>\n\n<blockquote>\n <p>There is some overhead associated with\n creating a StringBuilder object, both\n in time and memory. On a machine with\n fast memory, a StringBuilder becomes\n worthwhile if you're doing about five\n operations. As a rule of thumb, I\n would say 10 or more string operations\n is a justification for the overhead on\n any machine, even a slower one.</p>\n</blockquote>\n\n<p>So if you trust MSDN go with StringBuilder if you have to do more than 10 strings operations/concatenations - otherwise simple string concat with '+' is fine.</p>\n" }, { "answer_id": 6184000, "author": "Liran", "author_id": 2164233, "author_profile": "https://Stackoverflow.com/users/2164233", "pm_score": 1, "selected": false, "text": "<p>It really depends on your usage pattern.\nA detailed benchmark between string.Join, string,Concat and string.Format can be found here: <a href=\"http://www.liranchen.com/2010/07/stringformat-isnt-suitable-for.html\" rel=\"nofollow noreferrer\">String.Format Isn't Suitable for Intensive Logging</a></p>\n\n<p>(This is actually the same answer I gave to <a href=\"https://stackoverflow.com/questions/6785/is-string-format-as-efficient-as-stringbuilder\">this</a> question)</p>\n" }, { "answer_id": 12257751, "author": "Mr_Green", "author_id": 1577396, "author_profile": "https://Stackoverflow.com/users/1577396", "pm_score": 7, "selected": false, "text": "<p>There are 6 types of string concatenations:</p>\n\n<ol>\n<li>Using the plus (<code>+</code>) symbol.</li>\n<li>Using <code>string.Concat()</code>.</li>\n<li>Using <code>string.Join()</code>.</li>\n<li>Using <code>string.Format()</code>.</li>\n<li>Using <code>string.Append()</code>.</li>\n<li>Using <code>StringBuilder</code>.</li>\n</ol>\n\n<p>In an experiment, it has been proved that <code>string.Concat()</code> is the best way to approach if the words are less than 1000(approximately) and if the words are more than 1000 then <code>StringBuilder</code> should be used.</p>\n\n<p>For more information, check this <a href=\"http://www.dotnetperls.com/string-concat\" rel=\"noreferrer\">site</a>. </p>\n\n<blockquote>\n <h3>string.Join() vs string.Concat()</h3>\n \n <p>The string.Concat method here is equivalent to the string.Join method invocation with an empty separator. Appending an empty string is fast, but not doing so is even faster, so the <strong>string.Concat</strong> method would be superior here.</p>\n</blockquote>\n" }, { "answer_id": 19365619, "author": "talles", "author_id": 1316620, "author_profile": "https://Stackoverflow.com/users/1316620", "pm_score": 3, "selected": false, "text": "<p>It's also important to point it out that you should use the <code>+</code> operator if you are concatenating <a href=\"http://en.wikipedia.org/wiki/String_literal\" rel=\"noreferrer\">string literals</a>.</p>\n\n<blockquote>\n <p>When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs.</p>\n</blockquote>\n\n<p><a href=\"http://msdn.microsoft.com/library/ms228504.aspx\" rel=\"noreferrer\">How to: Concatenate Multiple Strings (C# Programming Guide)</a></p>\n" }, { "answer_id": 23266274, "author": "Dhibi_Mohanned", "author_id": 3416010, "author_profile": "https://Stackoverflow.com/users/3416010", "pm_score": 2, "selected": false, "text": "<p>System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.</p>\n" }, { "answer_id": 26680343, "author": "DBN", "author_id": 3192156, "author_profile": "https://Stackoverflow.com/users/3192156", "pm_score": 3, "selected": false, "text": "<p>Adding to the other answers, please keep in mind that <a href=\"http://msdn.microsoft.com/en-us/library/h1h0a5sy.aspx\" rel=\"nofollow noreferrer\">StringBuilder can be told an initial amount of memory to allocate</a>.</p>\n<blockquote>\n<p>The <em>capacity</em> parameter defines the maximum number of characters that can be stored in the memory allocated by the current instance. Its value is assigned to the <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.capacity.aspx\" rel=\"nofollow noreferrer\">Capacity</a> property. If the number of characters to be stored in the current instance exceeds this <em>capacity</em> value, the StringBuilder object allocates additional memory to store them.</p>\n<p>If <em>capacity</em> is zero, the implementation-specific default capacity is used.</p>\n</blockquote>\n<p>Repeatedly appending to a StringBuilder that hasn't been pre-allocated can result in a lot of unnecessary allocations just like repeatedly concatenating regular strings.</p>\n<p>If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.capacity.aspx\" rel=\"nofollow noreferrer\">Capacity</a> property. <em>Especially</em> when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.</p>\n<p>If you can't make any kind of guess about the size, you're probably writing a utility function which should have its own optional argument for controlling pre-allocation.</p>\n" }, { "answer_id": 34558305, "author": "Eduardo Mass", "author_id": 5696173, "author_profile": "https://Stackoverflow.com/users/5696173", "pm_score": 3, "selected": false, "text": "<p>Try this 2 pieces of code and you will find the solution.</p>\n\n<pre><code> static void Main(string[] args)\n {\n StringBuilder s = new StringBuilder();\n for (int i = 0; i &lt; 10000000; i++)\n {\n s.Append( i.ToString());\n }\n Console.Write(\"End\");\n Console.Read();\n }\n</code></pre>\n\n<p>Vs</p>\n\n<pre><code>static void Main(string[] args)\n {\n string s = \"\";\n for (int i = 0; i &lt; 10000000; i++)\n {\n s += i.ToString();\n }\n Console.Write(\"End\");\n Console.Read();\n }\n</code></pre>\n\n<p>You will find that 1st code will end really quick and the memory will be in a good amount.</p>\n\n<p>The second code maybe the memory will be ok, but it will take longer... much longer.\nSo if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more \"natural\" for developers.</p>\n\n<p>Cheers. </p>\n" }, { "answer_id": 43069670, "author": "RP Nainwal", "author_id": 1106356, "author_profile": "https://Stackoverflow.com/users/1106356", "pm_score": 3, "selected": false, "text": "<p>Following may be one more alternate solution to concatenate multiple strings.</p>\n\n<pre><code>String str1 = \"sometext\";\nstring str2 = \"some other text\";\n\nstring afterConcate = $\"{str1}{str2}\";\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/31014895/3546415\">string interpolation</a></p>\n" }, { "answer_id": 47231853, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 4, "selected": false, "text": "<p>Here is the fastest method I've evolved over a decade for my large-scale NLP app. I have variations for <code>IEnumerable&lt;T&gt;</code> and other input types, with and without separators of different types (<code>Char</code>, <code>String</code>), but here I show the simple case of <strong><em>concatenating all strings in an array</em></strong> into a single string, with no separator. Latest version here is developed and unit-tested on <strong>C# 7</strong> and <strong>.NET 4.7</strong>.</p>\n\n<p>There are two keys to higher performance; the first is to pre-compute the exact total size required. This step is trivial when the input is an array as shown here. For handling <code>IEnumerable&lt;T&gt;</code> instead, it is worth first gathering the strings into a temporary array for computing that total (The array is required to avoid calling <code>ToString()</code> more than once per element since technically, given the possibility of side-effects, doing so could change the expected semantics of a 'string join' operation).</p>\n\n<p>Next, given the total allocation size of the final string, the biggest boost in performance is gained by <strong><em>building the result string in-place</em></strong>. Doing this requires the (perhaps controversial) technique of temporarily suspending the immutability of a new <code>String</code> which is initially allocated full of zeros. Any such controversy aside, however...</p>\n\n<blockquote>\n <p>...note that this is the only bulk-concatenation solution on this page which entirely avoids an <em>extra round of allocation and copying</em> by the <code>String</code> constructor.</p>\n</blockquote>\n\n<p><strong>Complete code:</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Concatenate the strings in 'rg', none of which may be null, into a single String.\n/// &lt;/summary&gt;\npublic static unsafe String StringJoin(this String[] rg)\n{\n int i;\n if (rg == null || (i = rg.Length) == 0)\n return String.Empty;\n\n if (i == 1)\n return rg[0];\n\n String s, t;\n int cch = 0;\n do\n cch += rg[--i].Length;\n while (i &gt; 0);\n if (cch == 0)\n return String.Empty;\n\n i = rg.Length;\n fixed (Char* _p = (s = new String(default(Char), cch)))\n {\n Char* pDst = _p + cch;\n do\n if ((t = rg[--i]).Length &gt; 0)\n fixed (Char* pSrc = t)\n memcpy(pDst -= t.Length, pSrc, (UIntPtr)(t.Length &lt;&lt; 1));\n while (pDst &gt; _p);\n }\n return s;\n}\n\n[DllImport(\"MSVCR120_CLR0400\", CallingConvention = CallingConvention.Cdecl)]\nstatic extern unsafe void* memcpy(void* dest, void* src, UIntPtr cb);\n</code></pre>\n\n<p>I should mention that this code has a slight modification from what I use myself. In the original, I <a href=\"https://stackoverflow.com/a/47128947/147511\">call the <strong>cpblk</strong> IL instruction</a> from <strong>C#</strong> to do the actual copying. For simplicity and portability in the code here, I replaced that with P/Invoke <code>memcpy</code> instead, as you can see. For highest performance on x64 (<a href=\"http://xoofx.com/blog/2010/10/23/high-performance-memcpy-gotchas-in-c/\" rel=\"noreferrer\">but maybe not x86</a>) you may want to use the <strong>cpblk</strong> method instead.</p>\n" }, { "answer_id": 48340975, "author": "asady", "author_id": 9239715, "author_profile": "https://Stackoverflow.com/users/9239715", "pm_score": 2, "selected": false, "text": "<p>Another solution:</p>\n\n<p>inside the loop, use List instead of string.</p>\n\n<pre><code>List&lt;string&gt; lst= new List&lt;string&gt;();\n\nfor(int i=0; i&lt;100000; i++){\n ...........\n lst.Add(...);\n}\nreturn String.Join(\"\", lst.ToArray());;\n</code></pre>\n\n<p>it is very very fast.</p>\n" }, { "answer_id": 74502341, "author": "bertasoft", "author_id": 3917318, "author_profile": "https://Stackoverflow.com/users/3917318", "pm_score": 0, "selected": false, "text": "<p>I've tested all the methods in this page and at the end I've developed my solution that is the fastest and less memory expensive.</p>\n<p>Note: tested in Framework 4.8</p>\n<p><a href=\"https://i.stack.imgur.com/PqKti.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PqKti.png\" alt=\"enter image description here\" /></a></p>\n<pre><code> [MemoryDiagnoser]\npublic class StringConcatSimple\n{\n private string\n title = &quot;Mr.&quot;, firstName = &quot;David&quot;, middleName = &quot;Patrick&quot;, lastName = &quot;Callan&quot;;\n\n [Benchmark]\n public string FastConcat()\n {\n return FastConcat(\n title, &quot; &quot;, \n firstName, &quot; &quot;,\n middleName, &quot; &quot;, \n lastName);\n }\n\n [Benchmark]\n public string StringBuilder()\n {\n var stringBuilder =\n new StringBuilder();\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringBuilderExact24()\n {\n var stringBuilder =\n new StringBuilder(24);\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringBuilderEstimate100()\n {\n var stringBuilder =\n new StringBuilder(100);\n\n return stringBuilder\n .Append(title).Append(' ')\n .Append(firstName).Append(' ')\n .Append(middleName).Append(' ')\n .Append(lastName).ToString();\n }\n\n [Benchmark]\n public string StringPlus()\n {\n return title + ' ' + firstName + ' ' +\n middleName + ' ' + lastName;\n }\n\n [Benchmark]\n public string StringFormat()\n {\n return string.Format(&quot;{0} {1} {2} {3}&quot;,\n title, firstName, middleName, lastName);\n }\n\n [Benchmark]\n public string StringInterpolation()\n {\n return\n $&quot;{title} {firstName} {middleName} {lastName}&quot;;\n }\n\n [Benchmark]\n public string StringJoin()\n {\n return string.Join(&quot; &quot;, title, firstName,\n middleName, lastName);\n }\n\n [Benchmark]\n public string StringConcat()\n {\n return string.\n Concat(new String[]\n { title, &quot; &quot;, firstName, &quot; &quot;,\n middleName, &quot; &quot;, lastName });\n }\n}\n</code></pre>\n<p>Yes, it use unsafe</p>\n<pre><code>public static unsafe string FastConcat(string str1, string str2, string str3, string str4, string str5, string str6, string str7)\n {\n var capacity = 0;\n\n var str1Length = 0;\n var str2Length = 0;\n var str3Length = 0;\n var str4Length = 0;\n var str5Length = 0;\n var str6Length = 0;\n var str7Length = 0;\n\n if (str1 != null)\n {\n str1Length = str1.Length;\n capacity = str1Length;\n }\n\n if (str2 != null)\n {\n str2Length = str2.Length;\n capacity += str2Length;\n }\n\n if (str3 != null)\n {\n str3Length = str3.Length;\n capacity += str3Length;\n }\n\n if (str4 != null)\n {\n str4Length = str4.Length;\n capacity += str4Length;\n }\n\n if (str5 != null)\n {\n str5Length = str5.Length;\n capacity += str5Length;\n }\n\n if (str6 != null)\n {\n str6Length = str6.Length;\n capacity += str6Length;\n }\n\n if (str7 != null)\n {\n str7Length = str7.Length;\n capacity += str7Length;\n }\n\n\n string result = new string(' ', capacity);\n\n fixed (char* dest = result)\n {\n var x = dest;\n\n if (str1Length &gt; 0)\n {\n fixed (char* src = str1)\n {\n Unsafe.CopyBlock(x, src, (uint)str1Length * 2); \n x += str1Length;\n }\n }\n\n if (str2Length &gt; 0)\n {\n fixed (char* src = str2)\n {\n Unsafe.CopyBlock(x, src, (uint)str2Length * 2);\n x += str2Length;\n }\n }\n\n if (str3Length &gt; 0)\n {\n fixed (char* src = str3)\n {\n Unsafe.CopyBlock(x, src, (uint)str3Length * 2);\n x += str3Length;\n }\n }\n\n if (str4Length &gt; 0)\n {\n fixed (char* src = str4)\n {\n Unsafe.CopyBlock(x, src, (uint)str4Length * 2);\n x += str4Length;\n }\n }\n\n if (str5Length &gt; 0)\n {\n fixed (char* src = str5)\n {\n Unsafe.CopyBlock(x, src, (uint)str5Length * 2);\n x += str5Length;\n }\n }\n\n if (str6Length &gt; 0)\n {\n fixed (char* src = str6)\n {\n Unsafe.CopyBlock(x, src, (uint)str6Length * 2);\n x += str6Length;\n }\n }\n\n if (str7Length &gt; 0)\n {\n fixed (char* src = str7)\n {\n Unsafe.CopyBlock(x, src, (uint)str7Length * 2);\n }\n }\n }\n\n return result;\n }\n</code></pre>\n<p>You can edit the method and adapt it to your case. For example you can make it something like</p>\n<p>public static unsafe string FastConcat(string str1, string str2, string str3 = null, string str4 = null, string str5 = null, string str6 = null, string str7 = null)</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2358/" ]
What's the most efficient way to concatenate strings?
The `StringBuilder.Append()` method is much better than using the `+` operator. But I've found that, when executing 1000 concatenations or less, `String.Join()` is even more efficient than `StringBuilder`. ``` StringBuilder sb = new StringBuilder(); sb.Append(someString); ``` The only problem with `String.Join` is that you have to concatenate the strings with a common delimiter. **Edit:** as *@ryanversaw* pointed out, you can make the delimiter `string.Empty`. ``` string key = String.Join("_", new String[] { "Customers_Contacts", customerID, database, SessionID }); ```
21,133
<p>What's the easiest way to profile a PHP script?</p> <p>I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.</p> <p>I tried experimenting with the <a href="http://php.net/microtime" rel="noreferrer">microtime</a> function:</p> <pre><code>$then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); </code></pre> <p>but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.</p>
[ { "answer_id": 21139, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": 3, "selected": false, "text": "<p>I like to use phpDebug for profiling.\n<a href=\"http://phpdebug.sourceforge.net/www/index.html\" rel=\"noreferrer\">http://phpdebug.sourceforge.net/www/index.html</a></p>\n\n<p>It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted. </p>\n\n<p>For function and class profiling I'll just use <code>microtime()</code> + <code>get_memory_usage()</code> + <code>get_peak_memory_usage()</code>. </p>\n" }, { "answer_id": 21145, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 8, "selected": false, "text": "<p>You want <a href=\"http://www.xdebug.org/\" rel=\"noreferrer\">xdebug</a> I think. Install it on the server, turn it on, pump the output through <a href=\"http://kcachegrind.sourceforge.net/html/Home.html\" rel=\"noreferrer\">kcachegrind</a> (for linux) or <a href=\"http://sourceforge.net/projects/wincachegrind/\" rel=\"noreferrer\">wincachegrind</a> (for windows) and it'll show you a few pretty charts that detail the exact timings, counts and memory usage (but you'll need another extension for that).</p>\n\n<p>It rocks, seriously :D</p>\n" }, { "answer_id": 21189, "author": "Vincent", "author_id": 1508, "author_profile": "https://Stackoverflow.com/users/1508", "pm_score": 8, "selected": true, "text": "<p>The <a href=\"http://www.php.net/apd\" rel=\"nofollow noreferrer\">PECL APD</a> extension is used as follows:</p>\n\n<pre><code>&lt;?php\napd_set_pprof_trace();\n\n//rest of the script\n?&gt;\n</code></pre>\n\n<p>After, parse the generated file using <code>pprofp</code>.</p>\n\n<p>Example output:</p>\n\n<pre><code>Trace for /home/dan/testapd.php\nTotal Elapsed Time = 0.00\nTotal System Time = 0.00\nTotal User Time = 0.00\n\n\nReal User System secs/ cumm\n%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name\n--------------------------------------------------------------------------------------\n100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main\n56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace\n28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace\n14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace\n</code></pre>\n\n<p><strong>Warning: the latest release of APD is dated 2004, the extension <a href=\"https://pecl.php.net/package/apd\" rel=\"nofollow noreferrer\">is no longer maintained</a> and has various compability issues (see comments).</strong></p>\n" }, { "answer_id": 22689, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "<p>For benchmarking, like in your example, I use the <a href=\"http://pear.php.net/package/Benchmark\" rel=\"noreferrer\">pear Benchmark</a> package. You set markers for measuring. The class also provides a few presentation helpers, or you can process the data as you see fit.</p>\n\n<p>I actually have it wrapped in another class with a __destruct method. When a script exits, the output is logged via log4php to syslog, so I have a lot of performance data to work from.</p>\n" }, { "answer_id": 6453274, "author": "Josef Sábl", "author_id": 53864, "author_profile": "https://Stackoverflow.com/users/53864", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://pecl.php.net/package/xhprof\" rel=\"noreferrer\">PECL XHPROF</a> looks interensting too. It has <a href=\"http://www2.xpay.cz/xhprof/xhprof_html/?run=4d95b7eaea1b9&amp;source=xhprof_foo\" rel=\"noreferrer\">clickable HTML interface</a> for viewing reports and pretty straightforward <a href=\"http://mirror.facebook.net/facebook/xhprof/doc.html\" rel=\"noreferrer\">documentation</a>. I have yet to test it though.</p>\n" }, { "answer_id": 8807044, "author": "luka", "author_id": 494545, "author_profile": "https://Stackoverflow.com/users/494545", "pm_score": 5, "selected": false, "text": "<p>If subtracting microtimes gives you negative results, try using the function with the argument <code>true</code> (<code>microtime(true)</code>). With <code>true</code>, the function returns a float instead of a string (as it does if it is called without arguments).</p>\n" }, { "answer_id": 15805401, "author": "user2221743", "author_id": 2221743, "author_profile": "https://Stackoverflow.com/users/2221743", "pm_score": 2, "selected": false, "text": "<p>XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to <a href=\"http://www.nusphere.com/products/php_debugger.htm\" rel=\"nofollow\">DBG debugger</a>\nIts <a href=\"http://www.nusphere.com/products/php_profiler.htm\" rel=\"nofollow\">php benchmarking</a> provides timing for functions, methods, modules and even lines.</p>\n" }, { "answer_id": 20672191, "author": "zeroasterisk", "author_id": 194105, "author_profile": "https://Stackoverflow.com/users/194105", "pm_score": 5, "selected": false, "text": "<p>Honestly, I am going to argue that using NewRelic for profiling is the best.</p>\n\n<p>It's a PHP extension which doesn't seem to slow down runtime at all and they do the monitoring for you, allowing decent drill down. In the expensive version they allow heavy drill down (but we can't afford their pricing model).</p>\n\n<p>Still, even with the free/standard plan, it's obvious and simple where most of the low hanging fruit is. I also like that it can give you an idea on DB interactions too.</p>\n\n<p><img src=\"https://i.stack.imgur.com/hjuEU.png\" alt=\"screenshot of one of the interfaces when profiling\"></p>\n" }, { "answer_id": 29022400, "author": "TimH - Codidact", "author_id": 382254, "author_profile": "https://Stackoverflow.com/users/382254", "pm_score": 7, "selected": false, "text": "<p><strong>No extensions are needed, just use these two functions for simple profiling.</strong></p>\n\n<pre><code>// Call this at each point of interest, passing a descriptive string\nfunction prof_flag($str)\n{\n global $prof_timing, $prof_names;\n $prof_timing[] = microtime(true);\n $prof_names[] = $str;\n}\n\n// Call this when you're done and want to see the results\nfunction prof_print()\n{\n global $prof_timing, $prof_names;\n $size = count($prof_timing);\n for($i=0;$i&lt;$size - 1; $i++)\n {\n echo \"&lt;b&gt;{$prof_names[$i]}&lt;/b&gt;&lt;br&gt;\";\n echo sprintf(\"&amp;nbsp;&amp;nbsp;&amp;nbsp;%f&lt;br&gt;\", $prof_timing[$i+1]-$prof_timing[$i]);\n }\n echo \"&lt;b&gt;{$prof_names[$size-1]}&lt;/b&gt;&lt;br&gt;\";\n}\n</code></pre>\n\n<p><strong>Here is an example, calling prof_flag() with a description at each checkpoint, and prof_print() at the end:</strong></p>\n\n<pre><code>prof_flag(\"Start\");\n\n include '../lib/database.php';\n include '../lib/helper_func.php';\n\nprof_flag(\"Connect to DB\");\n\n connect_to_db();\n\nprof_flag(\"Perform query\");\n\n // Get all the data\n\n $select_query = \"SELECT * FROM data_table\";\n $result = mysql_query($select_query);\n\nprof_flag(\"Retrieve data\");\n\n $rows = array();\n $found_data=false;\n while($r = mysql_fetch_assoc($result))\n {\n $found_data=true;\n $rows[] = $r;\n }\n\nprof_flag(\"Close DB\");\n\n mysql_close(); //close database connection\n\nprof_flag(\"Done\");\nprof_print();\n</code></pre>\n\n<p><strong>Output looks like this:</strong></p>\n\n<p><b>Start</b><br>&nbsp;&nbsp;&nbsp;0.004303<br><b>Connect to DB</b><br>&nbsp;&nbsp;&nbsp;0.003518<br><b>Perform query</b><br>&nbsp;&nbsp;&nbsp;0.000308<br><b>Retrieve data</b><br>&nbsp;&nbsp;&nbsp;0.000009<br><b>Close DB</b><br>&nbsp;&nbsp;&nbsp;0.000049<br><b>Done</b><br></p>\n" }, { "answer_id": 32853739, "author": "Ali", "author_id": 4960774, "author_profile": "https://Stackoverflow.com/users/4960774", "pm_score": 3, "selected": false, "text": "<p>I would defiantly give <a href=\"https://blackfire.io\" rel=\"noreferrer\">BlackFire</a> a try. </p>\n\n<p>There is this virtualBox I've put together using <a href=\"https://puphpet.com/\" rel=\"noreferrer\">puphpet</a>, to test different php frameworks which coms with BlackFire, please feel free to fork and/or distribute if required :) </p>\n\n<p><a href=\"https://github.com/webit4me/PHPFrameworks\" rel=\"noreferrer\">https://github.com/webit4me/PHPFrameworks</a></p>\n" }, { "answer_id": 39378588, "author": "bishop", "author_id": 2908724, "author_profile": "https://Stackoverflow.com/users/2908724", "pm_score": 4, "selected": false, "text": "<p>Poor man's profiling, no extensions required. Supports nested profiles and percent of total:</p>\n\n<pre><code>function p_open($flag) {\n global $p_times;\n if (null === $p_times)\n $p_times = [];\n if (! array_key_exists($flag, $p_times))\n $p_times[$flag] = [ 'total' =&gt; 0, 'open' =&gt; 0 ];\n $p_times[$flag]['open'] = microtime(true);\n}\n\nfunction p_close($flag)\n{\n global $p_times;\n if (isset($p_times[$flag]['open'])) {\n $p_times[$flag]['total'] += (microtime(true) - $p_times[$flag]['open']);\n unset($p_times[$flag]['open']);\n }\n}\n\nfunction p_dump()\n{\n global $p_times;\n $dump = [];\n $sum = 0;\n foreach ($p_times as $flag =&gt; $info) {\n $dump[$flag]['elapsed'] = $info['total'];\n $sum += $info['total'];\n }\n foreach ($dump as $flag =&gt; $info) {\n $dump[$flag]['percent'] = $dump[$flag]['elapsed']/$sum;\n }\n return $dump;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&lt;?php\n\np_open('foo');\nsleep(1);\np_open('bar');\nsleep(2);\np_open('baz');\nsleep(3);\np_close('baz');\nsleep(2);\np_close('bar');\nsleep(1);\np_close('foo');\n\nvar_dump(p_dump());\n</code></pre>\n\n<p>Yields:</p>\n\n<pre><code>array:3 [\n \"foo\" =&gt; array:2 [\n \"elapsed\" =&gt; 9.000766992569\n \"percent\" =&gt; 0.4736904954747\n ]\n \"bar\" =&gt; array:2 [\n \"elapsed\" =&gt; 7.0004580020905\n \"percent\" =&gt; 0.36841864946596\n ]\n \"baz\" =&gt; array:2 [\n \"elapsed\" =&gt; 3.0001420974731\n \"percent\" =&gt; 0.15789085505934\n ]\n]\n</code></pre>\n" }, { "answer_id": 45512462, "author": "Matt S", "author_id": 163024, "author_profile": "https://Stackoverflow.com/users/163024", "pm_score": 6, "selected": false, "text": "<p><em>Cross posting my reference from SO Documentation beta which is going offline.</em></p>\n<h2>Profiling with XDebug</h2>\n<p>An extension to PHP called Xdebug is available to assist in <a href=\"https://xdebug.org/docs/profiler\" rel=\"noreferrer\">profiling PHP applications</a>, as well as runtime debugging. When running the profiler, the output is written to a file in a binary format called &quot;cachegrind&quot;. Applications are available on each platform to analyze these files. <strong>No application code changes are necessary to perform this profiling.</strong></p>\n<p>To enable profiling, install the extension and adjust php.ini settings. Some Linux distributions come with standard packages (e.g. Ubuntu's <code>php-xdebug</code> package). In our example we will run the profile optionally based on a request parameter. This allows us to keep settings static and turn on the profiler only as needed.</p>\n<pre><code># php.ini settings\n# Set to 1 to turn it on for every request\nxdebug.profiler_enable = 0\n# Let's use a GET/POST parameter to turn on the profiler\nxdebug.profiler_enable_trigger = 1\n# The GET/POST value we will pass; empty for any value\nxdebug.profiler_enable_trigger_value = &quot;&quot;\n# Output cachegrind files to /tmp so our system cleans them up later\nxdebug.profiler_output_dir = &quot;/tmp&quot;\nxdebug.profiler_output_name = &quot;cachegrind.out.%p&quot;\n</code></pre>\n<p>Next use a web client to make a request to your application's URL you wish to profile, e.g.</p>\n<pre><code>http://example.com/article/1?XDEBUG_PROFILE=1\n</code></pre>\n<p>As the page processes it will write to a file with a name similar to</p>\n<pre><code>/tmp/cachegrind.out.12345\n</code></pre>\n<p>By default the number in the filename is the process id which wrote it. This is configurable with the <code>xdebug.profiler_output_name</code> setting.</p>\n<p>Note that it will write one file for each PHP request / process that is executed. So, for example, if you wish to analyze a form post, one profile will be written for the GET request to display the HTML form. The XDEBUG_PROFILE parameter will need to be passed into the subsequent POST request to analyze the second request which processes the form. Therefore when profiling it is sometimes easier to run curl to POST a form directly.</p>\n<p><strong>Analyzing the Output</strong></p>\n<p>Once written the profile cache can be read by an application such as <a href=\"https://github.com/KDE/kcachegrind\" rel=\"noreferrer\">KCachegrind</a> or <a href=\"https://github.com/jokkedk/webgrind\" rel=\"noreferrer\">Webgrind</a>. PHPStorm, a popular PHP IDE, can also <a href=\"https://www.jetbrains.com/help/phpstorm/profiling-with-xdebug.html\" rel=\"noreferrer\">display this profiling data</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/ENtOu.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ENtOu.gif\" alt=\"KCachegrind\" /></a></p>\n<p>KCachegrind, for example, will display information including:</p>\n<ul>\n<li>Functions executed</li>\n<li>Call time, both itself and inclusive of subsequent function calls</li>\n<li>Number of times each function is called</li>\n<li>Call graphs</li>\n<li>Links to source code</li>\n</ul>\n<p><strong>What to Look For</strong></p>\n<p>Obviously performance tuning is very specific to each application's use cases. In general it's good to look for:</p>\n<ul>\n<li>Repeated calls to the same function you wouldn't expect to see. For functions that process and query data these could be prime opportunities for your application to cache.</li>\n<li>Slow-running functions. Where is the application spending most of its time? the best payoff in performance tuning is focusing on those parts of the application which consume the most time.</li>\n</ul>\n<p><em>Note</em>: Xdebug, and in particular its profiling features, are very resource intensive and slow down PHP execution. It is recommended to not run these in a production server environment.</p>\n" }, { "answer_id": 60036814, "author": "Jacek Dziurdzikowski", "author_id": 7445770, "author_profile": "https://Stackoverflow.com/users/7445770", "pm_score": 4, "selected": false, "text": "<p>You all should definitely check this new php profiler.</p>\n\n<p><a href=\"https://github.com/NoiseByNorthwest/php-spx\" rel=\"noreferrer\">https://github.com/NoiseByNorthwest/php-spx</a></p>\n\n<p>It redefines the way of how php profilers collects and presents the result.\nInstead of outputting just a total number of particular function calls and total time spent of executing it - PHP-SPX presents the whole timeline of request execution in a perfectly readable way. Below is the screen of GUI it provides.</p>\n\n<p><a href=\"https://i.stack.imgur.com/g772h.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/g772h.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
What's the easiest way to profile a PHP script? I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions. I tried experimenting with the [microtime](http://php.net/microtime) function: ``` $then = microtime(); myFunc(); $now = microtime(); echo sprintf("Elapsed: %f", $now-$then); ``` but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.
The [PECL APD](http://www.php.net/apd) extension is used as follows: ``` <?php apd_set_pprof_trace(); //rest of the script ?> ``` After, parse the generated file using `pprofp`. Example output: ``` Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace ``` **Warning: the latest release of APD is dated 2004, the extension [is no longer maintained](https://pecl.php.net/package/apd) and has various compability issues (see comments).**
21,184
<p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p> <p>Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?</p>
[ { "answer_id": 21389, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 6, "selected": true, "text": "<p>If you have your linq-query that contains all the rows you want to display, this code can be used:</p>\n\n<pre><code>var pageNum = 3;\nvar pageSize = 20;\nquery = query.Skip((pageNum - 1) * pageSize).Take(pageSize);\n</code></pre>\n\n<p>You can also make an extension method on the object to be able to write</p>\n\n<pre><code>query.Page(2,50)\n</code></pre>\n\n<p>to get the first 50 records of page 2. If that is want you want, the information is on the <a href=\"http://solidcoding.blogspot.com/2007/11/paging-with-linq.html\" rel=\"noreferrer\">solid code blog.</a></p>\n" }, { "answer_id": 442698, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 3, "selected": false, "text": "<p>Hi There is a wicked thing called PagedList which i got when watching a Rob Conery Screen Cast. </p>\n\n<p><a href=\"http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/\" rel=\"noreferrer\">http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/</a></p>\n\n<p>It has all the Skip and Take stuff built in.</p>\n\n<p>All you do is call</p>\n\n<pre><code>var query = from item in DB.Table\nwhere item.Field == 1\norderby item.Field2\nselect item;\n\nPagedList&lt;MyType&gt; pagedList = query.ToPagedList(pageIndex, pageSize);\n</code></pre>\n\n<p>Hope it helps.. I'm using it now and it works ok for linq to entities. With Linq to entities you have to perform an Orderby before you can use Skip and Take.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I've got a System.Generic.Collections.List(Of MyCustomClass) type object. Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?
If you have your linq-query that contains all the rows you want to display, this code can be used: ``` var pageNum = 3; var pageSize = 20; query = query.Skip((pageNum - 1) * pageSize).Take(pageSize); ``` You can also make an extension method on the object to be able to write ``` query.Page(2,50) ``` to get the first 50 records of page 2. If that is want you want, the information is on the [solid code blog.](http://solidcoding.blogspot.com/2007/11/paging-with-linq.html)
21,207
<p>I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? </p>
[ { "answer_id": 24499, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 7, "selected": true, "text": "<p>We run DB40 .NET version in a large client/server project.</p>\n\n<p>Our experiences is that you can potentially get much better performance than typical relational databases.</p>\n\n<p>However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship.</p>\n\n<p>Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects.</p>\n\n<p>Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want.</p>\n\n<p>Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these \"reflection\" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index(\"someField\"), which is not strongly typed.</p>\n\n<p>We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database.</p>\n\n<p>We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database.</p>\n\n<p>We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing:</p>\n\n<pre><code>// C# syntax for \"Find all MyFoos with Bar == 23\".\n// (Note the Java syntax is more verbose using the Predicate class.)\nIList&lt;MyFoo&gt; results = db4o.Query&lt;MyFoo&gt;(input =&gt; input.Bar == 23);\n</code></pre>\n\n<p>Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed.</p>\n\n<p>For .NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries.</p>\n\n<p>DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.)</p>\n\n<p>If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it.</p>\n\n<p><strong>update July 2015</strong> Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.</p>\n" }, { "answer_id": 89120, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 2, "selected": false, "text": "<p>Main problem I've encountered with it is reporting. There just doesn't seem to be any way to run efficient reports against a db4o data source.</p>\n" }, { "answer_id": 145605, "author": "Goran", "author_id": 23164, "author_profile": "https://Stackoverflow.com/users/23164", "pm_score": 2, "selected": false, "text": "<p>Most native queries can and are efficiently converted into SODA queries behind the scenes so that should not make a difference. Using NQ is of course preferred as you remain in the realms of strong typed language. If you have problems getting NQ to use indexes please feel free to post your problem to the <a href=\"http://developer.db4o.com/forums/\" rel=\"nofollow noreferrer\">db4o forums</a> and we'll try to help you out.</p>\n\n<p>Goran</p>\n" }, { "answer_id": 171901, "author": "Keith Patton", "author_id": 25255, "author_profile": "https://Stackoverflow.com/users/25255", "pm_score": 0, "selected": false, "text": "<p>Judah, it sounds like you are not using transparent activation, which is a feature of the latest production version (7.4)? Perhaps if you specified the version you are using as there may be other issues which are now resolved in the latest version?</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562/" ]
I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o?
We run DB40 .NET version in a large client/server project. Our experiences is that you can potentially get much better performance than typical relational databases. However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship. Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects. Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want. Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed. We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database. We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database. We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing: ``` // C# syntax for "Find all MyFoos with Bar == 23". // (Note the Java syntax is more verbose using the Predicate class.) IList<MyFoo> results = db4o.Query<MyFoo>(input => input.Bar == 23); ``` Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed. For .NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries. DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.) If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it. **update July 2015** Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.
21,232
<p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p> <p>Given integer varaibles pagesize and pagenumber, how can I collect only any single page of <code>MyCustomClass</code> objects?</p> <p>This is what I've got. How can I improve it?</p> <pre><code>'my given collection and paging parameters Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN Dim pagesize As Integer = GIVEN Dim pagenumber As Integer = GIVEN 'collect current page objects Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass) Dim objcount As Integer = 1 For Each obj As MyCustomClass In AllOfMyCustomClassObjects If objcount &gt; pagesize * (pagenumber - 1) And count &lt;= pagesize * pagenumber Then PageObjects.Add(obj) End If objcount = objcount + 1 Next 'find total page count Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize)) If objcount Mod pagesize &gt; 0 Then totalpages = totalpages + 1 End If </code></pre>
[ { "answer_id": 21267, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>You use GetRange on your IEnuramble implementing collection:</p>\n\n<pre><code>List&lt;int&gt; lolInts = new List&lt;int&gt;();\n\nfor (int i = 0; i &lt;= 100; i++)\n{\n lolInts.Add(i);\n}\n\nList&lt;int&gt; page1 = lolInts.GetRange(0, 49);\nList&lt;int&gt; page2 = lilInts.GetRange(50, 100);\n</code></pre>\n\n<p>I trust you can figure out how to use GetRange to grab an individual page from here.</p>\n" }, { "answer_id": 21268, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 2, "selected": false, "text": "<p>Generic.List should provide the Skip() and Take() methods, so you could do this:</p>\n\n<pre><code>Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)\nPageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)\n</code></pre>\n\n<hr>\n\n<p>If by \"without Linq\" you meant on the 2.0 Framework, I don't believe List(Of T) supports those methods. In that case, use GetRange like Jonathan suggested.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I've got a System.Generic.Collections.List(Of MyCustomClass) type object. Given integer varaibles pagesize and pagenumber, how can I collect only any single page of `MyCustomClass` objects? This is what I've got. How can I improve it? ``` 'my given collection and paging parameters Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN Dim pagesize As Integer = GIVEN Dim pagenumber As Integer = GIVEN 'collect current page objects Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass) Dim objcount As Integer = 1 For Each obj As MyCustomClass In AllOfMyCustomClassObjects If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then PageObjects.Add(obj) End If objcount = objcount + 1 Next 'find total page count Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize)) If objcount Mod pagesize > 0 Then totalpages = totalpages + 1 End If ```
Generic.List should provide the Skip() and Take() methods, so you could do this: ``` Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass) PageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize) ``` --- If by "without Linq" you meant on the 2.0 Framework, I don't believe List(Of T) supports those methods. In that case, use GetRange like Jonathan suggested.
21,265
<p>What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.</p>
[ { "answer_id": 21277, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 4, "selected": true, "text": "<p>The best approach I think is to compare <a href=\"http://en.wikipedia.org/wiki/Unit_in_the_last_place\" rel=\"noreferrer\">ULPs</a>.</p>\n\n<pre><code>bool is_nan(float f)\n{\n return (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x7f800000) == 0x7f800000 &amp;&amp; (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x007fffff) != 0;\n}\n\nbool is_finite(float f)\n{\n return (*reinterpret_cast&lt;unsigned __int32*&gt;(&amp;f) &amp; 0x7f800000) != 0x7f800000;\n}\n\n// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)\n// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other\n#define UNEQUAL_NANS 1\n// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)\n// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX\n#define INFINITE_INFINITIES 1\n\n// test whether two IEEE floats are within a specified number of representable values of each other\n// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers\nbool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)\n{\n#ifdef UNEQUAL_NANS\n if(is_nan(lhs) || is_nan(rhs))\n {\n return false;\n }\n#endif\n#ifdef INFINITE_INFINITIES\n if((is_finite(lhs) &amp;&amp; !is_finite(rhs)) || (!is_finite(lhs) &amp;&amp; is_finite(rhs)))\n {\n return false;\n }\n#endif\n signed __int32 left(*reinterpret_cast&lt;signed __int32*&gt;(&amp;lhs));\n // transform signed magnitude ints into 2s complement signed ints\n if(left &lt; 0)\n {\n left = 0x80000000 - left;\n }\n signed __int32 right(*reinterpret_cast&lt;signed __int32*&gt;(&amp;rhs));\n // transform signed magnitude ints into 2s complement signed ints\n if(right &lt; 0)\n {\n right = 0x80000000 - right;\n }\n if(static_cast&lt;unsigned __int32&gt;(std::abs(left - right)) &lt;= max_ulp_difference)\n {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are.</p>\n\n<p>I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.</p>\n" }, { "answer_id": 21279, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 0, "selected": false, "text": "<p>Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.</p>\n" }, { "answer_id": 21291, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.</p>\n</blockquote>\n\n<p>Even if it causes it to copy from vector registers to integer registers via memory, and even if it stalls the pipeline, it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.</p>\n\n<p>i.e. it is a price worth paying.</p>\n" }, { "answer_id": 21298, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 2, "selected": false, "text": "<p>The current version I am using is this</p>\n\n<pre><code>bool is_equals(float A, float B,\n float maxRelativeError, float maxAbsoluteError)\n{\n\n if (fabs(A - B) &lt; maxAbsoluteError)\n return true;\n\n float relativeError;\n if (fabs(B) &gt; fabs(A))\n relativeError = fabs((A - B) / B);\n else\n relativeError = fabs((A - B) / A);\n\n if (relativeError &lt;= maxRelativeError)\n return true;\n\n return false;\n}\n</code></pre>\n\n<p>This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?</p>\n" }, { "answer_id": 21307, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.</p>\n</blockquote>\n\n<p>If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.</p>\n" }, { "answer_id": 21312, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?</p>\n</blockquote>\n\n<p>ULPs are a direct measure of the \"distance\" between two floating point numbers. This means that they don't require you to conjure up the relative and absolute error values, nor do you have to make sure to get those values \"about right\". With ULPs, you can express directly how close you want the numbers to be, and the same threshold works just as well for small values as for large ones.</p>\n" }, { "answer_id": 21317, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.</p>\n</blockquote>\n\n<p>Even if we do the numeric analysis to minimize accumulation of error, we can't eliminate it and we can be left with results that ought to be identical (if we were calculating with reals) but differ (because we cannot calculate with reals).</p>\n" }, { "answer_id": 21318, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n" }, { "answer_id": 21323, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n</blockquote>\n\n<p>Perhaps we cannot afford the loss of range or performance that such an approach would inflict.</p>\n" }, { "answer_id": 21337, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.</p>\n</blockquote>\n\n<p>Perhaps I should explain the problem better. In C++, the following code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\n\nint main()\n{\n float a = 1.0;\n float b = 0.0;\n\n for(int i=0;i&lt;10;++i)\n {\n b+=0.1;\n }\n\n if(a != b)\n {\n cout &lt;&lt; \"Something is wrong\" &lt;&lt; endl;\n }\n\n return 1;\n}\n</code></pre>\n\n<p>prints the phrase \"Something is wrong\". Are you saying that it should?</p>\n" }, { "answer_id": 21374, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>@DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).</p>\n\n<p>@Craig H: Sure. I'm totally okay with it printing that. If a or b store money then they should be represented in fixed point. I'm struggling to think of a real world example where such logic ought to be allied to floats. Things suitable for floats:</p>\n\n<ul>\n<li>weights</li>\n<li>ranks</li>\n<li>distances</li>\n<li>real world values (like from a ADC)</li>\n</ul>\n\n<p>For all these things, either you much then numbers and simply present the results to the user for human interpretation, or you make a comparative statement (even if such a statement is, \"this thing is within 0.001 of this other thing\"). A comparative statement like mine is only useful in the context of the algorithm: the \"within 0.001\" part depends on what <em>physical</em> question you're asking. That my 0.02. Or should I say 2/100ths?</p>\n" }, { "answer_id": 21384, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>@DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).</p>\n</blockquote>\n\n<p>It rather depends on what you are doing with them. A fixed-point type with the same range as an IEEE float would be many many times slower (and many times larger). </p>\n\n<blockquote>\n <p>Things suitable for floats:</p>\n</blockquote>\n\n<p>3D graphics, physics/engineering, simulation, climate simulation....</p>\n" }, { "answer_id": 21426, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>It rather depends on what you are\n doing with them. A fixed-point type\n with the same range as an IEEE float\n would be many many times slower (and\n many times larger).</p>\n</blockquote>\n\n<p>Okay, but if I want a infinitesimally small bit-resolution then it's back to my original point: == and != have no meaning in the context of such a problem.</p>\n\n<p>An int lets me express ~10^9 values (regardless of the range) which seems like enough for any situation where I would care about two of them being equal. And if that's not enough, use a 64-bit OS and you've got about 10^19 distinct values.</p>\n\n<p>I can express values a range of 0 to 10^200 (for example) in an int, it is just the bit-resolution that suffers (resolution would be greater than 1, but, again, no application has that sort of range as well as that sort of resolution).</p>\n\n<p>To summarize, I think in all cases one either is representing a continuum of values, in which case != and == are irrelevant, or one is representing a fixed set of values, which can be mapped to an int (or a another fixed-precision type).</p>\n" }, { "answer_id": 187426, "author": "jakobengblom2", "author_id": 23054, "author_profile": "https://Stackoverflow.com/users/23054", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>An int lets me express ~10^9 values\n (regardless of the range) which seems\n like enough for any situation where I\n would care about two of them being\n equal. And if that's not enough, use a\n 64-bit OS and you've got about 10^19\n distinct values.</p>\n</blockquote>\n\n<p>I have actually hit that limit... I was trying to juggle times in ps and time in clock cycles in a simulation where you easily hit 10^10 cycles. No matter what I did I very quickly overflowed the puny range of 64-bit integers... 10^19 is not as much as you think it is, gimme 128 bits computing now! </p>\n\n<p>Floats allowed me to get a solution to the mathematical issues, as the values overflowed with lots zeros at the low end. So you basically had a decimal point floating aronud in the number with no loss of precision (I could like with the more limited distinct number of values allowed in the mantissa of a float compared to a 64-bit int, but desperately needed th range!). </p>\n\n<p>And then things converted back to integers to compare etc. </p>\n\n<p>Annoying, and in the end I scrapped the entire attempt and just relied on floats and &lt; and > to get the work done. Not perfect, but works for the use case envisioned. </p>\n" }, { "answer_id": 10973098, "author": "Michael Lehn", "author_id": 909565, "author_profile": "https://Stackoverflow.com/users/909565", "pm_score": 1, "selected": false, "text": "<p>In numerical software you often want to test whether two floating point numbers are <em>exactly</em> equal. LAPACK is full of examples for such cases. Sure, the most common case is where you want to test whether a floating point number equals \"Zero\", \"One\", \"Two\", \"Half\". If anyone is interested I can pick some algorithms and go more into detail.</p>\n\n<p>Also in BLAS you often want to check whether a floating point number is exactly Zero or One. For example, the routine dgemv can compute operations of the form</p>\n\n<ul>\n<li>y = beta*y + alpha*A*x</li>\n<li>y = beta*y + alpha*A^T*x</li>\n<li>y = beta*y + alpha*A^H*x</li>\n</ul>\n\n<p>So if beta equals One you have an \"plus assignment\" and for beta equals Zero a \"simple assignment\". So you certainly can cut the computational cost if you give these (common) cases a special treatment.</p>\n\n<p>Sure, you could design the BLAS routines in such a way that you can avoid exact comparisons (e.g. using some flags). However, the LAPACK is full of examples where it is not possible.</p>\n\n<p>P.S.:</p>\n\n<ul>\n<li><p>There are certainly many cases where you don't want check for \"is exactly equal\". For many people this even might be the only case they ever have to deal with. All I want to point out is that there are other cases too.</p></li>\n<li><p>Although LAPACK is written in Fortran the logic is the same if you are using other programming languages for numerical software.</p></li>\n</ul>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.
The best approach I think is to compare [ULPs](http://en.wikipedia.org/wiki/Unit_in_the_last_place). ``` bool is_nan(float f) { return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0; } bool is_finite(float f) { return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000; } // if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point) // if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other #define UNEQUAL_NANS 1 // if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater) // if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX #define INFINITE_INFINITIES 1 // test whether two IEEE floats are within a specified number of representable values of each other // This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference) { #ifdef UNEQUAL_NANS if(is_nan(lhs) || is_nan(rhs)) { return false; } #endif #ifdef INFINITE_INFINITIES if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs))) { return false; } #endif signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs)); // transform signed magnitude ints into 2s complement signed ints if(left < 0) { left = 0x80000000 - left; } signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs)); // transform signed magnitude ints into 2s complement signed ints if(right < 0) { right = 0x80000000 - right; } if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference) { return true; } return false; } ``` A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are. I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.
21,280
<p>I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.</p> <p>I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?</p>
[ { "answer_id": 21287, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 2, "selected": false, "text": "<p>The point is that LINQ integrates your queries into your primary programming language, allowing your IDE to provide you with some facilities (Intellisense and debug support, for example) that you otherwise would not have, and to allow the compiler to type-check your SQL code (which is impossible with a normal string query).</p>\n" }, { "answer_id": 21292, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "<p>LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.</p>\n\n<p>LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.</p>\n\n<p>Take the task of finding the intersection of two lists:</p>\n\n<p>Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code.</p>\n\n<pre><code>foreach (int number in list1)\n{\n foreach (int number2 in list2)\n {\n if (number2 == number)\n {\n returnList.add(number2);\n }\n }\n}\n</code></pre>\n\n<p>Using LINQ, it does the same thing in one line of code:</p>\n\n<pre><code>var results = list1.Intersect(list2);\n</code></pre>\n\n<p>You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.</p>\n" }, { "answer_id": 21331, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 3, "selected": false, "text": "<p>So the really, really big deal about LINQ has nothing to do with Linq to SQL. It's about the enhancements it brought to the C# language itself.</p>\n" }, { "answer_id": 21418, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>LINQ is not just an ORM system, as Jonathan pointed out it brings a lot of functional programming elements to C#. And it lets you do a lot of \"database-y\" things in regular C# code. It's difficult to explain just how incredibly powerful that can be. Consider how much having solid, well designed generic data structures (such as list, stack, dictionary/hash, etc.) included in common frameworks has improved the state of development in modern languages. Precisely because using these data structures is very common and reducing the intellectual overhead of using them is a huge benefit. LINQ doesn't do anything you can't do yourself, but it makes a lot of operations a lot more straightforward and a lot easier.</p>\n\n<p>Consider the time-honored example of removing duplicates from a non-ordered list. In a lower level language like C or C++ you'd probably have to sort the list and maintain two indices into the list as you removed dupes. In a language with hashes (Java, C#, Javascript, Perl, etc.) you could create a hash where the keys are the unique values, then extract the keys into a new list. With LINQ you could just do this:</p>\n\n<pre><code>int[] data = { 0, 1, 3, 3, 7, 8, 0, 9, 2, 1 };\n\nvar uniqueData = data.GroupBy(i =&gt; i).Select(g =&gt; g.Key);\n</code></pre>\n" }, { "answer_id": 80709, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 4, "selected": false, "text": "<p>Before:</p>\n\n<pre><code>// Init Movie\nm_ImageArray = new Image[K_NB_IMAGE];\n\nStream l_ImageStream = null;\nBitmap l_Bitmap = null;\n\n// get a reference to the current assembly\nAssembly l_Assembly = Assembly.GetExecutingAssembly();\n\n// get a list of resource names from the manifest\nstring[] l_ResourceName = l_Assembly.GetManifestResourceNames();\n\nforeach (string l_Str in l_ResourceName)\n{\n if (l_Str.EndsWith(\".png\"))\n {\n // attach to stream to the resource in the manifest\n l_ImageStream = l_Assembly.GetManifestResourceStream(l_Str);\n if (!(null == l_ImageStream))\n {\n // create a new bitmap from this stream and \n // add it to the arraylist\n l_Bitmap = Bitmap.FromStream(l_ImageStream) as Bitmap;\n if (!(null == l_Bitmap))\n {\n int l_Index = Convert.ToInt32(l_Str.Substring(l_Str.Length - 6, 2));\n l_Index -= 1;\n if (l_Index &lt; 0) l_Index = 0;\n if (l_Index &gt; K_NB_IMAGE) l_Index = K_NB_IMAGE;\n m_ImageArray[l_Index] = l_Bitmap;\n }\n l_Bitmap = null;\n l_ImageStream.Close();\n l_ImageStream = null;\n } // if\n } // if\n} // foreach\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>Assembly l_Assembly = Assembly.GetExecutingAssembly();\n\n//Linq is the tops\nm_ImageList = l_Assembly.GetManifestResourceNames()\n .Where(a =&gt; a.EndsWith(\".png\"))\n .OrderBy(b =&gt; b)\n .Select(c =&gt; l_Assembly.GetManifestResourceStream(c))\n .Where(d =&gt; d != null) //ImageStream not null\n .Select(e =&gt; Bitmap.FromStream(e))\n .Where(f =&gt; f != null) //Bitmap not null\n .ToList();\n</code></pre>\n\n<p>Or, alternatively (<em>query syntax</em>):</p>\n\n<pre><code>Assembly l_Assembly = Assembly.GetExecutingAssembly();\n\n//Linq is the tops\nm_ImageList = (\n from resource in l_Assembly.GetManifestResourceNames()\n where resource.EndsWith(\".png\")\n orderby resource\n let imageStream = l_Assembly.GetManifestResourceStream(resource)\n where imageStream != null\n let bitmap = Bitmap.FromStream(imageStream)\n where bitmap != null)\n .ToList();\n</code></pre>\n" }, { "answer_id": 641324, "author": "Jacob Stanley", "author_id": 72821, "author_profile": "https://Stackoverflow.com/users/72821", "pm_score": 2, "selected": false, "text": "<p>Because linq is really monads in sql clothing, I'm using it on a project to make asynchronous web requests with the continuation monad, and it's proving to work really well!</p>\n\n<p>Check out these articles:\n<a href=\"http://www.aboutcode.net/2008/01/14/Async+WebRequest+Using+LINQ+Syntax.aspx\" rel=\"nofollow noreferrer\">http://www.aboutcode.net/2008/01/14/Async+WebRequest+Using+LINQ+Syntax.aspx</a>\n<a href=\"http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx</a></p>\n\n<p>From the first article:</p>\n\n<pre><code> var requests = new[] \n {\n WebRequest.Create(\"http://www.google.com/\"),\n WebRequest.Create(\"http://www.yahoo.com/\"),\n WebRequest.Create(\"http://channel9.msdn.com/\")\n };\n\n var pages = from request in requests\n select\n from response in request.GetResponseAsync()\n let stream = response.GetResponseStream()\n from html in stream.ReadToEndAsync()\n select new { html, response };\n\n foreach (var page in pages)\n {\n page(d =&gt;\n {\n Console.WriteLine(d.response.ResponseUri.ToString());\n Console.WriteLine(d.html.Substring(0, 40));\n Console.WriteLine();\n });\n }\n</code></pre>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things. I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?
LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects. LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time. Take the task of finding the intersection of two lists: Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N\*M), and takes about 10 lines of code. ``` foreach (int number in list1) { foreach (int number2 in list2) { if (number2 == number) { returnList.add(number2); } } } ``` Using LINQ, it does the same thing in one line of code: ``` var results = list1.Intersect(list2); ``` You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.
21,294
<p>How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.</p> <p>The client that uses the component isn't required to load all the library script files (and manually insert <code>&lt;script&gt;</code> tags into their web page) that implement this component - just the 'main' component script file.</p> <p><strong>How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?</strong> Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?</p> <p>An addition to this question: <strong>is there a way to handle the event after a dynamically included JavaScript file is loaded?</strong> Prototype has <code>document.observe</code> for document-wide events. Example:</p> <pre><code>document.observe("dom:loaded", function() { // initially hide all containers for tab content $$('div.tabcontent').invoke('hide'); }); </code></pre> <p><strong>What are the available events for a script element?</strong></p>
[ { "answer_id": 21297, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 3, "selected": false, "text": "<p>Here is some example code I've found... does anyone have a better way?</p>\n\n<pre><code> function include(url)\n {\n var s = document.createElement(\"script\");\n s.setAttribute(\"type\", \"text/javascript\");\n s.setAttribute(\"src\", url);\n var nodes = document.getElementsByTagName(\"*\");\n var node = nodes[nodes.length -1].parentNode;\n node.appendChild(s);\n }\n</code></pre>\n" }, { "answer_id": 21300, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control</p>\n\n<pre><code>var loader = new YAHOO.util.YUILoader({\n\n require: ['calendar'], // what components?\n\n base: '../../build/',//where do they live?\n\n //filter: \"DEBUG\", //use debug versions (or apply some\n //some other filter?\n\n //loadOptional: true, //load all optional dependencies?\n\n //onSuccess is the function that YUI Loader\n //should call when all components are successfully loaded.\n onSuccess: function() {\n //Once the YUI Calendar Control and dependencies are on\n //the page, we'll verify that our target container is \n //available in the DOM and then instantiate a default\n //calendar into it:\n YAHOO.util.Event.onAvailable(\"calendar_container\", function() {\n var myCal = new YAHOO.widget.Calendar(\"mycal_id\", \"calendar_container\");\n myCal.render();\n })\n },\n\n // should a failure occur, the onFailure function will be executed\n onFailure: function(o) {\n alert(\"error: \" + YAHOO.lang.dump(o));\n }\n\n });\n\n// Calculate the dependency and insert the required scripts and css resources\n// into the document\nloader.insert();\n</code></pre>\n" }, { "answer_id": 21311, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 4, "selected": false, "text": "<p>I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the <code>head</code> element to get the job done. I simply created an <code>include</code> function (code below) to handle both script and CSS files.</p>\n<p>This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically. It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.</p>\n<pre><code>function include( url, type ){\n // First make sure it hasn't been loaded by something else.\n if( Array.contains( includedFile, url ) )\n return;\n \n // Determine the MIME type.\n var jsExpr = new RegExp( &quot;js$&quot;, &quot;i&quot; );\n var cssExpr = new RegExp( &quot;css$&quot;, &quot;i&quot; );\n if( type == null )\n if( jsExpr.test( url ) )\n type = 'text/javascript';\n else if( cssExpr.test( url ) )\n type = 'text/css';\n \n // Create the appropriate element.\n var element = null;\n switch( type ){\n case 'text/javascript' :\n element = document.createElement( 'script' );\n element.type = type;\n element.src = url;\n break;\n case 'text/css' :\n element = document.createElement( 'link' );\n element.rel = 'stylesheet';\n element.type = type;\n element.href = url;\n break;\n }\n \n // Insert it to the &lt;head&gt; and the array to ensure it is not\n // loaded again.\n document.getElementsByTagName(&quot;head&quot;)[0].appendChild( element );\n Array.add( includedFile, url );\n}\n</code></pre>\n" }, { "answer_id": 21320, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>does anyone have a better way?</p>\n</blockquote>\n\n<p>I think just adding the script to the body would be easier then adding it to the last node on the page. How about this:</p>\n\n<pre><code>function include(url) {\n var s = document.createElement(\"script\");\n s.setAttribute(\"type\", \"text/javascript\");\n s.setAttribute(\"src\", url);\n document.body.appendChild(s);\n}\n</code></pre>\n" }, { "answer_id": 21392, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 2, "selected": false, "text": "<p>The technique we use at work is to request the javascript file using an AJAX request and then eval() the return. If you're using the prototype library, they support this functionality in their Ajax.Request call.</p>\n" }, { "answer_id": 24313, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 5, "selected": false, "text": "<p>I used a <a href=\"http://gist.github.com/4102\" rel=\"noreferrer\">much less complicated version recently</a> with <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a>:</p>\n\n<pre><code>&lt;script src=\"scripts/jquery.js\"&gt;&lt;/script&gt;\n&lt;script&gt;\n var js = [\"scripts/jquery.dimensions.js\", \"scripts/shadedborder.js\", \"scripts/jqmodal.js\", \"scripts/main.js\"];\n var $head = $(\"head\");\n for (var i = 0; i &lt; js.length; i++) {\n $head.append(\"&lt;script src=\\\"\" + js[i] + \"\\\"&gt;&lt;/scr\" + \"ipt&gt;\");\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.</p>\n\n<p><strong>Update:</strong> jQuery-less version:</p>\n\n<pre><code>&lt;script&gt;\n var js = [\"scripts/jquery.dimensions.js\", \"scripts/shadedborder.js\", \"scripts/jqmodal.js\", \"scripts/main.js\"];\n for (var i = 0, l = js.length; i &lt; l; i++) {\n document.getElementsByTagName(\"head\")[0].innerHTML += (\"&lt;script src=\\\"\" + js[i] + \"\\\"&gt;&lt;/scr\" + \"ipt&gt;\");\n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 28249, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 2, "selected": false, "text": "<p>i've used yet another solution i found on the net ... this one is under creativecommons and it <strong>checks if the source was included prior to calling the function</strong> ...</p>\n\n<p>you can find the file here: <a href=\"http://xkr.us/code/javascript/include.js\" rel=\"nofollow noreferrer\">include.js</a></p>\n\n<pre><code>/** include - including .js files from JS - [email protected] - 2005-02-09\n ** Code licensed under Creative Commons Attribution-ShareAlike License \n ** http://creativecommons.org/licenses/by-sa/2.0/\n **/ \nvar hIncludes = null;\nfunction include(sURI)\n{ \n if (document.getElementsByTagName)\n { \n if (!hIncludes)\n {\n hIncludes = {}; \n var cScripts = document.getElementsByTagName(\"script\");\n for (var i=0,len=cScripts.length; i &lt; len; i++)\n if (cScripts[i].src) hIncludes[cScripts[i].src] = true;\n }\n if (!hIncludes[sURI])\n {\n var oNew = document.createElement(\"script\");\n oNew.type = \"text/javascript\";\n oNew.src = sURI;\n hIncludes[sURI]=true;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n }\n } \n} \n</code></pre>\n" }, { "answer_id": 242607, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 7, "selected": true, "text": "<p>You may create a script element dynamically, using <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototypes</a>:</p>\n<pre><code>new Element(&quot;script&quot;, {src: &quot;myBigCodeLibrary.js&quot;, type: &quot;text/javascript&quot;});\n</code></pre>\n<p>The problem here is that we do not know <em>when</em> the external script file is fully loaded.</p>\n<p>We often want our dependant code on the very next line and like to write something like:</p>\n<pre><code>if (iNeedSomeMore) {\n Script.load(&quot;myBigCodeLibrary.js&quot;); // includes code for myFancyMethod();\n myFancyMethod(); // cool, no need for callbacks!\n}\n</code></pre>\n<p>There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a <em>synchronous AJAX request</em> and eval the script on global level.</p>\n<p>If you use Prototype the Script.load method looks like this:</p>\n<pre><code>var Script = {\n _loadedScripts: [],\n include: function(script) {\n // include script only once\n if (this._loadedScripts.include(script)) {\n return false;\n }\n // request file synchronous\n var code = new Ajax.Request(script, {\n asynchronous: false,\n method: &quot;GET&quot;,\n evalJS: false,\n evalJSON: false\n }).transport.responseText;\n // eval code on global level\n if (Prototype.Browser.IE) {\n window.execScript(code);\n } else if (Prototype.Browser.WebKit) {\n $$(&quot;head&quot;).first().insert(Object.extend(\n new Element(&quot;script&quot;, {\n type: &quot;text/javascript&quot;\n }), {\n text: code\n }\n ));\n } else {\n window.eval(code);\n }\n // remember included script\n this._loadedScripts.push(script);\n }\n};\n</code></pre>\n" }, { "answer_id": 684047, "author": "Kariem", "author_id": 12039, "author_profile": "https://Stackoverflow.com/users/12039", "pm_score": 2, "selected": false, "text": "<p>Just found out about a great feature in <a href=\"http://developer.yahoo.com/yui/3/\" rel=\"nofollow noreferrer\">YUI 3</a> (at the time of writing available in preview release). You can easily insert dependencies to YUI libraries and to \"external\" modules (what you are looking for) without too much code: <a href=\"http://developer.yahoo.com/yui/3/examples/yui/yui-loader-ext.html\" rel=\"nofollow noreferrer\">YUI Loader</a>.</p>\n\n<p>It also answers your second question regarding the function being called as soon as the external module is loaded.</p>\n\n<p>Example:</p>\n\n<pre><code>YUI({\n modules: {\n 'simple': {\n fullpath: \"http://example.com/public/js/simple.js\"\n },\n 'complicated': {\n fullpath: \"http://example.com/public/js/complicated.js\"\n requires: ['simple'] // &lt;-- dependency to 'simple' module\n }\n },\n timeout: 10000\n}).use('complicated', function(Y, result) {\n // called as soon as 'complicated' is loaded\n if (!result.success) {\n // loading failed, or timeout\n handleError(result.msg);\n } else {\n // call a function that needs 'complicated'\n doSomethingComplicated(...);\n }\n});\n</code></pre>\n\n<p>Worked perfectly for me and has the advantage of managing dependencies. Refer to the YUI documentation for an <a href=\"http://developer.yahoo.com/yui/3/examples/yui/yui-loader-ext_clean.html\" rel=\"nofollow noreferrer\">example with YUI 2 calendar</a>.</p>\n" }, { "answer_id": 4689568, "author": "JM Design", "author_id": 572322, "author_profile": "https://Stackoverflow.com/users/572322", "pm_score": 2, "selected": false, "text": "<p><strong>jquery resolved this for me with its .append() function</strong>\n- used this to load the complete jquery ui package</p>\n\n<pre><code>/*\n * FILENAME : project.library.js\n * USAGE : loads any javascript library\n */\n var dirPath = \"../js/\";\n var library = [\"functions.js\",\"swfobject.js\",\"jquery.jeditable.mini.js\",\"jquery-ui-1.8.8.custom.min.js\",\"ui/jquery.ui.core.min.js\",\"ui/jquery.ui.widget.min.js\",\"ui/jquery.ui.position.min.js\",\"ui/jquery.ui.button.min.js\",\"ui/jquery.ui.mouse.min.js\",\"ui/jquery.ui.dialog.min.js\",\"ui/jquery.effects.core.min.js\",\"ui/jquery.effects.blind.min.js\",\"ui/jquery.effects.fade.min.js\",\"ui/jquery.effects.slide.min.js\",\"ui/jquery.effects.transfer.min.js\"];\n\n for(var script in library){\n $('head').append('&lt;script type=\"text/javascript\" src=\"' + dirPath + library[script] + '\"&gt;&lt;/script&gt;');\n }\n</code></pre>\n\n<p><strong>To Use</strong> - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"project.library.js\"&gt;&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 9267437, "author": "Muhd", "author_id": 446921, "author_profile": "https://Stackoverflow.com/users/446921", "pm_score": 3, "selected": false, "text": "<p>If you have jQuery loaded already, you should use <a href=\"http://api.jquery.com/jQuery.getScript/\">$.getScript</a>. </p>\n\n<p>This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.</p>\n" }, { "answer_id": 9268711, "author": "1nfiniti", "author_id": 1133102, "author_profile": "https://Stackoverflow.com/users/1133102", "pm_score": 1, "selected": false, "text": "<p>There are scripts that are designed specifically for this purpose.</p>\n\n<p><a href=\"http://yepnopejs.com/\" rel=\"nofollow\">yepnope.js</a> is built into Modernizr, and <a href=\"http://labjs.com/\" rel=\"nofollow\">lab.js</a> is a more optimized (but less user friendly version. </p>\n\n<p>I wouldn't reccomend doing this through a big library like jquery or prototype - because one of the major benefits of a script loader is the ability to load scripts early - you shouldn't have to wait until jquery &amp; all your dom elements load before running a check to see if you want to dynamically load a script.</p>\n" }, { "answer_id": 10013923, "author": "Naveed", "author_id": 671046, "author_profile": "https://Stackoverflow.com/users/671046", "pm_score": 4, "selected": false, "text": "<p>another awesome answer </p>\n\n<pre><code>$.getScript(\"my_lovely_script.js\", function(){\n\n\n alert(\"Script loaded and executed.\");\n // here you can use anything you defined in the loaded script\n\n });\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/950146/671046\">https://stackoverflow.com/a/950146/671046</a></p>\n" }, { "answer_id": 14786759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>There is no import / include / require in javascript, but there are two main ways to achieve what you want:</p>\n<p>1 - You can load it with an AJAX call then use eval.</p>\n<p>This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.</p>\n<p>2 - Add a script element with the script URL in the HTML.</p>\n<p>Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the <code>script</code> element in the <code>head</code> element of the web page, or at the bottom of the <code>body</code>.</p>\n<p>Both of these solutions are discussed and illustrated here.</p>\n<p>Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.</p>\n<p>It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.</p>\n<p>E.G : my_lovely_script.js contains MySuperObject</p>\n<pre><code>var js = document.createElement(&quot;script&quot;);\n\njs.type = &quot;text/javascript&quot;;\njs.src = jsFilePath;\n\ndocument.body.appendChild(js);\n\nvar s = new MySuperObject();\n\nError : MySuperObject is undefined\n</code></pre>\n<p>Then you reload the page hitting F5. And it works! Confusing...</p>\n<p>So what to do about it ?</p>\n<p>Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :</p>\n<pre><code>function loadScript(url, callback)\n{\n // adding the script element to the head as suggested before\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = url;\n\n // then bind the event to the callback function \n // there are several events for cross browser compatibility\n script.onreadystatechange = callback;\n script.onload = callback;\n\n // fire the loading\n head.appendChild(script);\n}\n</code></pre>\n<p>Then you write the code you want to use AFTER the script is loaded in a lambda function :</p>\n<pre><code>var myPrettyCode = function() {\n // here, do what ever you want\n};\n</code></pre>\n<p>Then you run all that :</p>\n<pre><code>loadScript(&quot;my_lovely_script.js&quot;, myPrettyCode);\n</code></pre>\n<p>Ok, I got it. But it's a pain to write all this stuff.</p>\n<p>Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :</p>\n<pre><code>$.getScript(&quot;my_lovely_script.js&quot;, function() {\n alert(&quot;Script loaded and executed.&quot;);\n // here you can use anything you defined in the loaded script\n});\n</code></pre>\n" }, { "answer_id": 15976901, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": 1, "selected": false, "text": "<p>I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: <a href=\"http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/\" rel=\"nofollow\">http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/</a></p>\n\n<pre><code>var _rmod = _rmod || {}; //require module namespace\n_rmod.on_ready_fn_stack = [];\n_rmod.libpath = '';\n_rmod.imported = {};\n_rmod.loading = {\n scripts: {},\n length: 0\n};\n\n_rmod.findScriptPath = function(script_name) {\n var script_elems = document.getElementsByTagName('script');\n for (var i = 0; i &lt; script_elems.length; i++) {\n if (script_elems[i].src.endsWith(script_name)) {\n var href = window.location.href;\n href = href.substring(0, href.lastIndexOf('/'));\n var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);\n return url.substring(href.length+1, url.length);\n }\n }\n return '';\n};\n\n_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library\n\n\n_rmod.injectScript = function(script_name, uri, callback, prepare) {\n\n if(!prepare)\n prepare(script_name, uri);\n\n var script_elem = document.createElement('script');\n script_elem.type = 'text/javascript';\n script_elem.title = script_name;\n script_elem.src = uri;\n script_elem.async = true;\n script_elem.defer = false;\n\n if(!callback)\n script_elem.onload = function() {\n callback(script_name, uri);\n };\n\n document.getElementsByTagName('head')[0].appendChild(script_elem);\n};\n\n_rmod.requirePrepare = function(script_name, uri) {\n _rmod.loading.scripts[script_name] = uri;\n _rmod.loading.length++;\n};\n\n_rmod.requireCallback = function(script_name, uri) {\n _rmod.loading.length--;\n delete _rmod.loading.scripts[script_name];\n _rmod.imported[script_name] = uri;\n\n if(_rmod.loading.length == 0)\n _rmod.onReady();\n};\n\n_rmod.onReady = function() {\n if (!_rmod.LOADED) {\n for (var i = 0; i &lt; _rmod.on_ready_fn_stack.length; i++){\n _rmod.on_ready_fn_stack[i]();\n });\n _rmod.LOADED = true;\n }\n};\n\n//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.\nvar require = function(script_name) {\n var np = script_name.split('.');\n if (np[np.length-1] === '*') {\n np.pop();\n np.push('_all');\n }\n\n script_name = np.join('.');\n var uri = _rmod.libpath + np.join('/')+'.js';\n if (!_rmod.loading.scripts.hasOwnProperty(script_name) \n &amp;&amp; !_rmod.imported.hasOwnProperty(script_name)) {\n _rmod.injectScript(script_name, uri, \n _rmod.requireCallback, \n _rmod.requirePrepare);\n }\n};\n\nvar ready = function(fn) {\n _rmod.on_ready_fn_stack.push(fn);\n};\n\n// ----- USAGE -----\n\nrequire('ivar.util.array');\nrequire('ivar.util.string');\nrequire('ivar.net.*');\n\nready(function(){\n //do something when required scripts are loaded\n});\n</code></pre>\n" }, { "answer_id": 16955574, "author": "Sielu", "author_id": 1250626, "author_profile": "https://Stackoverflow.com/users/1250626", "pm_score": 2, "selected": false, "text": "<p>If you want a <strong>SYNC</strong> script loading, you need to add script text directly to HTML HEAD element. Adding it as will trigger an <strong>ASYNC</strong> load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):</p>\n<pre><code>/*sample requires an additional method for array prototype:*/\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n var i = this.length;\n while (i--) { if (this[i] === obj) return true; }\n return false;\n};\n};\n\n/*define object that will wrap our logic*/\nvar ScriptLoader = {\nLoadedFiles: [],\n\nLoadFile: function (url) {\n var self = this;\n if (this.LoadedFiles.contains(url)) return;\n\n var xhr = new XMLHttpRequest();\n xhr.onload = function () {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n self.LoadedFiles.push(url);\n self.AddScript(xhr.responseText);\n } else {\n if (console) console.error(xhr.statusText);\n }\n }\n };\n xhr.open(&quot;GET&quot;, url, false);/*last parameter defines if call is async or not*/\n xhr.send(null);\n},\n\nAddScript: function (code) {\n var oNew = document.createElement(&quot;script&quot;);\n oNew.type = &quot;text/javascript&quot;;\n oNew.textContent = code;\n document.getElementsByTagName(&quot;head&quot;)[0].appendChild(oNew);\n}\n};\n\n/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/\n\nScriptLoader.LoadFile(&quot;Scripts/jquery-2.0.1.min.js&quot;);\nScriptLoader.LoadFile(&quot;Scripts/jquery-2.0.1.min.js&quot;);\n/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id &quot;tb1&quot;*/\n$(function () { alert($('#tb1').val()); });\n</code></pre>\n" }, { "answer_id": 28389499, "author": "tfont", "author_id": 1804013, "author_profile": "https://Stackoverflow.com/users/1804013", "pm_score": 2, "selected": false, "text": "<p>Keep it nice, short, simple, and maintainable! :]</p>\n\n<pre><code>// 3rd party plugins / script (don't forget the full path is necessary)\nvar FULL_PATH = '', s =\n[\n FULL_PATH + 'plugins/script.js' // Script example\n FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library \n FULL_PATH + 'plugins/crypto-js/hmac-sha1.js', // CryptoJS\n FULL_PATH + 'plugins/crypto-js/enc-base64-min.js' // CryptoJS\n];\n\nfunction load(url)\n{\n var ajax = new XMLHttpRequest();\n ajax.open('GET', url, false);\n ajax.onreadystatechange = function ()\n {\n var script = ajax.response || ajax.responseText;\n if (ajax.readyState === 4)\n {\n switch(ajax.status)\n {\n case 200:\n eval.apply( window, [script] );\n console.log(\"library loaded: \", url);\n break;\n default:\n console.log(\"ERROR: library not loaded: \", url);\n }\n }\n };\n ajax.send(null);\n}\n\n // initialize a single load \nload('plugins/script.js');\n\n// initialize a full load of scripts\nif (s.length &gt; 0)\n{\n for (i = 0; i &lt; s.length; i++)\n {\n load(s[i]);\n }\n}\n</code></pre>\n\n<p>This code is simply a short functional example that <em>could</em> require additional feature functionality for full support on any (or given) platform.</p>\n" }, { "answer_id": 35793206, "author": "adrianTNT", "author_id": 928532, "author_profile": "https://Stackoverflow.com/users/928532", "pm_score": 1, "selected": false, "text": "<p>I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:</p>\n\n<pre><code>document.write(\"&lt;script src='https://www.google.com/recaptcha/api.js'&gt;&lt;/script&gt;\");\n</code></pre>\n" }, { "answer_id": 42667747, "author": "Jacob", "author_id": 665783, "author_profile": "https://Stackoverflow.com/users/665783", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://www.sitepoint.com/dynamically-load-jquery-library-javascript/\" rel=\"nofollow noreferrer\">Here</a> is a simple one with callback and IE support:</p>\n\n<pre><code>function loadScript(url, callback) {\n\n var script = document.createElement(\"script\")\n script.type = \"text/javascript\";\n\n if (script.readyState) { //IE\n script.onreadystatechange = function () {\n if (script.readyState == \"loaded\" || script.readyState == \"complete\") {\n script.onreadystatechange = null;\n callback();\n }\n };\n } else { //Others\n script.onload = function () {\n callback();\n };\n }\n\n script.src = url;\n document.getElementsByTagName(\"head\")[0].appendChild(script);\n}\n\nloadScript(\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\", function () {\n\n //jQuery loaded\n console.log('jquery loaded');\n\n});\n</code></pre>\n" }, { "answer_id": 45488894, "author": "asmmahmud", "author_id": 1576255, "author_profile": "https://Stackoverflow.com/users/1576255", "pm_score": 2, "selected": false, "text": "<p>I know my answer is bit late for this question, but, here is a great article in <strong>www.html5rocks.com</strong> - <a href=\"https://www.html5rocks.com/en/tutorials/speed/script-loading/#toc-aggressive-optimisation\" rel=\"nofollow noreferrer\">Deep dive into the murky waters of script loading</a> .</p>\n\n<p>In that article it is concluded that in regards of browser support, the best way to dynamically load JavaScript file without blocking content rendering is the following way: </p>\n\n<p>Considering you've four scripts named <code>script1.js, script2.js, script3.js, script4.js</code> then you can do it with <strong>applying async = false</strong>: </p>\n\n<pre><code>[\n 'script1.js',\n 'script2.js',\n 'script3.js',\n 'script4.js'\n].forEach(function(src) {\n var script = document.createElement('script');\n script.src = src;\n script.async = false;\n document.head.appendChild(script);\n});\n</code></pre>\n\n<p>Now, <strong>Spec says</strong>: Download together, execute in order as soon as all download.</p>\n\n<p><strong>Firefox &lt; 3.6, Opera says:</strong> I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.</p>\n\n<p><strong>Safari 5.0 says:</strong> I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.</p>\n\n<p><strong>IE &lt; 10 says:</strong> No idea about “async”, but there is a workaround using “onreadystatechange”.</p>\n\n<p><strong>Everything else says:</strong> I’m your friend, we’re going to do this by the book.</p>\n\n<p><strong>Now, the full code with IE &lt; 10 workaround:</strong> </p>\n\n<pre><code>var scripts = [\n 'script1.js',\n 'script2.js',\n 'script3.js',\n 'script4.js'\n];\nvar src;\nvar script;\nvar pendingScripts = [];\nvar firstScript = document.scripts[0];\n\n// Watch scripts load in IE\nfunction stateChange() {\n // Execute as many scripts in order as we can\n var pendingScript;\n while (pendingScripts[0] &amp;&amp; pendingScripts[0].readyState == 'loaded') {\n pendingScript = pendingScripts.shift();\n // avoid future loading events from this script (eg, if src changes)\n pendingScript.onreadystatechange = null;\n // can't just appendChild, old IE bug if element isn't closed\n firstScript.parentNode.insertBefore(pendingScript, firstScript);\n }\n}\n\n// loop through our script urls\nwhile (src = scripts.shift()) {\n if ('async' in firstScript) { // modern browsers\n script = document.createElement('script');\n script.async = false;\n script.src = src;\n document.head.appendChild(script);\n }\n else if (firstScript.readyState) { // IE&lt;10\n // create a script and add it to our todo pile\n script = document.createElement('script');\n pendingScripts.push(script);\n // listen for state changes\n script.onreadystatechange = stateChange;\n // must set src AFTER adding onreadystatechange listener\n // else we’ll miss the loaded event for cached scripts\n script.src = src;\n }\n else { // fall back to defer\n document.write('&lt;script src=\"' + src + '\" defer&gt;&lt;/'+'script&gt;');\n }\n}\n</code></pre>\n\n<p><strong>A few tricks and minification later, it’s 362 bytes</strong> </p>\n\n<pre><code>!function(e,t,r){function n(){for(;d[0]&amp;&amp;\"loaded\"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o=\"onreadystatechange\",f=\"readyState\";s=r.shift();)a=e.createElement(t),\"async\"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write(\"&lt;\"+t+' src=\"'+s+'\" defer&gt;&lt;/'+t+\"&gt;\"),a.src=s}(document,\"script\",[\n \"//other-domain.com/1.js\",\n \"2.js\"\n])\n</code></pre>\n" }, { "answer_id": 49889707, "author": "James Arnold", "author_id": 2558016, "author_profile": "https://Stackoverflow.com/users/2558016", "pm_score": 2, "selected": false, "text": "<p>Something like this...</p>\n\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n $('body').append('&lt;script src=\"https://maps.googleapis.com/maps/api/js?key=KEY&amp;libraries=places&amp;callback=getCurrentPickupLocation\" async defer&gt;&lt;\\/script&gt;');\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 50051689, "author": "João Pimentel Ferreira", "author_id": 1243247, "author_profile": "https://Stackoverflow.com/users/1243247", "pm_score": 1, "selected": false, "text": "<p>Here a simple example for a function to load JS files. Relevant points:</p>\n\n<ul>\n<li>you don't need jQuery, so you may use this initially to load also the jQuery.js file</li>\n<li>it is async with callback</li>\n<li>it ensures it loads only once, as it keeps an enclosure with the record of loaded urls, thus avoiding usage of network</li>\n<li>contrary to jQuery <code>$.ajax</code> or <code>$.getScript</code> you can use nonces, solving thus issues with CSP <code>unsafe-inline</code>. Just use the property <code>script.nonce</code></li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>var getScriptOnce = function() {\n\n var scriptArray = []; //array of urls (closure)\n\n //function to defer loading of script\n return function (url, callback){\n //the array doesn't have such url\n if (scriptArray.indexOf(url) === -1){\n\n var script=document.createElement('script');\n script.src=url;\n var head=document.getElementsByTagName('head')[0],\n done=false;\n\n script.onload=script.onreadystatechange = function(){\n if ( !done &amp;&amp; (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {\n done=true;\n if (typeof callback === 'function') {\n callback();\n }\n script.onload = script.onreadystatechange = null;\n head.removeChild(script);\n\n scriptArray.push(url);\n }\n };\n\n head.appendChild(script);\n }\n };\n}();\n</code></pre>\n\n\n\n<p>Now you use it simply by</p>\n\n<pre><code>getScriptOnce(\"url_of_your_JS_file.js\");\n</code></pre>\n" }, { "answer_id": 51378436, "author": "Alister", "author_id": 1432509, "author_profile": "https://Stackoverflow.com/users/1432509", "pm_score": 2, "selected": false, "text": "<p>There's a new proposed ECMA standard called <a href=\"https://developers.google.com/web/updates/2017/11/dynamic-import\" rel=\"nofollow noreferrer\">dynamic import</a>, recently incorporated into Chrome and Safari. </p>\n\n<pre><code>const moduleSpecifier = './dir/someModule.js';\n\nimport(moduleSpecifier)\n .then(someModule =&gt; someModule.foo()); // executes foo method in someModule\n</code></pre>\n" }, { "answer_id": 52365356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>An absurd one-liner, for those who think that loading a js library shouldn't take more than one line of code :P</p>\n\n<pre><code>await new Promise((resolve, reject) =&gt; {let js = document.createElement(\"script\"); js.src=\"mylibrary.js\"; js.onload=resolve; js.onerror=reject; document.body.appendChild(js)});\n</code></pre>\n\n<p>Obviously if the script you want to import is a module, you can use the <a href=\"https://developers.google.com/web/updates/2017/11/dynamic-import\" rel=\"nofollow noreferrer\"><code>import(...)</code></a> function.</p>\n" }, { "answer_id": 57367916, "author": "NVRM", "author_id": 2494754, "author_profile": "https://Stackoverflow.com/users/2494754", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports\" rel=\"nofollow noreferrer\">Dynamic <strong>module</strong> import landed in Firefox 67+</a>.</p>\n<pre><code>(async () =&gt; {\n await import('./synth/BubbleSynth.js')\n})()\n</code></pre>\n<p>With error handling:</p>\n<pre><code>(async () =&gt; {\n await import('./synth/BubbleSynth.js').catch((error) =&gt; console.log('Loading failed' + error))\n})()\n</code></pre>\n<hr />\n<p>It also works for any kind of non-modules libraries, on this case the lib is available on the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/self\" rel=\"nofollow noreferrer\"><code>window.self</code></a> object, the old way, but only on demand, which is nice.</p>\n<p>Example using <a href=\"https://github.com/mourner/suncalc\" rel=\"nofollow noreferrer\">suncalc.js</a>, the server must have <strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\" rel=\"nofollow noreferrer\">CORS enabled</a></strong> to works this way!</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>(async () =&gt; {\n await import('https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js')\n .then( () =&gt; {\n let times = SunCalc.getTimes(new Date(), 51.5,-0.1);\n console.log(\"Golden Hour today in London: \" + times.goldenHour.getHours() + ':' + times.goldenHour.getMinutes() + \". Take your pics!\")\n })\n})()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"https://caniuse.com/#feat=es6-module-dynamic-import\" rel=\"nofollow noreferrer\">https://caniuse.com/#feat=es6-module-dynamic-import</a></p>\n" }, { "answer_id": 59012155, "author": "VG P", "author_id": 3936513, "author_profile": "https://Stackoverflow.com/users/3936513", "pm_score": 0, "selected": false, "text": "<p>I have tweaked some of the above post with working example.\nHere we can give css and js in same array also.</p>\n\n<pre><code>$(document).ready(function(){\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n var i = this.length;\n while (i--) { if (this[i] === obj) return true; }\n return false;\n};\n};\n\n/* define object that will wrap our logic */\nvar jsScriptCssLoader = {\n\njsExpr : new RegExp( \"js$\", \"i\" ),\ncssExpr : new RegExp( \"css$\", \"i\" ),\nloadedFiles: [],\n\nloadFile: function (cssJsFileArray) {\n var self = this;\n // remove duplicates with in array\n cssJsFileArray.filter((item,index)=&gt;cssJsFileArray.indexOf(item)==index)\n var loadedFileArray = this.loadedFiles;\n $.each(cssJsFileArray, function( index, url ) {\n // if multiple arrays are loaded the check the uniqueness\n if (loadedFileArray.contains(url)) return;\n if( self.jsExpr.test( url ) ){\n $.get(url, function(data) {\n self.addScript(data);\n });\n\n }else if( self.cssExpr.test( url ) ){\n $.get(url, function(data) {\n self.addCss(data);\n });\n }\n\n self.loadedFiles.push(url);\n });\n\n // don't load twice accross different arrays\n\n},\naddScript: function (code) {\n var oNew = document.createElement(\"script\");\n oNew.type = \"text/javascript\";\n oNew.textContent = code;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n},\naddCss: function (code) {\n var oNew = document.createElement(\"style\");\n oNew.textContent = code;\n document.getElementsByTagName(\"head\")[0].appendChild(oNew);\n}\n\n};\n\n\n//jsScriptCssLoader.loadFile([\"css/1.css\",\"css/2.css\",\"css/3.css\"]);\njsScriptCssLoader.loadFile([\"js/common/1.js\",\"js/2.js\",\"js/common/file/fileReader.js\"]);\n});\n</code></pre>\n" }, { "answer_id": 59612206, "author": "radulle", "author_id": 3008018, "author_profile": "https://Stackoverflow.com/users/3008018", "pm_score": 2, "selected": false, "text": "<p>With Promises you can simplify it like this.\nLoader function:</p>\n\n<pre><code> const loadCDN = src =&gt;\n new Promise((resolve, reject) =&gt; {\n if (document.querySelector(`head &gt; script[src=\"${src}\"]`) !== null) return resolve()\n const script = document.createElement(\"script\")\n script.src = src\n script.async = true\n document.head.appendChild(script)\n script.onload = resolve\n script.onerror = reject\n })\n</code></pre>\n\n<p>Usage (async/await):</p>\n\n<pre><code>await loadCDN(\"https://.../script.js\")\n</code></pre>\n\n<p>Usage (Promise):</p>\n\n<pre><code>loadCDN(\"https://.../script.js\").then(res =&gt; {}).catch(err =&gt; {})\n</code></pre>\n\n<p>NOTE: there was one similar solution but it doesn't check if the script is already loaded and loads the script each time. This one checks src property.</p>\n" }, { "answer_id": 60248096, "author": "Ludmil Tinkov", "author_id": 519553, "author_profile": "https://Stackoverflow.com/users/519553", "pm_score": 1, "selected": false, "text": "<p>For those of you, who love one-liners:</p>\n\n<pre><code>import('./myscript.js');\n</code></pre>\n\n<p>Chances are you might get an error, like:</p>\n\n<blockquote>\n <p>Access to script at '<a href=\"http://..../myscript.js\" rel=\"nofollow noreferrer\">http://..../myscript.js</a>' from origin\n '<a href=\"http://127.0.0.1\" rel=\"nofollow noreferrer\">http://127.0.0.1</a>' has been blocked by CORS policy: No\n 'Access-Control-Allow-Origin' header is present on the requested\n resource.</p>\n</blockquote>\n\n<p>In which case, you can fallback to:</p>\n\n<pre><code>fetch('myscript.js').then(r =&gt; r.text()).then(t =&gt; new Function(t)());\n</code></pre>\n" }, { "answer_id": 67646541, "author": "Enrico", "author_id": 7116948, "author_profile": "https://Stackoverflow.com/users/7116948", "pm_score": 1, "selected": false, "text": "<p>In as much as I love how handy the JQuery approach is, the JavaScript approach isn't that complicated but just require little tweaking to what you already use...\nHere is how I load JS dynamically(Only when needed), and wait for them to load before executing the script that depends on them.</p>\n<p><strong>JavaScript Approach</strong></p>\n<pre><code>//Create a script element that will load\nlet dynamicScript = document.createElement('script');\n\n//Set source to the script we need to load\ndynamicScript.src = 'linkToNeededJsFile.js';\n\n//Set onload to callback function that depends on this script or do inline as shown below\ndynamicScript.onload = () =&gt; {\n\n //Code that depends on the loaded script should be here\n\n};\n\n//append the created script element to body element\ndocument.body.append(dynamicScript);\n</code></pre>\n<p>There are other ways approach one could accomplish this with JS but, I prefer this as it's require the basic JS knowledge every dev can relate.</p>\n<p>Not part of the answer but here is the JQuery version I prefer with projects that already include JQuery:</p>\n<pre><code>$.getScript('linkToNeededJsFile.js', () =&gt; {\n\n //Code that depends on the loaded script should be here\n\n});\n</code></pre>\n<p>More on the JQuery option <a href=\"https://api.jquery.com/jQuery.getScript/\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 72079575, "author": "vatavale", "author_id": 1056384, "author_profile": "https://Stackoverflow.com/users/1056384", "pm_score": 1, "selected": false, "text": "<p>This function uses memorization. And could be called many times with no conflicts of loading and running the same script twice. Also it's not resolving sooner than the script is actually loaded (like in <a href=\"https://stackoverflow.com/a/59612206/1056384\">@radulle</a> answer).</p>\n<pre><code>const loadScript = function () {\n let cache = {};\n return function (src) {\n return cache[src] || (cache[src] = new Promise((resolve, reject) =&gt; {\n let s = document.createElement('script');\n s.defer = true;\n s.src = src;\n s.onload = resolve;\n s.onerror = reject;\n document.head.append(s);\n }));\n }\n}();\n</code></pre>\n<p>Please notice the parentheses () after the function expression.</p>\n<p>Parallel loading of scripts:</p>\n<pre><code>Promise.all([\n loadScript('/script1.js'),\n loadScript('/script2.js'),\n // ...\n]).then(() =&gt; {\n // do something\n})\n</code></pre>\n<p>You can use the same method for <a href=\"https://stackoverflow.com/a/72082566/1056384\">dynamic loading stylesheets</a>.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand. The client that uses the component isn't required to load all the library script files (and manually insert `<script>` tags into their web page) that implement this component - just the 'main' component script file. **How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?** Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts? An addition to this question: **is there a way to handle the event after a dynamically included JavaScript file is loaded?** Prototype has `document.observe` for document-wide events. Example: ``` document.observe("dom:loaded", function() { // initially hide all containers for tab content $$('div.tabcontent').invoke('hide'); }); ``` **What are the available events for a script element?**
You may create a script element dynamically, using [Prototypes](http://www.prototypejs.org/): ``` new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"}); ``` The problem here is that we do not know *when* the external script file is fully loaded. We often want our dependant code on the very next line and like to write something like: ``` if (iNeedSomeMore) { Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod(); myFancyMethod(); // cool, no need for callbacks! } ``` There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a *synchronous AJAX request* and eval the script on global level. If you use Prototype the Script.load method looks like this: ``` var Script = { _loadedScripts: [], include: function(script) { // include script only once if (this._loadedScripts.include(script)) { return false; } // request file synchronous var code = new Ajax.Request(script, { asynchronous: false, method: "GET", evalJS: false, evalJSON: false }).transport.responseText; // eval code on global level if (Prototype.Browser.IE) { window.execScript(code); } else if (Prototype.Browser.WebKit) { $$("head").first().insert(Object.extend( new Element("script", { type: "text/javascript" }), { text: code } )); } else { window.eval(code); } // remember included script this._loadedScripts.push(script); } }; ```
21,303
<p>VC++ makes functions which are implemented within the class declaration inline functions.</p> <p>If I declare a class <code>Foo</code> as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?</p> <pre><code>class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } </code></pre>
[ { "answer_id": 21322, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the &quot;inline&quot; keyword.</p>\n<p>In both cases it's a hint to the compiler. An &quot;inline&quot; function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.</p>\n" }, { "answer_id": 21324, "author": "Mickey", "author_id": 1494, "author_profile": "https://Stackoverflow.com/users/1494", "pm_score": 3, "selected": false, "text": "<p>Putting the function definition in the class body is equivalent to marking a function with the inline keyword. That means the function may or may not be inlined by the compiler. So I guess the best answer would be &quot;maybe&quot;?</p>\n" }, { "answer_id": 21326, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 5, "selected": false, "text": "<p>The short answer is yes. Any function can be declared inline, and putting the function body in the class definition is one way of doing that. You could also have done:</p>\n<pre><code>class Foo \n{\n int* p;\npublic:\n Foo();\n ~Foo();\n};\n\ninline Foo::Foo() \n{ \n p = new char[0x00100000]; \n}\n\ninline Foo::~Foo()\n{ \n delete [] p; \n}\n</code></pre>\n<p>However, it's up to the compiler if it actually does inline the function. VC++ pretty much ignores your requests for inlining. It will only inline a function if it thinks it's a good idea. Recent versions of the compiler will also inline things that are in separate .obj files and not declared inline (e.g. from code in different .cpp files) if you use <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301698.aspx\" rel=\"nofollow noreferrer\">link time code generation</a>.</p>\n<p>You could use the <a href=\"http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx\" rel=\"nofollow noreferrer\">__forceinline</a> keyword to tell the compiler that you really really mean it when you say &quot;inline this function&quot;, but it's usally not worth it. In many cases, the compiler really does know best.</p>\n" }, { "answer_id": 21327, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<p>To the same extent that we can make any other function inline, yes.</p>\n" }, { "answer_id": 222406, "author": "Rodney Schuler", "author_id": 6188, "author_profile": "https://Stackoverflow.com/users/6188", "pm_score": 2, "selected": false, "text": "<p>To inline or not is mostly decided by your compiler. Inline in the code only hints to the compiler.<br>\nOne rule that you can count on is that virtual functions will never be inlined. If your base class has virtual constructor/destructor yours will probably never be inlined.</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
VC++ makes functions which are implemented within the class declaration inline functions. If I declare a class `Foo` as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions? ``` class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } ```
Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword. In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.
21,448
<p>I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.</p> <p>So far I have this: </p> <pre><code>DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties= ""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E </code></pre> <p>This gives me the error: <strong><code>Option "Properties=Excel 8.0;HDR=Yes" is not valid.</code></strong></p> <p>I've tried a few variations with the Quotation marks but have not been able to get it right yet.</p> <p>Does anyone know how to fix this?</p> <p><strong><code>UPDATE:</code></strong></p> <p>Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.</p>
[ { "answer_id": 22093, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 2, "selected": false, "text": "<p>Unless it's a business requirement, I suggest you move the connection string from the command line to the package and use a package configuration to define the path to the Excel file (in order not to hard-code it). This will make it easier to maintain.</p>\n\n<ol>\n<li>Define a variable <em>@ExcelPath</em>.</li>\n<li>Use connection's <em>Expression</em> property to construct a connection string - an example: <code>\"Data Source=\" + @[User::FilePath] + \";Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBASE IV;\"</code></li>\n<li>Assign a value to <em>@ExcelPath</em> in the package configuration.</li>\n</ol>\n\n<hr>\n\n<p>Take a closer look at the connection string above. It's taken from a working package. I'm not sure about this, but maybe you don't need any quotes at all (the ones above are only there because the expression editor requires them).</p>\n\n<hr>\n\n<p><a href=\"http://chopeen.blogspot.com/2007/04/importing-data-from-dbf-files-using.html\" rel=\"nofollow noreferrer\">I have also had some problems with SSIS on 64-bit SQL Server 2005.</a> That post from my blog does not answer your question, but it is somewhat related so I am posting the link.</p>\n" }, { "answer_id": 110617, "author": "Michael Entin", "author_id": 19880, "author_profile": "https://Stackoverflow.com/users/19880", "pm_score": 2, "selected": false, "text": "<p>There is no 64-bit Jet OLEDB provider, so you can't access Excel files from 64-bit SSIS.</p>\n\n<p>However, you can use 32-bit SSIS even on 64-bit server. It is already installed when you installed 64-bit version, and all you need to do is run the 32-bit DTEXEC.EXE - the one installed <code>Program Files (x86)\\Microsoft Sql Server\\90\\Dts\\Binn</code> (replace <strong>90</strong> with <strong>100</strong> if you are using SSIS 2008).</p>\n" }, { "answer_id": 378782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You can use an Excel connection in 64bit environment.\nGo to the package configuration properties.</p>\n\n<p>Debugging -> Debugging Options -> Run64BtRuntime -> change to False\nIn addition if you use SQL Agent go to the job step properties and then check the 32 bit runtime.</p>\n\n<p>note: this only applies to debugging within Visual Studio...</p>\n" }, { "answer_id": 774652, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I kinda did what Dr Zim did but I copied the DTExec file <code>C:\\Program Files (x86)\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec.exe</code> to <code>C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\</code> folder but named the 32 bit one to DTExec32.exe</p>\n\n<p>then I was able to run my SSIS script through a stored proc:</p>\n\n<pre><code>set @params = '/set \\package.variables[ImportFilename].Value;\"\\\"' + @FileName + '\\\"\" '\nset @cmd = 'dtexec32 /SQ \"' + @packagename + ' ' + @params + '\"'\n--DECLARE @returncode int\nexec master..xp_cmdshell @cmd\n--exec @returncode = master..xp_cmdshell @cmd\n--select @returncode\n</code></pre>\n" }, { "answer_id": 6805514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This step-by-step example is for others who might stumble upon this question. This example uses <em>SSIS 2005</em> and uses <em>SQL Server 2005 64-bit edition server</em> to run the job.</p>\n\n<p>The answer here concentrates only on fixing the error message mentioned in the question. The example will demonstrate the steps to recreate the issue and also the cause of the issue followed by how to fix it.</p>\n\n<p><strong><code>NOTE:</code></strong> I would recommend using the option of storing the package configuration values in database or using indirect XML configuration with the help of Environment Variables. Also, the steps to create Excel file would be done using a template which would then archived by moving to a different folder. These steps are not discussed in this post. As mentioned earlier, the purpose of this post is to address the error.</p>\n\n<p>Let’s proceed with the example. I have also blogged about this answer, which can be found in <a href=\"http://learnbycoding.com/2011/07/accessing-excel-data-source-from-an-ssis-package-that-is-deployed-on-a-64-bit-server/\" rel=\"nofollow noreferrer\">this link</a>. It is the same answer.</p>\n\n<p>Create an SSIS package (<a href=\"http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/\" rel=\"nofollow noreferrer\">Steps to create an SSIS package</a>). This example uses BIDS 2005. I have named the package in the format YYYYMMDD_hhmm in the beginning followed by SO stands for Stack Overflow, followed by the SO question id, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have a Data Sources named Adventure Works. I will be using Adventure Works data source, which points to AdventureWorks database downloaded from <a href=\"http://msftdbprodsamples.codeplex.com/\" rel=\"nofollow noreferrer\">this link</a>. The example uses SQL Server 2008 R2 database. Refer screenshot <strong>#1</strong>.</p>\n\n<p>In the AdventureWorks database, create a stored procedure named <em>dbo.GetCurrency</em> using the below given script.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[GetCurrency]\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT \n TOP 10 CurrencyCode\n , Name\n , ModifiedDate \n FROM Sales.Currency\n ORDER BY CurrencyCode\nEND\nGO\n</code></pre>\n\n<p>On the package’s Connection Manager section, right-click and select <em>New Connection From Data Source</em>. On the <em>Select Data Source</em> dialog, select <em>Adventure Works</em> and click OK. You should now see the Adventure Works data source under the <em>Connection Managers</em> section.</p>\n\n<p>On the package’s Connection Managers section, right-click again but this time select <em>New Connection…</em>. This is to create the Excel connection. On the Add SSIS Connection Manager, select <em>EXCEL</em>. On the Excel Connection Manager, enter the path <em>C:\\Temp\\Template.xls</em>. When we deploy it to the server, we will change this path. I have selected Excel version <em>Microsoft Excel 97-2005</em> and chose to leave the checkbox <em>First row has column names</em> checked so that the create the Excel file is created column headers. Click <em>OK</em>. Rename the Excel connection to <em>Excel</em>, just to keep it simple. Refer screenshots <strong>#2</strong> - <strong>#7</strong>.</p>\n\n<p>On the package, create the following variable. Refer screenshot <strong>#8</strong>.</p>\n\n<ul>\n<li><em>SQLGetData</em>: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value <em>EXEC dbo.GetCurrency</em></li>\n</ul>\n\n<p>Screenshot <strong>#9</strong> shows the output of the stored procedure execution statement <em>EXEC dbo.GetCurrency</em></p>\n\n<p>On the package’s Control Flow tab, place a <code>Data Flow task</code> and name it as Export to Excel. Refer screenshot <strong>#10</strong>.</p>\n\n<p>Double-click on the Data Flow Task to switch to the Data Flow tab.</p>\n\n<p>On the Data Flow tab, place an <code>OLE DB Source</code> to connect to the SQL Server data to fetch the data from the stored procedure and name it as SQL. Double-click on the OLE DB Source to bring up the OLE DB Source Editor. On the Connection Manager section, select <em>Adventure Works</em> from the OLE DB connection manager, select SQL command from variable from Data access mode and select the variable <em>User::SQLGetData</em> from the Variable name drop down. On the Columns section, make sure the column names are mapped correctly. Click OK to close the OLE DB Source Editor. Refer screenshots <strong>#11</strong> and <strong>#12</strong>.</p>\n\n<p>On the Data Flow tab, place an <code>Excel Destination</code> to insert the data into the Excel file and name it as Excel. Double-click on the Excel Destination to open the Excel Destination Editor. On the Connection Manager section, select Excel from the OLE DB connection manager and select Table or view from Data access mode. At this point, we don’t have an Excel because while creating the Excel connection manager, we simply specified the path but never created the file. Hence, there won’t be any values in the drop down Name of the Excel sheet. So, click the <em>New…</em> button (the second New one) to create a new Excel sheet. On the Create Table window, BIDS automatically provide a create sheet based on the incoming data source. You can change the values according to your preferences. I will simply click OK by retaining the default value. The name of the sheet will be populated in the drop down Name of the Excel sheet. The name of the sheet is taken from the task name, here in this case the Excel Destination, which we have named it as Excel. On the Mappings section, make sure the column names are mapped correctly. Click OK to close the Excel Destination Editor. Refer screenshots <strong>#13</strong> - <strong>#16</strong>.</p>\n\n<p>Once the data flow task is configured, it should look like as shown in screenshot <strong>#17</strong>.</p>\n\n<p>Execute the package by pressing F5. Screenshots <strong>#18</strong> - <strong>#21</strong> show the successful execution of the package in both Control Flow and Data Flow Task. Also, the file is generated in the path <em>C:\\Temp\\Template.xls</em> provided in the Excel connection and the data shown in the stored procedure execution output matches with the data written to the file.</p>\n\n<p>The package developed on my local machine in the folder path <em>C:\\Learn\\Learn.VS2005\\Learn.SSIS</em>. Now, we need to deploy the files on to the Server that hosts the 64-bit version of the SQL Server to schedule a job. So, the folder on the server would be <em>D:\\SSIS\\Practice</em>. Copy the package file (<strong>.dtsx</strong>) from the local machine and paste it in the server folder. Also, in order for the package to run correctly, we need to have the Excel spreadsheet present on the server. Otherwise, the validation will fail. Usually, I create a Template folder that will contain the empty Excel spreadsheet file that matches the output. Later, during run time I will change the Excel output path to a different location using package configuration. For this example, I am going to keep it simple. So, let’s copy the Excel file generated in the local machine in the path <em>C:\\Temp\\Template.xls</em> to the server location <em>D:\\SSIS\\Practice</em>. I want the SQL job to generate the file in the name Currencies.xls. So, rename the file Template.xls to <em>Currencies.xls</em>. Refer screenshot <strong>#22</strong>.</p>\n\n<p>To show that I am indeed going to run the job on the server in a 64-bit edition of SQL Server, I executed the command SELECT @@version on the SQL Server and screenshot <strong>#23</strong> shows the results.</p>\n\n<p>We will use <em>Execute Package Utility</em> (dtexec.exe) to generate the command line parameters. Log into the server which will run the SSIS package in an SQL job. Double-click on the package file, this will bring the Execute Package Utility. On the General section, select File system from Package source. Click on the Ellipsis and browse to the package path. On the Connection Managers section, select Excel and change the path inside the Excel file from C:\\Temp\\Template.xls to D:\\SSIS\\Practice\\Currencies.xls. The changes made in the Utility will generate a command line accordingly on the Command Line section. On the Command Line section, copy the Command line that contains all the necessary parameters. We are not going to execute the package from here. Click <em>Close</em>. Refer screenshots <strong>#24</strong> - <strong>#26</strong>.</p>\n\n<p>Next, we need to set up a job to run the SSIS package. We cannot choose SQL Server Integration Services Package type because that will run under 64-bit and won’t find the Excel connection provider. So, we have to run it as <code>Operating System (CmdExec)</code> job type. Go to SQL Server Management Studio and connect to the Database Engine. Expand SQL Server Agent and right-click on Jobs node. Select New Job…. On the General section of the Job Properties window, provide the job name as 01_SSIS_Export_To_Excel, Owner will be the user creating the job. I have a Category named SSIS, so I will select that but the default category is <em>[Uncategorized (Local)]</em> and provide a brief description. On the Steps section, click <em>New…</em> button. This will bring Job Step properties. On the General section of the Job Step properties, provide Step name as Export to Excel, Select type <code>Operating system (CmdExec)</code>, leave the default Run as account as SQL Server Agent Service Account and provide the following Command. Click OK. On the New Job window, Click OK. Refer screenshots <strong>#27</strong> - <strong>#31</strong>.</p>\n\n<pre><code>C:\\Program Files (x86)\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec.exe /FILE \n\"D:\\SSIS\\Practice\\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx\" \n/CONNECTION Excel;\"\\\"Provider=Microsoft.Jet.OLEDB.4.0;Data \nSource=D:\\SSIS\\Practice\\Currencies.xls;Extended Properties=\"\"EXCEL 8.0;HDR=YES\"\";\\\"\" \n/MAXCONCURRENT \" -1 \" /CHECKPOINTING OFF /REPORTING EWCDI\n</code></pre>\n\n<p>The new job should appear under SQL Server Agent –> Jobs node. Right-click on the newly created job 01_SSIS_Export_To_Excel and select <em>Start Job at Step…</em>, this will commence the job execution. The job will fail as expected because that is the context of this issue. Click Close to close the Start Jobs dialog. Refer screenshots <strong>#32</strong> and <strong>#33</strong>.</p>\n\n<p>Let’s take a look at what happened. Go to SQL Server Agent and Jobs node. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job failed. Expand the node near the red cross and click on the line that Step ID value of 1. At the bottom section, you can see the error message <strong><code>Option “8.0;HDR=YES’;” is not valid.</code></strong> Click Close to close the Log File Viewer window. Refer screenshots <strong>#34</strong> and <strong>#35</strong>.</p>\n\n<p>Now, right-click on the job and select Properties to open the Job Properties. You can also double-click on the job to bring the Job Properties window. Click on the Steps on the left section. and click Edit. Replace the command with the following command and click OK. Click OK on the Job Properties to close the window. Right-click on the job 01_SSIS_Export_To_Excel and select Start Job at Step…, this will commence the job execution. The job will fail execute successfully. Click Close to close the Start Jobs dialog. Let’s take a look at the history. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job succeeded during the second run. Expand the node near the green tick cross and click on the line that Step ID value of 1. At the bottom section, you can see the message Option The step succeeded. Click Close to close the Log File Viewer window. The file D:\\SSIS\\Practice\\Currencies.xls will be successfully populated with the data. If you execute the job successfully multiple times, the data will get appended to the file and you will find more data. As I mentioned earlier, this is not the right-way to generate the files. This example was created to demonstrate a fix for this issue. Refer screenshots <strong>#36</strong> - <strong>#38</strong>.</p>\n\n<p>Screenshot <strong>#39</strong> shows the differences between the working and the non-working command line arguments. The one on the right is the working command line and the left one is incorrect. It required another double quotes with backslash escape sequence to fix the error. There could be other ways to fix this well but this option seems to work.</p>\n\n<p>Thus, the example demonstrated a way to fix the command line argument issue while accessing Excel data source from an SSIS package that is deployed on a 64-bit server.</p>\n\n<p>Hope that helps someone.</p>\n\n<p><strong>Screenshots:</strong></p>\n\n<p><strong>#1:</strong> Solution_Explorer</p>\n\n<p><img src=\"https://i.stack.imgur.com/8LXYw.png\" alt=\"Solution_Explorer\"></p>\n\n<p><strong>#2:</strong> New_Connection_Data_Source</p>\n\n<p><img src=\"https://i.stack.imgur.com/kLUaJ.png\" alt=\"New_Connection_Data_Source\"></p>\n\n<p><strong>#3:</strong> Select_Data_Source</p>\n\n<p><img src=\"https://i.stack.imgur.com/dctco.png\" alt=\"Select_Data_Source\"></p>\n\n<p><strong>#4:</strong> New_Connection</p>\n\n<p><img src=\"https://i.stack.imgur.com/ENgBq.png\" alt=\"New_Connection\"></p>\n\n<p><strong>#5:</strong> Add_SSIS_Connection_Manager</p>\n\n<p><img src=\"https://i.stack.imgur.com/e477v.png\" alt=\"Add_SSIS_Connection_Manager\"></p>\n\n<p><strong>#6:</strong> Excel_Connection_Manager</p>\n\n<p><img src=\"https://i.stack.imgur.com/rLuSb.png\" alt=\"Excel_Connection_Manager\"></p>\n\n<p><strong>#7:</strong> Connection_Managers</p>\n\n<p><img src=\"https://i.stack.imgur.com/Tw4K1.png\" alt=\"Connection_Managers\"></p>\n\n<p><strong>#8:</strong> Variables</p>\n\n<p><img src=\"https://i.stack.imgur.com/wOuU5.png\" alt=\"Variables\"></p>\n\n<p><strong>#9:</strong> Stored_Procedure_Output</p>\n\n<p><img src=\"https://i.stack.imgur.com/mynyS.png\" alt=\"Stored_Procedure_Output\"></p>\n\n<p><strong>#10:</strong> Control_Flow</p>\n\n<p><img src=\"https://i.stack.imgur.com/DTucs.png\" alt=\"enter image description here\"></p>\n\n<p><strong>#11:</strong> OLE_DB_Source_Connections_Manager</p>\n\n<p><img src=\"https://i.stack.imgur.com/tLHQP.png\" alt=\"OLE_DB_Source_Connections_Manager\"></p>\n\n<p><strong>#12:</strong> OLE_DB_Source_Columns</p>\n\n<p><img src=\"https://i.stack.imgur.com/uxZZ4.png\" alt=\"OLE_DB_Source_Columns\"></p>\n\n<p><strong>#13:</strong> Excel_Destination_Editor_New</p>\n\n<p><img src=\"https://i.stack.imgur.com/nyUgx.png\" alt=\"Excel_Destination_Editor_New\"></p>\n\n<p><strong>#14:</strong> Excel_Destination_Create_Table</p>\n\n<p><img src=\"https://i.stack.imgur.com/UN5xT.png\" alt=\"Excel_Destination_Create_Table\"></p>\n\n<p><strong>#15:</strong> Excel_Destination_Edito</p>\n\n<p><img src=\"https://i.stack.imgur.com/RdH54.png\" alt=\"Excel_Destination_Edito\"></p>\n\n<p><strong>#16:</strong> Excel_Destination_Mappings</p>\n\n<p><img src=\"https://i.stack.imgur.com/iPO8y.png\" alt=\"Excel_Destination_Mappings\"></p>\n\n<p><strong>#17:</strong> Data_Flow</p>\n\n<p><img src=\"https://i.stack.imgur.com/wLxa4.png\" alt=\"Data_Flow\"></p>\n\n<p><strong>#18:</strong> Successful_Package_Execution_Control</p>\n\n<p><img src=\"https://i.stack.imgur.com/TZ0ou.png\" alt=\"Successful_Package_Execution_Control\"></p>\n\n<p><strong>#19:</strong> Successful_Package_Execution_Data_Flow</p>\n\n<p><img src=\"https://i.stack.imgur.com/FI6VA.png\" alt=\"Successful_Package_Execution_Data_Flow\"></p>\n\n<p><strong>#20:</strong> C_Temp_File_Created</p>\n\n<p><img src=\"https://i.stack.imgur.com/VMjnn.png\" alt=\"C_Temp_File_Created\"></p>\n\n<p><strong>#21:</strong> Data_Populated</p>\n\n<p><img src=\"https://i.stack.imgur.com/IYhUg.png\" alt=\"Data_Populated\"></p>\n\n<p><strong>#22:</strong> File_On_Server</p>\n\n<p><img src=\"https://i.stack.imgur.com/k7hKu.png\" alt=\"File_On_Server\"></p>\n\n<p><strong>#23:</strong> SQL_Server_Version</p>\n\n<p><img src=\"https://i.stack.imgur.com/n2gpY.png\" alt=\"SQL_Server_Version\"></p>\n\n<p><strong>#24:</strong> Execute_Package_Utility_General</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZNCW0.png\" alt=\"Execute_Package_Utility_General\"></p>\n\n<p><strong>#25:</strong> Execute_Package_Utility_Connection_Managers</p>\n\n<p><img src=\"https://i.stack.imgur.com/o39ar.png\" alt=\"Execute_Package_Utility_Connection_Managers\"></p>\n\n<p><strong>#26:</strong> Execute_Package_Utility_Command_Line</p>\n\n<p><img src=\"https://i.stack.imgur.com/mq9Ts.png\" alt=\"Execute_Package_Utility_Command_Line\"></p>\n\n<p><strong>#27:</strong> Job_New_Job</p>\n\n<p><img src=\"https://i.stack.imgur.com/Dx17J.png\" alt=\"Job_New_Job\"></p>\n\n<p><strong>#28:</strong> New_Job_General</p>\n\n<p><img src=\"https://i.stack.imgur.com/Wwk7H.png\" alt=\"New_Job_General\"></p>\n\n<p><strong>#29:</strong> New_Job_Step</p>\n\n<p><img src=\"https://i.stack.imgur.com/5VDWF.png\" alt=\"New_Job_Step\"></p>\n\n<p><strong>#30:</strong> New_Job_Step_General </p>\n\n<p><img src=\"https://i.stack.imgur.com/MTXMT.png\" alt=\"New_Job_Step_General\"></p>\n\n<p><strong>#31:</strong> New_Job_Steps_Added</p>\n\n<p><img src=\"https://i.stack.imgur.com/p9IeS.png\" alt=\"New_Job_Steps_Added\"></p>\n\n<p><strong>#32:</strong> Job_Start_Job_at_Step</p>\n\n<p><img src=\"https://i.stack.imgur.com/Qpef2.png\" alt=\"Job_Start_Job_at_Step\"></p>\n\n<p><strong>#33:</strong> SQL_Job_Execution_Failure</p>\n\n<p><img src=\"https://i.stack.imgur.com/qSPdR.png\" alt=\"SQL_Job_Execution_Failure\"></p>\n\n<p><strong>#34:</strong> View_History</p>\n\n<p><img src=\"https://i.stack.imgur.com/xZqWk.png\" alt=\"View_History\"></p>\n\n<p><strong>#35:</strong> SQL_Job_Error_Message</p>\n\n<p><img src=\"https://i.stack.imgur.com/oYovo.png\" alt=\"SQL_Job_Error_Message\"></p>\n\n<p><strong>#36:</strong> SQL_Job_Execution_Success</p>\n\n<p><img src=\"https://i.stack.imgur.com/fYeKc.png\" alt=\"SQL_Job_Execution_Success\"></p>\n\n<p><strong>#37:</strong> SQL_Job_Success_Message</p>\n\n<p><img src=\"https://i.stack.imgur.com/3yEQe.png\" alt=\"SQL_Job_Success_Message\"></p>\n\n<p><strong>#38:</strong> Excel_File_Generated</p>\n\n<p><img src=\"https://i.stack.imgur.com/ovlVm.png\" alt=\"Excel_File_Generated\"></p>\n\n<p><strong>#39:</strong> Command_Comparison</p>\n\n<p><img src=\"https://i.stack.imgur.com/2h7mX.png\" alt=\"39_Command_Comparison\"></p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2375/" ]
I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files. So far I have this: ``` DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties= ""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E ``` This gives me the error: **`Option "Properties=Excel 8.0;HDR=Yes" is not valid.`** I've tried a few variations with the Quotation marks but have not been able to get it right yet. Does anyone know how to fix this? **`UPDATE:`** Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.
This step-by-step example is for others who might stumble upon this question. This example uses *SSIS 2005* and uses *SQL Server 2005 64-bit edition server* to run the job. The answer here concentrates only on fixing the error message mentioned in the question. The example will demonstrate the steps to recreate the issue and also the cause of the issue followed by how to fix it. **`NOTE:`** I would recommend using the option of storing the package configuration values in database or using indirect XML configuration with the help of Environment Variables. Also, the steps to create Excel file would be done using a template which would then archived by moving to a different folder. These steps are not discussed in this post. As mentioned earlier, the purpose of this post is to address the error. Let’s proceed with the example. I have also blogged about this answer, which can be found in [this link](http://learnbycoding.com/2011/07/accessing-excel-data-source-from-an-ssis-package-that-is-deployed-on-a-64-bit-server/). It is the same answer. Create an SSIS package ([Steps to create an SSIS package](http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/)). This example uses BIDS 2005. I have named the package in the format YYYYMMDD\_hhmm in the beginning followed by SO stands for Stack Overflow, followed by the SO question id, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have a Data Sources named Adventure Works. I will be using Adventure Works data source, which points to AdventureWorks database downloaded from [this link](http://msftdbprodsamples.codeplex.com/). The example uses SQL Server 2008 R2 database. Refer screenshot **#1**. In the AdventureWorks database, create a stored procedure named *dbo.GetCurrency* using the below given script. ``` CREATE PROCEDURE [dbo].[GetCurrency] AS BEGIN SET NOCOUNT ON; SELECT TOP 10 CurrencyCode , Name , ModifiedDate FROM Sales.Currency ORDER BY CurrencyCode END GO ``` On the package’s Connection Manager section, right-click and select *New Connection From Data Source*. On the *Select Data Source* dialog, select *Adventure Works* and click OK. You should now see the Adventure Works data source under the *Connection Managers* section. On the package’s Connection Managers section, right-click again but this time select *New Connection…*. This is to create the Excel connection. On the Add SSIS Connection Manager, select *EXCEL*. On the Excel Connection Manager, enter the path *C:\Temp\Template.xls*. When we deploy it to the server, we will change this path. I have selected Excel version *Microsoft Excel 97-2005* and chose to leave the checkbox *First row has column names* checked so that the create the Excel file is created column headers. Click *OK*. Rename the Excel connection to *Excel*, just to keep it simple. Refer screenshots **#2** - **#7**. On the package, create the following variable. Refer screenshot **#8**. * *SQLGetData*: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value *EXEC dbo.GetCurrency* Screenshot **#9** shows the output of the stored procedure execution statement *EXEC dbo.GetCurrency* On the package’s Control Flow tab, place a `Data Flow task` and name it as Export to Excel. Refer screenshot **#10**. Double-click on the Data Flow Task to switch to the Data Flow tab. On the Data Flow tab, place an `OLE DB Source` to connect to the SQL Server data to fetch the data from the stored procedure and name it as SQL. Double-click on the OLE DB Source to bring up the OLE DB Source Editor. On the Connection Manager section, select *Adventure Works* from the OLE DB connection manager, select SQL command from variable from Data access mode and select the variable *User::SQLGetData* from the Variable name drop down. On the Columns section, make sure the column names are mapped correctly. Click OK to close the OLE DB Source Editor. Refer screenshots **#11** and **#12**. On the Data Flow tab, place an `Excel Destination` to insert the data into the Excel file and name it as Excel. Double-click on the Excel Destination to open the Excel Destination Editor. On the Connection Manager section, select Excel from the OLE DB connection manager and select Table or view from Data access mode. At this point, we don’t have an Excel because while creating the Excel connection manager, we simply specified the path but never created the file. Hence, there won’t be any values in the drop down Name of the Excel sheet. So, click the *New…* button (the second New one) to create a new Excel sheet. On the Create Table window, BIDS automatically provide a create sheet based on the incoming data source. You can change the values according to your preferences. I will simply click OK by retaining the default value. The name of the sheet will be populated in the drop down Name of the Excel sheet. The name of the sheet is taken from the task name, here in this case the Excel Destination, which we have named it as Excel. On the Mappings section, make sure the column names are mapped correctly. Click OK to close the Excel Destination Editor. Refer screenshots **#13** - **#16**. Once the data flow task is configured, it should look like as shown in screenshot **#17**. Execute the package by pressing F5. Screenshots **#18** - **#21** show the successful execution of the package in both Control Flow and Data Flow Task. Also, the file is generated in the path *C:\Temp\Template.xls* provided in the Excel connection and the data shown in the stored procedure execution output matches with the data written to the file. The package developed on my local machine in the folder path *C:\Learn\Learn.VS2005\Learn.SSIS*. Now, we need to deploy the files on to the Server that hosts the 64-bit version of the SQL Server to schedule a job. So, the folder on the server would be *D:\SSIS\Practice*. Copy the package file (**.dtsx**) from the local machine and paste it in the server folder. Also, in order for the package to run correctly, we need to have the Excel spreadsheet present on the server. Otherwise, the validation will fail. Usually, I create a Template folder that will contain the empty Excel spreadsheet file that matches the output. Later, during run time I will change the Excel output path to a different location using package configuration. For this example, I am going to keep it simple. So, let’s copy the Excel file generated in the local machine in the path *C:\Temp\Template.xls* to the server location *D:\SSIS\Practice*. I want the SQL job to generate the file in the name Currencies.xls. So, rename the file Template.xls to *Currencies.xls*. Refer screenshot **#22**. To show that I am indeed going to run the job on the server in a 64-bit edition of SQL Server, I executed the command SELECT @@version on the SQL Server and screenshot **#23** shows the results. We will use *Execute Package Utility* (dtexec.exe) to generate the command line parameters. Log into the server which will run the SSIS package in an SQL job. Double-click on the package file, this will bring the Execute Package Utility. On the General section, select File system from Package source. Click on the Ellipsis and browse to the package path. On the Connection Managers section, select Excel and change the path inside the Excel file from C:\Temp\Template.xls to D:\SSIS\Practice\Currencies.xls. The changes made in the Utility will generate a command line accordingly on the Command Line section. On the Command Line section, copy the Command line that contains all the necessary parameters. We are not going to execute the package from here. Click *Close*. Refer screenshots **#24** - **#26**. Next, we need to set up a job to run the SSIS package. We cannot choose SQL Server Integration Services Package type because that will run under 64-bit and won’t find the Excel connection provider. So, we have to run it as `Operating System (CmdExec)` job type. Go to SQL Server Management Studio and connect to the Database Engine. Expand SQL Server Agent and right-click on Jobs node. Select New Job…. On the General section of the Job Properties window, provide the job name as 01\_SSIS\_Export\_To\_Excel, Owner will be the user creating the job. I have a Category named SSIS, so I will select that but the default category is *[Uncategorized (Local)]* and provide a brief description. On the Steps section, click *New…* button. This will bring Job Step properties. On the General section of the Job Step properties, provide Step name as Export to Excel, Select type `Operating system (CmdExec)`, leave the default Run as account as SQL Server Agent Service Account and provide the following Command. Click OK. On the New Job window, Click OK. Refer screenshots **#27** - **#31**. ``` C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe /FILE "D:\SSIS\Practice\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx" /CONNECTION Excel;"\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\SSIS\Practice\Currencies.xls;Extended Properties=""EXCEL 8.0;HDR=YES"";\"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EWCDI ``` The new job should appear under SQL Server Agent –> Jobs node. Right-click on the newly created job 01\_SSIS\_Export\_To\_Excel and select *Start Job at Step…*, this will commence the job execution. The job will fail as expected because that is the context of this issue. Click Close to close the Start Jobs dialog. Refer screenshots **#32** and **#33**. Let’s take a look at what happened. Go to SQL Server Agent and Jobs node. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job failed. Expand the node near the red cross and click on the line that Step ID value of 1. At the bottom section, you can see the error message **`Option “8.0;HDR=YES’;” is not valid.`** Click Close to close the Log File Viewer window. Refer screenshots **#34** and **#35**. Now, right-click on the job and select Properties to open the Job Properties. You can also double-click on the job to bring the Job Properties window. Click on the Steps on the left section. and click Edit. Replace the command with the following command and click OK. Click OK on the Job Properties to close the window. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select Start Job at Step…, this will commence the job execution. The job will fail execute successfully. Click Close to close the Start Jobs dialog. Let’s take a look at the history. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job succeeded during the second run. Expand the node near the green tick cross and click on the line that Step ID value of 1. At the bottom section, you can see the message Option The step succeeded. Click Close to close the Log File Viewer window. The file D:\SSIS\Practice\Currencies.xls will be successfully populated with the data. If you execute the job successfully multiple times, the data will get appended to the file and you will find more data. As I mentioned earlier, this is not the right-way to generate the files. This example was created to demonstrate a fix for this issue. Refer screenshots **#36** - **#38**. Screenshot **#39** shows the differences between the working and the non-working command line arguments. The one on the right is the working command line and the left one is incorrect. It required another double quotes with backslash escape sequence to fix the error. There could be other ways to fix this well but this option seems to work. Thus, the example demonstrated a way to fix the command line argument issue while accessing Excel data source from an SSIS package that is deployed on a 64-bit server. Hope that helps someone. **Screenshots:** **#1:** Solution\_Explorer ![Solution_Explorer](https://i.stack.imgur.com/8LXYw.png) **#2:** New\_Connection\_Data\_Source ![New_Connection_Data_Source](https://i.stack.imgur.com/kLUaJ.png) **#3:** Select\_Data\_Source ![Select_Data_Source](https://i.stack.imgur.com/dctco.png) **#4:** New\_Connection ![New_Connection](https://i.stack.imgur.com/ENgBq.png) **#5:** Add\_SSIS\_Connection\_Manager ![Add_SSIS_Connection_Manager](https://i.stack.imgur.com/e477v.png) **#6:** Excel\_Connection\_Manager ![Excel_Connection_Manager](https://i.stack.imgur.com/rLuSb.png) **#7:** Connection\_Managers ![Connection_Managers](https://i.stack.imgur.com/Tw4K1.png) **#8:** Variables ![Variables](https://i.stack.imgur.com/wOuU5.png) **#9:** Stored\_Procedure\_Output ![Stored_Procedure_Output](https://i.stack.imgur.com/mynyS.png) **#10:** Control\_Flow ![enter image description here](https://i.stack.imgur.com/DTucs.png) **#11:** OLE\_DB\_Source\_Connections\_Manager ![OLE_DB_Source_Connections_Manager](https://i.stack.imgur.com/tLHQP.png) **#12:** OLE\_DB\_Source\_Columns ![OLE_DB_Source_Columns](https://i.stack.imgur.com/uxZZ4.png) **#13:** Excel\_Destination\_Editor\_New ![Excel_Destination_Editor_New](https://i.stack.imgur.com/nyUgx.png) **#14:** Excel\_Destination\_Create\_Table ![Excel_Destination_Create_Table](https://i.stack.imgur.com/UN5xT.png) **#15:** Excel\_Destination\_Edito ![Excel_Destination_Edito](https://i.stack.imgur.com/RdH54.png) **#16:** Excel\_Destination\_Mappings ![Excel_Destination_Mappings](https://i.stack.imgur.com/iPO8y.png) **#17:** Data\_Flow ![Data_Flow](https://i.stack.imgur.com/wLxa4.png) **#18:** Successful\_Package\_Execution\_Control ![Successful_Package_Execution_Control](https://i.stack.imgur.com/TZ0ou.png) **#19:** Successful\_Package\_Execution\_Data\_Flow ![Successful_Package_Execution_Data_Flow](https://i.stack.imgur.com/FI6VA.png) **#20:** C\_Temp\_File\_Created ![C_Temp_File_Created](https://i.stack.imgur.com/VMjnn.png) **#21:** Data\_Populated ![Data_Populated](https://i.stack.imgur.com/IYhUg.png) **#22:** File\_On\_Server ![File_On_Server](https://i.stack.imgur.com/k7hKu.png) **#23:** SQL\_Server\_Version ![SQL_Server_Version](https://i.stack.imgur.com/n2gpY.png) **#24:** Execute\_Package\_Utility\_General ![Execute_Package_Utility_General](https://i.stack.imgur.com/ZNCW0.png) **#25:** Execute\_Package\_Utility\_Connection\_Managers ![Execute_Package_Utility_Connection_Managers](https://i.stack.imgur.com/o39ar.png) **#26:** Execute\_Package\_Utility\_Command\_Line ![Execute_Package_Utility_Command_Line](https://i.stack.imgur.com/mq9Ts.png) **#27:** Job\_New\_Job ![Job_New_Job](https://i.stack.imgur.com/Dx17J.png) **#28:** New\_Job\_General ![New_Job_General](https://i.stack.imgur.com/Wwk7H.png) **#29:** New\_Job\_Step ![New_Job_Step](https://i.stack.imgur.com/5VDWF.png) **#30:** New\_Job\_Step\_General ![New_Job_Step_General](https://i.stack.imgur.com/MTXMT.png) **#31:** New\_Job\_Steps\_Added ![New_Job_Steps_Added](https://i.stack.imgur.com/p9IeS.png) **#32:** Job\_Start\_Job\_at\_Step ![Job_Start_Job_at_Step](https://i.stack.imgur.com/Qpef2.png) **#33:** SQL\_Job\_Execution\_Failure ![SQL_Job_Execution_Failure](https://i.stack.imgur.com/qSPdR.png) **#34:** View\_History ![View_History](https://i.stack.imgur.com/xZqWk.png) **#35:** SQL\_Job\_Error\_Message ![SQL_Job_Error_Message](https://i.stack.imgur.com/oYovo.png) **#36:** SQL\_Job\_Execution\_Success ![SQL_Job_Execution_Success](https://i.stack.imgur.com/fYeKc.png) **#37:** SQL\_Job\_Success\_Message ![SQL_Job_Success_Message](https://i.stack.imgur.com/3yEQe.png) **#38:** Excel\_File\_Generated ![Excel_File_Generated](https://i.stack.imgur.com/ovlVm.png) **#39:** Command\_Comparison ![39_Command_Comparison](https://i.stack.imgur.com/2h7mX.png)
21,449
<p>What is the difference between the following types of endianness?</p> <ul> <li>byte (8b) invariant big and little endianness</li> <li>half-word (16b) invariant big and little endianness</li> <li>word (32b) invariant big and little endianness</li> <li>double-word (64b) invariant big and little endianness</li> </ul> <p>Are there other types/variations?</p>
[ { "answer_id": 21455, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": -1, "selected": false, "text": "<p>the basic concept is the ordering of bits:</p>\n\n<pre><code>1010 0011\n</code></pre>\n\n<p>in little-endian is the same as</p>\n\n<pre><code>0011 1010\n</code></pre>\n\n<p>in big-endian (and vice-versa).</p>\n\n<p>You'll notice the order changes by grouping, not by individual bit. I don't know of a system, for example, where</p>\n\n<pre><code>1100 0101\n</code></pre>\n\n<p>would be the \"other-endian\" version of the first version.</p>\n" }, { "answer_id": 21470, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 2, "selected": false, "text": "<p>There's also middle or mixed endian. See <a href=\"http://en.wikipedia.org/wiki/Middle_endian#Middle-endian\" rel=\"nofollow noreferrer\">wikipedia</a> for details.</p>\n\n<p>The only time I had to worry about this was when writing some networking code in C. Networking typically uses big-endian IIRC. Most languages either abstract the whole thing or offer libraries to guarantee that you're using the right endian-ness though.</p>\n" }, { "answer_id": 21531, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "<p>Actually, I'd describe the endianness of a machine as the order of <strong>bytes</strong> inside of a word, and not the order of <strong>bits</strong>.</p>\n\n<p>By \"bytes\" up there I mean the \"smallest unit of memory the architecture can manage individually\". So, if the smallest unit is 16 bits long (what in x86 would be called a <em>word</em>) then a 32 bit \"word\" representing the value 0xFFFF0000 could be stored like this:</p>\n\n<pre><code>FFFF 0000\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>0000 FFFF\n</code></pre>\n\n<p>in memory, depending on endianness.</p>\n\n<p>So, if you have 8-bit endianness, it means that every word consisting of 16 bits, will be stored as:</p>\n\n<pre><code>FF 00\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>00 FF\n</code></pre>\n\n<p>and so on.</p>\n" }, { "answer_id": 21624, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 2, "selected": false, "text": "<p>Best article I read about endianness \"<a href=\"http://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/\" rel=\"nofollow noreferrer\">Understanding Big and Little Endian Byte Order</a>\".</p>\n" }, { "answer_id": 61730, "author": "Ben Lever", "author_id": 2045, "author_profile": "https://Stackoverflow.com/users/2045", "pm_score": 5, "selected": false, "text": "<p>There are two approaches to endian mapping: <em>address invariance</em> and <em>data invariance</em>.</p>\n\n<h2>Address Invariance</h2>\n\n<p>In this type of mapping, the address of bytes is always preserved between big and little. This has the side effect of reversing the order of significance (most significant to least significant) of a particular datum (e.g. 2 or 4 byte word) and therefore the interpretation of data. Specifically, in little-endian, the interpretation of data is least-significant to most-significant bytes whilst in big-endian, the interpretation is most-significant to least-significant. In both cases, the set of bytes accessed remains the same.</p>\n\n<p><strong>Example</strong></p>\n\n<p>Address invariance (also known as <em>byte invariance</em>): the byte address is constant but byte significance is reversed.</p>\n\n<pre><code>Addr Memory\n 7 0\n | | (LE) (BE)\n |----|\n +0 | aa | lsb msb\n |----|\n +1 | bb | : :\n |----|\n +2 | cc | : :\n |----|\n +3 | dd | msb lsb\n |----|\n | |\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xaa (preserved)\nRead 2 bytes: 0xbbaa 0xaabb\nRead 4 bytes: 0xddccbbaa 0xaabbccdd\n</code></pre>\n\n<h2>Data Invariance</h2>\n\n<p>In this type of mapping, the relative byte significance is preserved for datum of a particular size. There are therefore different types of data invariant endian mappings for different datum sizes. For example, a 32-bit word invariant endian mapping would be used for a datum size of 32. The effect of preserving the value of particular sized datum, is that the byte addresses of bytes within the datum are reversed between big and little endian mappings.</p>\n\n<p><strong>Example</strong></p>\n\n<p>32-bit data invariance (also known as <em>word invariance</em>): The datum is a 32-bit word which always has the value <code>0xddccbbaa</code>, independent of endianness. However, for accesses smaller than a word, the address of the bytes are reversed between big and little endian mappings.</p>\n\n<pre><code>Addr Memory\n\n | +3 +2 +1 +0 | &lt;- LE\n |-------------------|\n+0 msb | dd | cc | bb | aa | lsb\n |-------------------|\n+4 msb | 99 | 88 | 77 | 66 | lsb\n |-------------------|\n BE -&gt; | +0 +1 +2 +3 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xdd\nRead 2 bytes: 0xbbaa 0xddcc\nRead 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n</code></pre>\n\n<p><strong>Example</strong></p>\n\n<p>16-bit data invariance (also known as <em>half-word invariance</em>): The datum is a 16-bit\nwhich always has the value <code>0xbbaa</code>, independent of endianness. However, for accesses smaller than a half-word, the address of the bytes are reversed between big and little endian mappings.</p>\n\n<pre><code>Addr Memory\n\n | +1 +0 | &lt;- LE\n |---------|\n+0 msb | bb | aa | lsb\n |---------|\n+2 msb | dd | cc | lsb\n |---------|\n+4 msb | 77 | 66 | lsb\n |---------|\n+6 msb | 99 | 88 | lsb\n |---------|\n BE -&gt; | +0 +1 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0xbb\nRead 2 bytes: 0xbbaa 0xbbaa (preserved)\nRead 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n</code></pre>\n\n<p><strong>Example</strong></p>\n\n<p>64-bit data invariance (also known as <em>double-word invariance</em>): The datum is a 64-bit\nword which always has the value <code>0x99887766ddccbbaa</code>, independent of endianness. However, for accesses smaller than a double-word, the address of the bytes are reversed between big and little endian mappings.</p>\n\n<pre><code>Addr Memory\n\n | +7 +6 +5 +4 +3 +2 +1 +0 | &lt;- LE\n |---------------------------------------|\n+0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb\n |---------------------------------------|\n BE -&gt; | +0 +1 +2 +3 +4 +5 +6 +7 |\n\n\nAt Addr=0: Little-endian Big-endian\nRead 1 byte: 0xaa 0x99\nRead 2 bytes: 0xbbaa 0x9988\nRead 4 bytes: 0xddccbbaa 0x99887766\nRead 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)\n</code></pre>\n" }, { "answer_id": 68689, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "<p>Practically speaking, endianess refers to the way the processor will interpret the content of a given memory location. For example, if we have memory location 0x100 with the following content (hex bytes)</p>\n\n<pre><code>\n 0x100: 12 34 56 78 90 ab cd ef\n\nReads Little Endian Big Endian\n 8-bit: 12 12\n16-bit: 34 12 12 34\n32-bit: 78 56 34 12 12 34 56 78\n64-bit: ef cd ab 90 78 56 34 12 12 34 56 78 90 ab cd ef\n</code></pre>\n\n<p>The two situations where you need to mind endianess are with networking code and if you do down casting with pointers.</p>\n\n<p>TCP/IP specifies that data on the wire should be big endian. If you transmit types other than byte arrays (like pointers to structures), you should make sure to use the ntoh/hton macros to ensure the data is sent big endian. If you send from a little-endian processor to a big-endian processor (or vice versa), the data will be garbled...</p>\n\n<p>Casting issues:</p>\n\n<pre><code>\n uint32_t* lptr = 0x100;\n uint16_t data;\n *lptr = 0x0000FFFF\n\n data = *((uint16_t*)lptr);\n</code></pre>\n\n<p>What will be the value of data?\nOn a big-endian system, it would be 0 On a little-endian system, it would be FFFF</p>\n" }, { "answer_id": 69163, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "<p>13 years ago I worked on a tool portable to both a DEC ALPHA system and a PC. On this DEC ALPHA the <strong>bits were actually inverted</strong>. That is:</p>\n\n<pre><code>1010 0011\n</code></pre>\n\n<p>actually translated to</p>\n\n<pre><code>1100 0101\n</code></pre>\n\n<p>It was almost transparent and seamless in the C code except that I had a bitfield declared like</p>\n\n<pre><code>typedef struct {\n int firstbit:1;\n int middlebits:10;\n int lastbits:21;\n};\n</code></pre>\n\n<p>that needed to be translated to (using #ifdef conditional compiling)</p>\n\n<pre><code>typedef struct {\n int lastbits:21;\n int middlebits:10;\n int firstbit:1;\n};\n</code></pre>\n" }, { "answer_id": 3581332, "author": "eel ghEEz", "author_id": 80772, "author_profile": "https://Stackoverflow.com/users/80772", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/21449/types-of-endianness/69163#69163\">Philibert</a> said,</p>\n\n<blockquote>\n <p>bits were actually inverted</p>\n</blockquote>\n\n<p>I doubt any architecture would break byte value invariance. The order of bit-fields may need inversion when mapping structs containing them against data. Such direct mapping relies on compiler specifics which are outside the C99 standard but which may still be common. Direct mapping is faster but does not comply with the C99 standard that does not stipulate packing, alignment and byte order. C99-compliant code should use slow mapping based on values rather than addresses. That is, instead of doing this,</p>\n\n<pre><code>#if LITTLE_ENDIAN\n struct breakdown_t {\n int least_significant_bit: 1;\n int middle_bits: 10;\n int most_significant_bits: 21;\n };\n#elif BIG_ENDIAN\n struct breakdown_t {\n int most_significant_bits: 21;\n int middle_bits: 10;\n int least_significant_bit: 1;\n };\n#else\n #error Huh\n#endif\n\nuint32_t data = ...;\nstruct breakdown_t *b = (struct breakdown_t *)&amp;data;\n</code></pre>\n\n<p>one should write this (and this is how the compiler would generate code anyways even for the above \"direct mapping\"),</p>\n\n<pre><code>uint32_t data = ...;\nuint32_t least_significant_bit = data &amp; 0x00000001;\nuint32_t middle_bits = (data &gt;&gt; 1) &amp; 0x000003FF;\nuint32_t most_significant_bits = (data &gt;&gt; 11) &amp; 0x001fffff;\n</code></pre>\n\n<p>The reason behind the need to invert the order of bit-fields in each endian-neutral, application-specific data storage unit is that compilers pack bit-fields into bytes of growing addresses. </p>\n\n<p>The \"order of bits\" in each byte does not matter as the only way to extract them is by applying masks of values and by shifting to the the least-significant-bit or most-significant-bit direction. The \"order of bits\" issue would only become important in imaginary architectures with the notion of bit addresses. I believe all existing architectures hide this notion in hardware and provide only least vs. most significant bit extraction which is the notion based on the endian-neutral byte values.</p>\n" }, { "answer_id": 71747967, "author": "Meloman", "author_id": 2282880, "author_profile": "https://Stackoverflow.com/users/2282880", "pm_score": 0, "selected": false, "text": "<p>As @erik-van-brakel answered on this post, be careful when communicating with certain PLC : <strong>Mixed-endian still alive !</strong></p>\n<p>Indeed, I need to communicate with a PLC (from a well known manufacturer) with (Modbus-TCP) OPC protocol and it seems that it returns me a mixed-endian on every half word. So it is still used by some of the larger manufacturers.</p>\n<p>Here is an example with the &quot;pieces&quot; string :</p>\n<p><a href=\"https://i.stack.imgur.com/Pzsdi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Pzsdi.png\" alt=\"https://i.imgur.com/VrdriAt.png\" /></a></p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
What is the difference between the following types of endianness? * byte (8b) invariant big and little endianness * half-word (16b) invariant big and little endianness * word (32b) invariant big and little endianness * double-word (64b) invariant big and little endianness Are there other types/variations?
There are two approaches to endian mapping: *address invariance* and *data invariance*. Address Invariance ------------------ In this type of mapping, the address of bytes is always preserved between big and little. This has the side effect of reversing the order of significance (most significant to least significant) of a particular datum (e.g. 2 or 4 byte word) and therefore the interpretation of data. Specifically, in little-endian, the interpretation of data is least-significant to most-significant bytes whilst in big-endian, the interpretation is most-significant to least-significant. In both cases, the set of bytes accessed remains the same. **Example** Address invariance (also known as *byte invariance*): the byte address is constant but byte significance is reversed. ``` Addr Memory 7 0 | | (LE) (BE) |----| +0 | aa | lsb msb |----| +1 | bb | : : |----| +2 | cc | : : |----| +3 | dd | msb lsb |----| | | At Addr=0: Little-endian Big-endian Read 1 byte: 0xaa 0xaa (preserved) Read 2 bytes: 0xbbaa 0xaabb Read 4 bytes: 0xddccbbaa 0xaabbccdd ``` Data Invariance --------------- In this type of mapping, the relative byte significance is preserved for datum of a particular size. There are therefore different types of data invariant endian mappings for different datum sizes. For example, a 32-bit word invariant endian mapping would be used for a datum size of 32. The effect of preserving the value of particular sized datum, is that the byte addresses of bytes within the datum are reversed between big and little endian mappings. **Example** 32-bit data invariance (also known as *word invariance*): The datum is a 32-bit word which always has the value `0xddccbbaa`, independent of endianness. However, for accesses smaller than a word, the address of the bytes are reversed between big and little endian mappings. ``` Addr Memory | +3 +2 +1 +0 | <- LE |-------------------| +0 msb | dd | cc | bb | aa | lsb |-------------------| +4 msb | 99 | 88 | 77 | 66 | lsb |-------------------| BE -> | +0 +1 +2 +3 | At Addr=0: Little-endian Big-endian Read 1 byte: 0xaa 0xdd Read 2 bytes: 0xbbaa 0xddcc Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved) Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved) ``` **Example** 16-bit data invariance (also known as *half-word invariance*): The datum is a 16-bit which always has the value `0xbbaa`, independent of endianness. However, for accesses smaller than a half-word, the address of the bytes are reversed between big and little endian mappings. ``` Addr Memory | +1 +0 | <- LE |---------| +0 msb | bb | aa | lsb |---------| +2 msb | dd | cc | lsb |---------| +4 msb | 77 | 66 | lsb |---------| +6 msb | 99 | 88 | lsb |---------| BE -> | +0 +1 | At Addr=0: Little-endian Big-endian Read 1 byte: 0xaa 0xbb Read 2 bytes: 0xbbaa 0xbbaa (preserved) Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved) Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved) ``` **Example** 64-bit data invariance (also known as *double-word invariance*): The datum is a 64-bit word which always has the value `0x99887766ddccbbaa`, independent of endianness. However, for accesses smaller than a double-word, the address of the bytes are reversed between big and little endian mappings. ``` Addr Memory | +7 +6 +5 +4 +3 +2 +1 +0 | <- LE |---------------------------------------| +0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb |---------------------------------------| BE -> | +0 +1 +2 +3 +4 +5 +6 +7 | At Addr=0: Little-endian Big-endian Read 1 byte: 0xaa 0x99 Read 2 bytes: 0xbbaa 0x9988 Read 4 bytes: 0xddccbbaa 0x99887766 Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved) ```
21,454
<p>How do I go about specifying and using an ENUM in a Django model?</p>
[ { "answer_id": 21468, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 7, "selected": false, "text": "<p>From the <a href=\"https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices\" rel=\"noreferrer\">Django documentation</a>:</p>\n\n<pre><code>MAYBECHOICE = (\n ('y', 'Yes'),\n ('n', 'No'),\n ('u', 'Unknown'),\n)\n</code></pre>\n\n<p>And you define a charfield in your model :</p>\n\n<pre><code>married = models.CharField(max_length=1, choices=MAYBECHOICE)\n</code></pre>\n\n<p>You can do the same with integer fields if you don't like to have letters\nin your db.</p>\n\n<p>In that case, rewrite your choices:</p>\n\n<pre><code>MAYBECHOICE = (\n (0, 'Yes'),\n (1, 'No'),\n (2, 'Unknown'),\n)\n</code></pre>\n" }, { "answer_id": 33932, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 5, "selected": false, "text": "<p>Using the <code>choices</code> parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use <code>choices</code> with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options:</p>\n\n<ol>\n<li>Use \"./manage.py sql appname\" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, \"./manage.py syncdb\" won't mess with it.</li>\n<li>If you don't want to do this manually every time you generate your DB, put some custom SQL in appname/sql/modelname.sql to perform the appropriate ALTER TABLE command.</li>\n<li>Create a <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields\" rel=\"noreferrer\">custom field type</a> and define the db_type method appropriately.</li>\n</ol>\n\n<p>With any of these options, it would be your responsibility to deal with the implications for cross-database portability. In option 2, you could use <a href=\"http://www.djangoproject.com/documentation/model-api/#database-backend-specific-sql-data\" rel=\"noreferrer\">database-backend-specific custom SQL</a> to ensure your ALTER TABLE is only run on MySQL. In option 3, your db_type method would need to check the database engine and set the db column type to a type that actually exists in that database.</p>\n\n<p><strong>UPDATE</strong>: Since the migrations framework was added in Django 1.7, options 1 and 2 above are entirely obsolete. Option 3 was always the best option anyway. The new version of options 1/2 would involve a complex custom migration using <code>SeparateDatabaseAndState</code> -- but really you want option 3.</p>\n" }, { "answer_id": 334932, "author": "Charles Merriam", "author_id": 1320510, "author_profile": "https://Stackoverflow.com/users/1320510", "pm_score": 3, "selected": false, "text": "<p>If you really want to use your databases ENUM type:</p>\n\n<ol>\n<li>Use Django 1.x</li>\n<li>Recognize your application will only work on some databases.</li>\n<li>Puzzle through this documentation page:<a href=\"http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields</a></li>\n</ol>\n\n<p>Good luck!</p>\n" }, { "answer_id": 1530858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>from django.db import models\n\nclass EnumField(models.Field):\n \"\"\"\n A field class that maps to MySQL's ENUM type.\n\n Usage:\n\n class Card(models.Model):\n suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts'))\n\n c = Card()\n c.suit = 'Clubs'\n c.save()\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.values = kwargs.pop('values')\n kwargs['choices'] = [(v, v) for v in self.values]\n kwargs['default'] = self.values[0]\n super(EnumField, self).__init__(*args, **kwargs)\n\n def db_type(self):\n return \"enum({0})\".format( ','.join(\"'%s'\" % v for v in self.values) )\n</code></pre>\n" }, { "answer_id": 13089465, "author": "keithxm23", "author_id": 1415352, "author_profile": "https://Stackoverflow.com/users/1415352", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/\">http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/</a></p>\n\n<blockquote>\n<pre><code>class Entry(models.Model):\n LIVE_STATUS = 1\n DRAFT_STATUS = 2\n HIDDEN_STATUS = 3\n STATUS_CHOICES = (\n (LIVE_STATUS, 'Live'),\n (DRAFT_STATUS, 'Draft'),\n (HIDDEN_STATUS, 'Hidden'),\n )\n # ...some other fields here...\n status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)\n\nlive_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)\ndraft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)\n\nif entry_object.status == Entry.LIVE_STATUS:\n</code></pre>\n</blockquote>\n\n<p>This is another nice and easy way of implementing enums although it doesn't really save enums in the database.</p>\n\n<p>However it does allow you to reference the 'label' whenever querying or specifying defaults as opposed to the top-rated answer where you have to use the 'value' (which may be a number).</p>\n" }, { "answer_id": 19040441, "author": "David Cain", "author_id": 815632, "author_profile": "https://Stackoverflow.com/users/815632", "pm_score": 3, "selected": false, "text": "<p>Setting <code>choices</code> on the field will allow some validation on the Django end, but it <em>won't</em> define any form of an enumerated type on the database end.</p>\n\n<p>As others have mentioned, the solution is to specify <a href=\"https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.db_type\"><code>db_type</code></a> on a custom field.</p>\n\n<p>If you're using a SQL backend (e.g. MySQL), you can do this like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from django.db import models\n\n\nclass EnumField(models.Field):\n def __init__(self, *args, **kwargs):\n super(EnumField, self).__init__(*args, **kwargs)\n assert self.choices, \"Need choices for enumeration\"\n\n def db_type(self, connection):\n if not all(isinstance(col, basestring) for col, _ in self.choices):\n raise ValueError(\"MySQL ENUM values should be strings\")\n return \"ENUM({})\".format(','.join(\"'{}'\".format(col) \n for col, _ in self.choices))\n\n\nclass IceCreamFlavor(EnumField, models.CharField):\n def __init__(self, *args, **kwargs):\n flavors = [('chocolate', 'Chocolate'),\n ('vanilla', 'Vanilla'),\n ]\n super(IceCreamFlavor, self).__init__(*args, choices=flavors, **kwargs)\n\n\nclass IceCream(models.Model):\n price = models.DecimalField(max_digits=4, decimal_places=2)\n flavor = IceCreamFlavor(max_length=20)\n</code></pre>\n\n<p>Run <code>syncdb</code>, and inspect your table to see that the <code>ENUM</code> was created properly.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>mysql&gt; SHOW COLUMNS IN icecream;\n+--------+-----------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-----------------------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| price | decimal(4,2) | NO | | NULL | |\n| flavor | enum('chocolate','vanilla') | NO | | NULL | |\n+--------+-----------------------------+------+-----+---------+----------------+\n</code></pre>\n" }, { "answer_id": 22155357, "author": "Kenzo", "author_id": 1576113, "author_profile": "https://Stackoverflow.com/users/1576113", "pm_score": -1, "selected": false, "text": "<p>A the top of your models.py file, add this line after you do your imports:</p>\n\n<pre><code> enum = lambda *l: [(s,_(s)) for s in l]\n</code></pre>\n" }, { "answer_id": 28408589, "author": "AncientSwordRage", "author_id": 1075247, "author_profile": "https://Stackoverflow.com/users/1075247", "pm_score": 2, "selected": false, "text": "<p>There're currently two github projects based on adding these, though I've not looked into exactly how they're implemented:</p>\n\n<ol>\n<li><a href=\"https://github.com/5monkeys/django-enumfield\" rel=\"nofollow\">Django-EnumField</a>:<br>\nProvides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. </li>\n<li><a href=\"https://github.com/hzdg/django-enumfields\" rel=\"nofollow\">Django-EnumFields</a>:<br>\nThis package lets you use real Python (PEP435-style) enums with Django.</li>\n</ol>\n\n<p>I don't think either use DB enum types, but they are <a href=\"https://github.com/5monkeys/django-enumfield/issues/18\" rel=\"nofollow\">in the works</a> for first one.</p>\n" }, { "answer_id": 58052062, "author": "Cesar Canassa", "author_id": 360829, "author_profile": "https://Stackoverflow.com/users/360829", "pm_score": 3, "selected": false, "text": "<h1>Django 3.0 has built-in support for Enums</h1>\n\n<p>From the <a href=\"https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices-enum-types\" rel=\"noreferrer\">documentation</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from django.utils.translation import gettext_lazy as _\n\nclass Student(models.Model):\n\n class YearInSchool(models.TextChoices):\n FRESHMAN = 'FR', _('Freshman')\n SOPHOMORE = 'SO', _('Sophomore')\n JUNIOR = 'JR', _('Junior')\n SENIOR = 'SR', _('Senior')\n GRADUATE = 'GR', _('Graduate')\n\n year_in_school = models.CharField(\n max_length=2,\n choices=YearInSchool.choices,\n default=YearInSchool.FRESHMAN,\n )\n</code></pre>\n\n<p>Now, be aware that <strong>it does not enforce the choices at a database level</strong> this is Python only construct. If you want to also enforce those value at the database you could combine that with database constraints:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Student(models.Model):\n ...\n\n class Meta:\n constraints = [\n CheckConstraint(\n check=Q(year_in_school__in=YearInSchool.values),\n name=\"valid_year_in_school\")\n ]\n</code></pre>\n" }, { "answer_id": 73765582, "author": "Nikolay", "author_id": 11620296, "author_profile": "https://Stackoverflow.com/users/11620296", "pm_score": 1, "selected": false, "text": "<p>If you have to have enum type in MySQL table and not a &quot;fake&quot; enum (only visible on python side) then you can try <a href=\"https://github.com/adamchainz/django-mysql\" rel=\"nofollow noreferrer\"><strong>Django-MySQL</strong></a> extension and its <a href=\"https://django-mysql.readthedocs.io/en/latest/model_fields/enum_field.html\" rel=\"nofollow noreferrer\">EnumField</a>.</p>\n<p>The models:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from django.db import models\nfrom django_mysql.models import EnumField\n\n\nclass IceCreamFlavor(models.TextChoices):\n CHOCOLATE = &quot;chocolate&quot;\n VANILLA = &quot;vanilla&quot;\n\n\nclass IceCream(models.Model):\n price = models.DecimalField(max_digits=4, decimal_places=2)\n ice_cream_flavor = EnumField(choices=IceCreamFlavor.choices)\n\n</code></pre>\n<p>Resulting table:</p>\n<pre><code>mysql&gt; SHOW COLUMNS IN myapp.db_icecream;\n+------------------+-----------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+-----------------------------+------+-----+---------+----------------+\n| id | int | NO | PRI | NULL | auto_increment |\n| price | decimal(4,2) | NO | | NULL | |\n| ice_cream_flavor | enum('chocolate','vanilla') | NO | | NULL | |\n+------------------+-----------------------------+------+-----+---------+----------------+\n\n</code></pre>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019/" ]
How do I go about specifying and using an ENUM in a Django model?
From the [Django documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices): ``` MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), ) ``` And you define a charfield in your model : ``` married = models.CharField(max_length=1, choices=MAYBECHOICE) ``` You can do the same with integer fields if you don't like to have letters in your db. In that case, rewrite your choices: ``` MAYBECHOICE = ( (0, 'Yes'), (1, 'No'), (2, 'Unknown'), ) ```
21,461
<pre><code>#if SYMBOL //code #endif </code></pre> <p>what values does C# predefine for use?</p>
[ { "answer_id": 21467, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>Depends on what /define compiler options you use. <code>Visual Studio</code> puts the <code>DEBUG</code> symbol in there for you via the project settings, but you could create any ones that you want.</p>\n" }, { "answer_id": 21479, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "<p>To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from <code>#define</code> and <code>/define</code>.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx\" rel=\"nofollow noreferrer\">#if on MSDN</a></p>\n" }, { "answer_id": 21502, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Well, that depends on the compiler you are using, and the command line options. Mono defines different names than Microsoft's compiler by default, and depending on what system you are you get different defines, etc.</p>\n\n<p>If you provide a more specific system for which you are compiling, we might be able to come up with the list for that particular system (for example: x64 Vista system, using Visual Studio 2008).</p>\n" } ]
2008/08/21
[ "https://Stackoverflow.com/questions/21461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
``` #if SYMBOL //code #endif ``` what values does C# predefine for use?
To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from `#define` and `/define`. [#if on MSDN](http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx)
21,489
<p>SQL Experts,</p> <p>Is there an efficient way to group runs of data together using SQL?<br> Or is it going to be more efficient to process the data in code. </p> <p>For example if I have the following data:</p> <pre><code>ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith </code></pre> <p>I need to display this:</p> <pre><code>Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith </code></pre> <p>@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.</p>
[ { "answer_id": 21492, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>For this particular case, all you need to do is group by the name and ask for the count, like this:</p>\n\n<pre><code>select Name, count(*)\nfrom MyTable\ngroup by Name\n</code></pre>\n\n<p>That'll get you the count for each name as a second column.</p>\n\n<p>You can get it all as one column by concatenating like this:</p>\n\n<pre><code>select Name + ' (' + cast(count(*) as varchar) + ')'\nfrom MyTable\ngroup by Name\n</code></pre>\n" }, { "answer_id": 21510, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 1, "selected": false, "text": "<p>Well, this:</p>\n\n<pre><code>select Name, count(Id)\nfrom MyTable\ngroup by Name\n</code></pre>\n\n<p>will give you this:</p>\n\n<pre><code>Harry Johns, 1\nAdam Taylor, 1\nJohn Smith, 2\nBill Manning, 1\n</code></pre>\n\n<p>and this (MS SQL syntax):</p>\n\n<pre><code>select Name +\n case when ( count(Id) &gt; 1 ) \n then ' ('+cast(count(Id) as varchar)+')' \n else ''\n end\nfrom MyTable\ngroup by Name\n</code></pre>\n\n<p>will give you this:</p>\n\n<pre><code>Harry Johns\nAdam Taylor\nJohn Smith (2)\nBill Manning\n</code></pre>\n\n<p>Did you actually want that other John Smith on the end of your results?</p>\n\n<p>EDIT: Oh I see, you want consecutive runs grouped. In that case, I'd say you need a cursor or to do it in your program code.</p>\n" }, { "answer_id": 21545, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>select n.name, \n (select count(*) \n from myTable n1\n where n1.name = n.name and n1.id &gt;= n.id and (n1.id &lt;=\n (\n select isnull(min(nn.id), (select max(id) + 1 from myTable))\n from myTable nn\n where nn.id &gt; n.id and nn.name &lt;&gt; n.name\n )\n ))\nfrom myTable n\nwhere not exists (\n select 1\n from myTable n3\n where n3.name = n.name and n3.id &lt; n.id and n3.id &gt; (\n select isnull(max(n4.id), (select min(id) - 1 from myTable))\n from myTable n4\n where n4.id &lt; n.id and n4.name &lt;&gt; n.name\n )\n)\n</code></pre>\n\n<p>I think that'll do what you want. Bit of a kludge though.</p>\n\n<p>Phew! After a few edits I think I have all the edge cases sorted out.</p>\n" }, { "answer_id": 21555, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 2, "selected": false, "text": "<p>I hate cursors with a passion... but here's a dodgy cursor version...</p>\n\n<pre><code>Declare @NewName Varchar(50)\nDeclare @OldName Varchar(50)\nDeclare @CountNum int\nSet @CountNum = 0\n\nDECLARE nameCursor CURSOR FOR \nSELECT Name\nFROM NameTest\nOPEN nameCursor\n\nFETCH NEXT FROM nameCursor INTO @NewName\n\n WHILE @@FETCH_STATUS = 0 \n\n BEGIN\n\n if @OldName &lt;&gt; @NewName\n BEGIN\n Print @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'\n Set @CountNum = 0\n END\n SELECT @OldName = @NewName\n FETCH NEXT FROM nameCursor INTO @NewName\n Set @CountNum = @CountNum + 1\n\n END\nPrint @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'\n\nCLOSE nameCursor\nDEALLOCATE nameCursor\n</code></pre>\n" }, { "answer_id": 21561, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>declare @tmp table (Id int, Nm varchar(50));\n\ninsert @tmp select 1, 'Harry Johns';\ninsert @tmp select 2, 'Adam Taylor';\ninsert @tmp select 3, 'John Smith';\ninsert @tmp select 4, 'John Smith';\ninsert @tmp select 5, 'Bill Manning';\ninsert @tmp select 6, 'John Smith';\n\nselect * from @tmp order by Id;\n\nselect Nm, count(1) from \n(\nselect Id, Nm, \n case when exists (\n select 1 from @tmp t2 \n where t2.Nm=t1.Nm \n and (t2.Id = t1.Id + 1 or t2.Id = t1.Id - 1)) \n then 1 else 0 end as Run\nfrom @tmp t1\n) truns group by Nm, Run\n</code></pre>\n\n<p>[Edit] That can be shortened a bit</p>\n\n<pre><code>select Nm, count(1) from (select Id, Nm, case when exists (\n select 1 from @tmp t2 where t2.Nm=t1.Nm \n and abs(t2.Id-t1.Id)=1) then 1 else 0 end as Run\nfrom @tmp t1) t group by Nm, Run\n</code></pre>\n" }, { "answer_id": 21768, "author": "Jon Erickson", "author_id": 1950, "author_profile": "https://Stackoverflow.com/users/1950", "pm_score": 2, "selected": false, "text": "<p>My solution just for kicks (this was a fun exercise), no cursors, no iterations, but i do have a helper field</p>\n\n<pre><code>-- Setup test table\nDECLARE @names TABLE (\n id INT IDENTITY(1,1),\n name NVARCHAR(25) NOT NULL,\n grp UNIQUEIDENTIFIER NULL\n )\n\nINSERT @names (name)\nSELECT 'Harry Johns' UNION ALL \nSELECT 'Adam Taylor' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'Bill Manning' UNION ALL\nSELECT 'John Smith' UNION ALL\nSELECT 'Bill Manning' \n\n-- Set the first id's group to a newid()\nUPDATE n\nSET grp = newid()\nFROM @names n\nWHERE n.id = (SELECT MIN(id) FROM @names)\n\n-- Set the group to a newid() if the name does not equal the previous\nUPDATE n\nSET grp = newid()\nFROM @names n\nINNER JOIN @names b\n ON (n.ID - 1) = b.ID\n AND ISNULL(b.Name, '') &lt;&gt; n.Name\n\n-- Set groups that are null to the previous group\n-- Keep on doing this until all groups have been set\nWHILE (EXISTS(SELECT 1 FROM @names WHERE grp IS NULL))\nBEGIN\n UPDATE n\n SET grp = b.grp\n FROM @names n\n INNER JOIN @names b\n ON (n.ID - 1) = b.ID\n AND n.grp IS NULL\nEND\n\n-- Final output\nSELECT MIN(id) AS id_start,\n MAX(id) AS id_end,\n name,\n count(1) AS consecutive\nFROM @names\nGROUP BY grp, \n name\nORDER BY id_start\n\n/*\nResults:\n\nid_start id_end name consecutive\n1 1 Harry Johns 1\n2 2 Adam Taylor 1\n3 4 John Smith 2\n5 7 Bill Manning 3\n8 8 John Smith 1\n9 9 Bill Manning 1\n*/\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
SQL Experts, Is there an efficient way to group runs of data together using SQL? Or is it going to be more efficient to process the data in code. For example if I have the following data: ``` ID|Name 01|Harry Johns 02|Adam Taylor 03|John Smith 04|John Smith 05|Bill Manning 06|John Smith ``` I need to display this: ``` Harry Johns Adam Taylor John Smith (2) Bill Manning John Smith ``` @Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.
Try this: ``` select n.name, (select count(*) from myTable n1 where n1.name = n.name and n1.id >= n.id and (n1.id <= ( select isnull(min(nn.id), (select max(id) + 1 from myTable)) from myTable nn where nn.id > n.id and nn.name <> n.name ) )) from myTable n where not exists ( select 1 from myTable n3 where n3.name = n.name and n3.id < n.id and n3.id > ( select isnull(max(n4.id), (select min(id) - 1 from myTable)) from myTable n4 where n4.id < n.id and n4.name <> n.name ) ) ``` I think that'll do what you want. Bit of a kludge though. Phew! After a few edits I think I have all the edge cases sorted out.
21,547
<p>I've spent a good amount of time coming up with solution to this problem, so in the spirit of <a href="https://stackoverflow.com/questions/21245/questions-vs-conveying-information">this post</a>, I'm posting it here, since I think it might be useful to others. </p> <p>If anyone has a better script, or anything to add, please post it.</p> <p>Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.</p>
[ { "answer_id": 21551, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 5, "selected": false, "text": "<p>Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.</p>\n\n<pre><code>declare @schema varchar(100), @table varchar(100)\nset @schema = 'dbo' -- set schema name here\nset @table = 'MyTable' -- set table name here\ndeclare @sql table(s varchar(1000), id int identity)\n\n-- create statement\ninsert into @sql(s) values ('create table [' + @table + '] (')\n\n-- column list\ninsert into @sql(s)\nselect \n ' ['+column_name+'] ' + \n data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=@table\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(@table) as varchar) + ',' + \n cast(ident_incr(@table) as varchar) + ')'\n else ''\n end + ' ' +\n ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','\n\n from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema\n order by ordinal_position\n\n-- primary key\ndeclare @pkname varchar(100)\nselect @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nwhere table_name = @table and constraint_type='PRIMARY KEY'\n\nif ( @pkname is not null ) begin\n insert into @sql(s) values(' PRIMARY KEY (')\n insert into @sql(s)\n select ' ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n where constraint_name = @pkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' )')\nend\nelse begin\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\nend\n\n-- closing bracket\ninsert into @sql(s) values( ')' )\n\n-- result!\nselect s from @sql order by id\n</code></pre>\n" }, { "answer_id": 22126, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "<p>Credit due to @Blorgbeard for sharing his script. I'll certainly bookmark it in case I need it.</p>\n\n<p>Yes, you can \"right click\" on the table and script the <code>CREATE TABLE</code> script, but:</p>\n\n<ul>\n<li>The a script will contain <strong>loads</strong> of cruft (interested in the extended properties anyone?)</li>\n<li>If you have 200+ tables in your schema, it's going to take you half a day to script the lot by hand.</li>\n</ul>\n\n<p>With this script converted into a stored procedure, and combined with a wrapper script you would have a nice automated way to dump your table design into source control etc.</p>\n\n<p>The rest of your DB code (SP's, FK indexes, Triggers etc) would be under source control anyway ;)</p>\n" }, { "answer_id": 119784, "author": "Joel Rein", "author_id": 20961, "author_profile": "https://Stackoverflow.com/users/20961", "pm_score": 2, "selected": false, "text": "<p>Something I've noticed - in the INFORMATION_SCHEMA.COLUMNS view, CHARACTER_MAXIMUM_LENGTH gives a size of 2147483647 (2^31-1) for field types such as image and text. ntext is 2^30-1 (being double-byte unicode and all).</p>\n\n<p>This size is included in the output from this query, but it is invalid for these data types in a CREATE statement (they should not have a maximum size value at all). So unless the results from this are manually corrected, the CREATE script won't work given these data types.</p>\n\n<p>I imagine it's possible to fix the script to account for this, but that's beyond my SQL capabilities.</p>\n" }, { "answer_id": 119827, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are using management studio and have the query analyzer window open you can drag the table name to the query analyzer window and ... bingo! you get the table script. \nI've not tried this in SQL2008</p>\n" }, { "answer_id": 317864, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<p>I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).</p>\n\n<pre><code>\nselect 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END\nfrom sysobjects so\ncross apply\n (SELECT \n ' ['+column_name+'] ' + \n data_type + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'xml' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=so.name\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end + ' ' +\n (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + \n case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' \n\n from information_schema.columns where table_name = so.name\n order by ordinal_position\n FOR XML PATH('')) o (list)\nleft join\n information_schema.table_constraints tc\non tc.Table_name = so.Name\nAND tc.Constraint_Type = 'PRIMARY KEY'\ncross apply\n (select '[' + Column_Name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY\n ORDINAL_POSITION\n FOR XML PATH('')) j (list)\nwhere xtype = 'U'\nAND name NOT IN ('dtproperties')\n\n</code></pre>\n\n<p><strong>Update:</strong> Added handling of the XML data type</p>\n\n<p><strong>Update 2:</strong> Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name</p>\n" }, { "answer_id": 317894, "author": "user25623", "author_id": 25623, "author_profile": "https://Stackoverflow.com/users/25623", "pm_score": 3, "selected": false, "text": "<p>If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this <a href=\"http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated\" rel=\"noreferrer\">SQL Team link</a> on how to use SMO to script objects.</p>\n" }, { "answer_id": 991321, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "<p>-- or you could create a stored procedure ... first with Id creation </p>\n\n<pre><code>USE [db]\nGO\n\n/****** Object: StoredProcedure [dbo].[procUtils_InsertGeneratorWithId] Script Date: 06/13/2009 22:18:11 ******/\nSET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\n\ncreate PROC [dbo].[procUtils_InsertGeneratorWithId] \n( \n@domain_user varchar(50), \n@tableName varchar(100) \n) \n\n\nas \n\n--Declare a cursor to retrieve column specific information for the specified table \nDECLARE cursCol CURSOR FAST_FORWARD FOR \nSELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName \nOPEN cursCol \nDECLARE @string nvarchar(3000) --for storing the first half of INSERT statement \nDECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement \nDECLARE @dataType nvarchar(1000) --data types returned for respective columns \nDECLARE @IDENTITY_STRING nvarchar ( 100 ) \nSET @IDENTITY_STRING = ' ' \nselect @IDENTITY_STRING \nSET @string='INSERT '+@tableName+'(' \nSET @stringData='' \n\nDECLARE @colName nvarchar(50) \n\nFETCH NEXT FROM cursCol INTO @colName,@dataType \n\nIF @@fetch_status&lt;&gt;0 \n begin \n print 'Table '+@tableName+' not found, processing skipped.' \n close curscol \n deallocate curscol \n return \nEND \n\nWHILE @@FETCH_STATUS=0 \nBEGIN \nIF @dataType in ('varchar','char','nchar','nvarchar') \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+' \nEND \nELSE \nif @dataType in ('text','ntext') --if the datatype is text or something else \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+' \nEND \nELSE \nIF @dataType = 'money' --because money doesn't get converted from varchar implicitly \nBEGIN \n SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \nEND \nELSE \nIF @dataType='datetime' \nBEGIN \n --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+' \n --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \n --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \n SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n -- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \nEND \nELSE \nIF @dataType='image' \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+' \nEND \nELSE --presuming the data type is int,bit,numeric,decimal \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+' \n --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+' \nEND \n\nSET @string=@string+@colName+',' \n\nFETCH NEXT FROM cursCol INTO @colName,@dataType \nEND \nDECLARE @Query nvarchar(4000) \n\nSET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName \nexec sp_executesql @query \n--select @query \n\nCLOSE cursCol \nDEALLOCATE cursCol \n\n\n /*\nUSAGE\n\n*/\n\nGO\n</code></pre>\n\n<p>-- and second without iD INSERTION</p>\n\n<pre><code>USE [db]\nGO\n\n/****** Object: StoredProcedure [dbo].[procUtils_InsertGenerator] Script Date: 06/13/2009 22:20:52 ******/\nSET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE PROC [dbo].[procUtils_InsertGenerator] \n( \n@domain_user varchar(50), \n@tableName varchar(100) \n) \n\n\nas \n\n--Declare a cursor to retrieve column specific information for the specified table \nDECLARE cursCol CURSOR FAST_FORWARD FOR \n\n\n-- SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName \n/* NEW \nSELECT c.name , sc.data_type FROM sys.extended_properties AS ep \nINNER JOIN sys.tables AS t ON ep.major_id = t.object_id \nINNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id \n= c.column_id \nINNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and \nc.name = sc.column_name \nWHERE t.name = @tableName and c.is_identity=0 \n */ \n\nselect object_name(c.object_id) \"TABLE_NAME\", c.name \"COLUMN_NAME\", s.name \"DATA_TYPE\" \n from sys.columns c \n join sys.systypes s on (s.xtype = c.system_type_id) \n where object_name(c.object_id) in (select name from sys.tables where name not like 'sysdiagrams') \n AND object_name(c.object_id) in (select name from sys.tables where [name]=@tableName ) and c.is_identity=0 and s.name not like 'sysname' \n\n\n\n\nOPEN cursCol \nDECLARE @string nvarchar(3000) --for storing the first half of INSERT statement \nDECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement \nDECLARE @dataType nvarchar(1000) --data types returned for respective columns \nDECLARE @IDENTITY_STRING nvarchar ( 100 ) \nSET @IDENTITY_STRING = ' ' \nselect @IDENTITY_STRING \nSET @string='INSERT '+@tableName+'(' \nSET @stringData='' \n\nDECLARE @colName nvarchar(50) \n\nFETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType \n\nIF @@fetch_status&lt;&gt;0 \n begin \n print 'Table '+@tableName+' not found, processing skipped.' \n close curscol \n deallocate curscol \n return \nEND \n\nWHILE @@FETCH_STATUS=0 \nBEGIN \nIF @dataType in ('varchar','char','nchar','nvarchar') \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+' \nEND \nELSE \nif @dataType in ('text','ntext') --if the datatype is text or something else \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+' \nEND \nELSE \nIF @dataType = 'money' --because money doesn't get converted from varchar implicitly \nBEGIN \n SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \nEND \nELSE \nIF @dataType='datetime' \nBEGIN \n --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+' \n --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \n --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+' \n SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n -- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations \nEND \nELSE \nIF @dataType='image' \nBEGIN \n SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+' \nEND \nELSE --presuming the data type is int,bit,numeric,decimal \nBEGIN \n --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+' \n --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+' \n SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+' \nEND \n\nSET @string=@string+@colName+',' \n\nFETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType \nEND \nDECLARE @Query nvarchar(4000) \n\nSET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName \nexec sp_executesql @query \n--select @query \n\nCLOSE cursCol \nDEALLOCATE cursCol \n\n\n /* \n\nuse poc \ngo \n\nDECLARE @RC int \nDECLARE @domain_user varchar(50) \nDECLARE @tableName varchar(100) \n\n-- TODO: Set parameter values here. \nset @domain_user='yorgeorg' \nset @tableName = 'tbGui_WizardTabButtonAreas' \n\nEXECUTE @RC = [POC].[dbo].[procUtils_InsertGenerator] \n @domain_user \n ,@tableName \n\n*/\nGO\n</code></pre>\n" }, { "answer_id": 4687819, "author": "viljun", "author_id": 575183, "author_profile": "https://Stackoverflow.com/users/575183", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.varuste.net/show_create_table.html\" rel=\"nofollow\">Show create table in classic asp</a> (handles constraints, primary keys, copying the table structure and/or data ...)</p>\n\n<blockquote>\n <p>Sql server Show create table\n Mysql-style \"Show create table\" and \"show create database\" commands from Microsoft sql server.\n The script is written is Microsoft asp-language and is quite easy to port to another language.*</p>\n</blockquote>\n" }, { "answer_id": 10115560, "author": "8kb", "author_id": 375799, "author_profile": "https://Stackoverflow.com/users/375799", "pm_score": 4, "selected": false, "text": "<p>There is a Powershell script buried in the <a href=\"http://social.msdn.microsoft.com/Forums/en/sqlsmoanddmo/thread/69784251-ff9a-4eb2-96a2-9eacb292bd4a\">msdb</a> forums that will script all the tables and related objects: </p>\n\n<pre><code># Script all tables in a database\n[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SqlServer.SMO\") \n | out-null\n\n$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '&lt;Servername&gt;'\n$db = $s.Databases['&lt;Database&gt;']\n\n$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)\n$scrp.Options.AppendToFile = $True\n$scrp.Options.ClusteredIndexes = $True\n$scrp.Options.DriAll = $True\n$scrp.Options.ScriptDrops = $False\n$scrp.Options.IncludeHeaders = $False\n$scrp.Options.ToFileOnly = $True\n$scrp.Options.Indexes = $True\n$scrp.Options.WithDependencies = $True\n$scrp.Options.FileName = 'C:\\Temp\\&lt;Database&gt;.SQL'\n\nforeach($item in $db.Tables) { $tablearray+=@($item) }\n$scrp.Script($tablearray)\n\nWrite-Host \"Scripting complete\"\n</code></pre>\n" }, { "answer_id": 15645815, "author": "zanlok", "author_id": 512671, "author_profile": "https://Stackoverflow.com/users/512671", "pm_score": 4, "selected": false, "text": "<p><strong>Support for schemas:</strong></p>\n\n<p>This is an updated version that amends the great answer from David, et al. Added is support for named schemas. It should be noted this may break if there's actually tables of the same name present within various schemas. Another improvement is the use of the official <a href=\"http://msdn.microsoft.com/en-us/library/ms176114.aspx\" rel=\"nofollow noreferrer\">QuoteName()</a> function.</p>\n\n<pre><code>SELECT \n t.TABLE_CATALOG,\n t.TABLE_SCHEMA,\n t.TABLE_NAME,\n 'create table '+QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) + ' (' + LEFT(o.List, Len(o.List)-1) + '); ' \n + CASE WHEN tc.Constraint_Name IS NULL THEN '' \n ELSE \n 'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) \n + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + '); ' \n END as 'SQL_CREATE_TABLE'\nFROM sysobjects so\n\nCROSS APPLY (\n SELECT \n ' ['+column_name+'] ' \n + data_type \n + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else \n coalesce(\n '('+ case when character_maximum_length = -1 \n then 'MAX' \n else cast(character_maximum_length as varchar) end \n + ')','') \n end \n + ' ' \n + case when exists ( \n SELECT id \n FROM syscolumns\n WHERE \n object_name(id) = so.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end \n + ' ' \n + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) \n + 'NULL ' \n + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT \n ELSE '' \n END \n + ',' -- can't have a field name or we'll end up with XML\n\n FROM information_schema.columns \n WHERE table_name = so.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n) o (list)\n\nLEFT JOIN information_schema.table_constraints tc on \n tc.Table_name = so.Name\n AND tc.Constraint_Type = 'PRIMARY KEY'\n\nLEFT JOIN information_schema.tables t on \n t.Table_name = so.Name\n\nCROSS APPLY (\n SELECT QuoteName(Column_Name) + ', '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY ORDINAL_POSITION\n FOR XML PATH('')\n) j (list)\n\nWHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n -- AND so.name = 'ASPStateTempSessions'\n;\n</code></pre>\n\n<p>..</p>\n\n<p><strong>For use in Management Studio:</strong></p>\n\n<p>One detractor to the sql code above is if you test it using SSMS, long statements aren't easy to read. So, as per <a href=\"https://stackoverflow.com/questions/2679481/ssms-results-to-grid-crlf-not-preserved-in-copy-paste-any-better-techniques\">this helpful post</a>, here's another version that's somewhat modified to be easier on the eyes after clicking the link of a cell in the grid. The results are more readily identifiable as nicely formatted CREATE TABLE statements for each table in the db.</p>\n\n<pre><code>-- settings\nDECLARE @CRLF NCHAR(2)\nSET @CRLF = Nchar(13) + NChar(10)\nDECLARE @PLACEHOLDER NCHAR(3)\nSET @PLACEHOLDER = '{:}'\n\n-- the main query\nSELECT \n t.TABLE_CATALOG,\n t.TABLE_SCHEMA,\n t.TABLE_NAME,\n CAST(\n REPLACE(\n 'create table ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.name) + ' (' + @CRLF \n + LEFT(o.List, Len(o.List) - (LEN(@PLACEHOLDER)+2)) + @CRLF + ');' + @CRLF\n + CASE WHEN tc.Constraint_Name IS NULL THEN '' \n ELSE\n 'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.Name) \n + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY (' + LEFT(j.List, Len(j.List) - 1) + ');' + @CRLF\n END,\n @PLACEHOLDER,\n @CRLF\n )\n AS XML) as 'SQL_CREATE_TABLE'\nFROM sysobjects so\n\nCROSS APPLY (\n SELECT \n ' '\n + '['+column_name+'] ' \n + data_type \n + case data_type\n when 'sql_variant' then ''\n when 'text' then ''\n when 'ntext' then ''\n when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'\n else \n coalesce(\n '('+ case when character_maximum_length = -1 \n then 'MAX' \n else cast(character_maximum_length as varchar) end \n + ')','') \n end \n + ' ' \n + case when exists ( \n SELECT id \n FROM syscolumns\n WHERE \n object_name(id) = so.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end \n + ' ' \n + (case when IS_NULLABLE = 'No' then 'NOT ' else '' end) \n + 'NULL ' \n + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT \n ELSE '' \n END \n + ', ' \n + @PLACEHOLDER -- note, can't have a field name or we'll end up with XML\n\n FROM information_schema.columns where table_name = so.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n) o (list)\n\nLEFT JOIN information_schema.table_constraints tc on \n tc.Table_name = so.Name\n AND tc.Constraint_Type = 'PRIMARY KEY'\n\nLEFT JOIN information_schema.tables t on \n t.Table_name = so.Name\n\nCROSS APPLY (\n SELECT QUOTENAME(Column_Name) + ', '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY ORDINAL_POSITION\n FOR XML PATH('')\n) j (list)\n\nWHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n -- AND so.name = 'ASPStateTempSessions'\n;\n</code></pre>\n\n<p>Not to belabor the point, but here's the functionally equivalent example outputs for comparison:</p>\n\n<pre><code>-- 1 (scripting version)\ncreate table [dbo].[ASPStateTempApplications] ( [AppId] int NOT NULL , [AppName] char(280) NOT NULL ); ALTER TABLE [dbo].[ASPStateTempApplications] ADD CONSTRAINT PK__ASPState__8E2CF7F908EA5793 PRIMARY KEY ([AppId]); \n\n-- 2 (SSMS version)\ncreate table [dbo].[ASPStateTempSessions] (\n [SessionId] nvarchar(88) NOT NULL , \n [Created] datetime NOT NULL DEFAULT (getutcdate()), \n [Expires] datetime NOT NULL , \n [LockDate] datetime NOT NULL , \n [LockDateLocal] datetime NOT NULL , \n [LockCookie] int NOT NULL , \n [Timeout] int NOT NULL , \n [Locked] bit NOT NULL , \n [SessionItemShort] varbinary(7000) NULL , \n [SessionItemLong] image(2147483647) NULL , \n [Flags] int NOT NULL DEFAULT ((0))\n);\nALTER TABLE [dbo].[ASPStateTempSessions] ADD CONSTRAINT PK__ASPState__C9F4929003317E3D PRIMARY KEY ([SessionId]);\n</code></pre>\n\n<p>..</p>\n\n<p><strong>Detracting factors:</strong></p>\n\n<p>It should be noted that I remain relatively unhappy with this due to the lack of support for indeces other than a primary key. It remains suitable for use as a mechanism for simple data export or replication.</p>\n" }, { "answer_id": 18619504, "author": "Hubbitus", "author_id": 307525, "author_profile": "https://Stackoverflow.com/users/307525", "pm_score": 3, "selected": false, "text": "<p>One more variant with foreign keys support and in one statement:</p>\n\n<pre><code> SELECT\n obj.name\n ,'CREATE TABLE [' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')'\n + ISNULL(' ' + refs.list, '')\n FROM sysobjects obj\n CROSS APPLY (\n SELECT \n CHAR(10)\n + ' [' + column_name + '] '\n + data_type\n + CASE data_type\n WHEN 'sql_variant' THEN ''\n WHEN 'text' THEN ''\n WHEN 'ntext' THEN ''\n WHEN 'xml' THEN ''\n WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'\n ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')\n END\n + ' '\n + case when exists ( -- Identity skip\n select id from syscolumns\n where object_name(id) = obj.name\n and name = column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(obj.name) as varchar) + ',' + \n cast(ident_incr(obj.name) as varchar) + ')'\n else ''\n end + ' '\n + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END\n + 'NULL'\n + CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END\n + ','\n FROM\n INFORMATION_SCHEMA.COLUMNS\n WHERE table_name = obj.name\n ORDER BY ordinal_position\n FOR XML PATH('')\n ) cols (list)\n CROSS APPLY(\n SELECT\n CHAR(10) + 'ALTER TABLE ' + obj.name + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)\n FROM(\n SELECT\n CHAR(10)\n + ' CONSTRAINT ' + tc.constraint_name\n + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'\n + COALESCE(CHAR(10) + r.list, ', ')\n FROM\n information_schema.table_constraints tc\n CROSS APPLY(\n SELECT\n '[' + kcu.column_name + '], '\n FROM\n information_schema.key_column_usage kcu\n WHERE\n kcu.constraint_name = tc.constraint_name\n ORDER BY\n kcu.ordinal_position\n FOR XML PATH('')\n ) c (list)\n OUTER APPLY(\n -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema\n SELECT\n ' REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '(' + kcu2.column_name + '), '\n FROM information_schema.referential_constraints as rc\n JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)\n JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)\n WHERE\n kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name\n ) r (list)\n WHERE tc.table_name = obj.name\n FOR XML PATH('')\n ) a (alt)\n ) refs (list)\n WHERE\n xtype = 'U'\n AND name NOT IN ('dtproperties')\n AND obj.name = 'your_table_name'\n</code></pre>\n\n<p>You could try in is sqlfiddle: <a href=\"http://sqlfiddle.com/#!6/e3b66/3/0\" rel=\"noreferrer\">http://sqlfiddle.com/#!6/e3b66/3/0</a></p>\n" }, { "answer_id": 25324645, "author": "JasmineOT", "author_id": 2991410, "author_profile": "https://Stackoverflow.com/users/2991410", "pm_score": 3, "selected": false, "text": "<p>I modified the accepted answer and now it can get the command including primary key and foreign key in a certain schema.</p>\n\n<pre><code>declare @table varchar(100)\ndeclare @schema varchar(100)\nset @table = 'Persons' -- set table name here\nset @schema = 'OT' -- set SCHEMA name here\ndeclare @sql table(s varchar(1000), id int identity)\n\n-- create statement\ninsert into @sql(s) values ('create table ' + @table + ' (')\n\n-- column list\ninsert into @sql(s)\nselect \n ' '+column_name+' ' + \n data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=@table\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(@table) as varchar) + ',' + \n cast(ident_incr(@table) as varchar) + ')'\n else ''\n end + ' ' +\n ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','\n\n from information_schema.columns where table_name = @table and table_schema = @schema\n order by ordinal_position\n\n-- primary key\ndeclare @pkname varchar(100)\nselect @pkname = constraint_name from information_schema.table_constraints\nwhere table_name = @table and constraint_type='PRIMARY KEY'\n\nif ( @pkname is not null ) begin\n insert into @sql(s) values(' PRIMARY KEY (')\n insert into @sql(s)\n select ' '+COLUMN_NAME+',' from information_schema.key_column_usage\n where constraint_name = @pkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' )')\nend\nelse begin\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\nend\n\n\n-- foreign key\ndeclare @fkname varchar(100)\nselect @fkname = constraint_name from information_schema.table_constraints\nwhere table_name = @table and constraint_type='FOREIGN KEY'\n\nif ( @fkname is not null ) begin\n insert into @sql(s) values(',')\n insert into @sql(s) values(' FOREIGN KEY (')\n insert into @sql(s)\n select ' '+COLUMN_NAME+',' from information_schema.key_column_usage\n where constraint_name = @fkname\n order by ordinal_position\n -- remove trailing comma\n update @sql set s=left(s,len(s)-1) where id=@@identity\n insert into @sql(s) values (' ) REFERENCES ')\n insert into @sql(s) \n SELECT \n OBJECT_NAME(fk.referenced_object_id)\n FROM \n sys.foreign_keys fk\n INNER JOIN \n sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id\n INNER JOIN\n sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id\n INNER JOIN\n sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id\n where fk.name = @fkname\n insert into @sql(s) \n SELECT \n '('+c2.name+')'\n FROM \n sys.foreign_keys fk\n INNER JOIN \n sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id\n INNER JOIN\n sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id\n INNER JOIN\n sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id\n where fk.name = @fkname\nend\n\n-- closing bracket\ninsert into @sql(s) values( ')' )\n\n-- result!\nselect s from @sql order by id\n</code></pre>\n" }, { "answer_id": 35092198, "author": "FLICKER", "author_id": 1017065, "author_profile": "https://Stackoverflow.com/users/1017065", "pm_score": 3, "selected": false, "text": "<p>I'm going to improve the answer by supporting partitioned tables:</p>\n\n<p>find partition scheme and partition key using below scritps:</p>\n\n<pre><code>declare @partition_scheme varchar(100) = (\nselect distinct ps.Name AS PartitionScheme\nfrom sys.indexes i \njoin sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id \njoin sys.partition_schemes ps on ps.data_space_id = i.data_space_id \nwhere i.object_id = object_id('your table name')\n)\nprint @partition_scheme\n\ndeclare @partition_column varchar(100) = (\nselect c.name \nfrom sys.tables t\njoin sys.indexes i \n on(i.object_id = t.object_id \n and i.index_id &lt; 2)\njoin sys.index_columns ic \n on(ic.partition_ordinal &gt; 0 \n and ic.index_id = i.index_id and ic.object_id = t.object_id)\njoin sys.columns c \n on(c.object_id = ic.object_id \n and c.column_id = ic.column_id)\nwhere t.object_id = object_id('your table name')\n)\nprint @partition_column\n</code></pre>\n\n<p>then change the generation query by adding below line at the right place:</p>\n\n<pre><code>+ IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')\n</code></pre>\n" }, { "answer_id": 41834624, "author": "Erick Lanford Xenes", "author_id": 5190625, "author_profile": "https://Stackoverflow.com/users/5190625", "pm_score": 2, "selected": false, "text": "<p>I include definitions for computed columns</p>\n\n<pre><code> select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name\nfrom sysobjects so\ncross apply\n (SELECT\n\ncase when comps.definition is not null then ' ['+column_name+'] AS ' + comps.definition \nelse\n ' ['+column_name+'] ' + data_type + \n case\n when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')\n then ''\n when data_type in ('float')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'\n when data_type in ('datetime2', 'datetimeoffset', 'time')\n then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'\n when data_type in ('decimal', 'numeric')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'\n when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1\n then '(max)'\n when character_maximum_length is not null\n then '(' + cast(character_maximum_length as varchar(11)) + ')'\n else ''\n end + ' ' +\n case when exists ( \n select id from syscolumns\n where object_name(id)=so.name\n and name=column_name\n and columnproperty(id,name,'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(so.name) as varchar) + ',' + \n cast(ident_incr(so.name) as varchar) + ')'\n else ''\n end + ' ' +\n (case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + \n case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END \nend + ', ' \n\n from information_schema.columns \n left join sys.computed_columns comps \n on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name\n\n where table_name = so.name\n order by ordinal_position\n FOR XML PATH('')) o (list)\nleft join\n information_schema.table_constraints tc\non tc.Table_name = so.Name\nAND tc.Constraint_Type = 'PRIMARY KEY'\ncross apply\n (select '[' + Column_Name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.Constraint_Name = tc.Constraint_Name\n ORDER BY\n ORDINAL_POSITION\n FOR XML PATH('')) j (list)\nwhere xtype = 'U'\nAND name NOT IN ('dtproperties')\n</code></pre>\n" }, { "answer_id": 46601179, "author": "Stu", "author_id": 178362, "author_profile": "https://Stackoverflow.com/users/178362", "pm_score": 2, "selected": false, "text": "<p>I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use</p>\n\n<pre><code>select into x from db.schema.y where 1=0\n</code></pre>\n\n<p>to copy the table to a new DB</p>\n" }, { "answer_id": 63866858, "author": "AMieres", "author_id": 4550898, "author_profile": "https://Stackoverflow.com/users/4550898", "pm_score": 1, "selected": false, "text": "<p>A query based on Hubbitus answer.</p>\n<ul>\n<li>includes schema names</li>\n<li>fixes foreign keys with more than one field</li>\n<li>includes CASCADE UPDATE &amp; DELETE</li>\n<li>includes a conditioned DROP TABLE</li>\n</ul>\n<pre><code>SELECT \n Schema_Name = SCHEMA_NAME(obj.uid)\n, Table_Name = name\n, Drop_Table = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + SCHEMA_NAME(obj.uid) + ''' AND TABLE_NAME = ''' + obj.name + '''))\nDROP TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] '\n, Create_Table ='\nCREATE TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')' + ISNULL(' ' + refs.list, '')\n FROM sysobjects obj\n CROSS APPLY (\n SELECT \n CHAR(10)\n + ' [' + column_name + '] '\n + data_type\n + CASE data_type\n WHEN 'sql_variant' THEN ''\n WHEN 'text' THEN ''\n WHEN 'ntext' THEN ''\n WHEN 'xml' THEN ''\n WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'\n ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')\n END\n + ' '\n + case when exists ( -- Identity skip\n select id from syscolumns\n where id = obj.id\n and name = column_name\n and columnproperty(id, name, 'IsIdentity') = 1 \n ) then\n 'IDENTITY(' + \n cast(ident_seed(obj.name) as varchar) + ',' + \n cast(ident_incr(obj.name) as varchar) + ')'\n else ''\n end + ' '\n + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END\n + 'NULL'\n + CASE WHEN IC.column_default IS NOT NULL THEN ' DEFAULT ' + IC.column_default ELSE '' END\n + ','\n FROM INFORMATION_SCHEMA.COLUMNS IC\n WHERE IC.table_name = obj.name\n AND IC.TABLE_SCHEMA = SCHEMA_NAME(obj.uid)\n ORDER BY ordinal_position\n FOR XML PATH('')\n ) cols (list)\n CROSS APPLY(\n SELECT\n CHAR(10) + 'ALTER TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] ADD ' + LEFT(alt, LEN(alt)-1)\n FROM(\n SELECT\n CHAR(10)\n + ' CONSTRAINT ' + tc.constraint_name\n + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'\n + COALESCE(CHAR(10) + r.list, ', ')\n FROM information_schema.table_constraints tc\n CROSS APPLY(\n SELECT '[' + kcu.column_name + '], '\n FROM information_schema.key_column_usage kcu\n WHERE kcu.constraint_name = tc.constraint_name\n ORDER BY kcu.ordinal_position\n FOR XML PATH('')\n ) c (list)\n OUTER APPLY(\n -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema\n SELECT LEFT(f.list, LEN(f.list)-1) + ')' + IIF(rc.DELETE_RULE = 'NO ACTION', '', ' ON DELETE ' + rc.DELETE_RULE) + IIF(rc.UPDATE_RULE = 'NO ACTION', '', ' ON UPDATE ' + rc.UPDATE_RULE) + ', '\n FROM information_schema.referential_constraints rc\n CROSS APPLY(\n SELECT IIF(kcu.ordinal_position = 1, ' REFERENCES [' + kcu.table_schema + '].[' + kcu.table_name + '] (', '') \n + '[' + kcu.column_name + '], '\n FROM information_schema.key_column_usage kcu \n WHERE kcu.constraint_catalog = rc.unique_constraint_catalog AND kcu.constraint_schema = rc.unique_constraint_schema AND kcu.constraint_name = rc.unique_constraint_name\n ORDER BY kcu.ordinal_position\n FOR XML PATH('')\n ) f (list)\n WHERE rc.constraint_catalog = tc.constraint_catalog \n AND rc.constraint_schema = tc.constraint_schema \n AND rc.constraint_name = tc.constraint_name\n ) r (list)\n WHERE tc.table_name = obj.name\n FOR XML PATH('')\n ) a (alt)\n ) refs (list)\n WHERE xtype = 'U'\n</code></pre>\n<p>To combine drop table (if exists) with create use like this:</p>\n<pre><code>SELECT Drop_Table + CHAR(10) + Create_Table FROM SysCreateTables\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
I've spent a good amount of time coming up with solution to this problem, so in the spirit of [this post](https://stackoverflow.com/questions/21245/questions-vs-conveying-information), I'm posting it here, since I think it might be useful to others. If anyone has a better script, or anything to add, please post it. Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.
I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply). ``` select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END from sysobjects so cross apply (SELECT ' ['+column_name+'] ' + data_type + case data_type when 'sql_variant' then '' when 'text' then '' when 'ntext' then '' when 'xml' then '' when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')' else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' + case when exists ( select id from syscolumns where object_name(id)=so.name and name=column_name and columnproperty(id,name,'IsIdentity') = 1 ) then 'IDENTITY(' + cast(ident_seed(so.name) as varchar) + ',' + cast(ident_incr(so.name) as varchar) + ')' else '' end + ' ' + (case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' + case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', ' from information_schema.columns where table_name = so.name order by ordinal_position FOR XML PATH('')) o (list) left join information_schema.table_constraints tc on tc.Table_name = so.Name AND tc.Constraint_Type = 'PRIMARY KEY' cross apply (select '[' + Column_Name + '], ' FROM information_schema.key_column_usage kcu WHERE kcu.Constraint_Name = tc.Constraint_Name ORDER BY ORDINAL_POSITION FOR XML PATH('')) j (list) where xtype = 'U' AND name NOT IN ('dtproperties') ``` **Update:** Added handling of the XML data type **Update 2:** Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name
21,558
<p>I want to know what a "<em>virtual base class</em>" is and what it means.</p> <p>Let me show an example:</p> <pre><code>class Foo { public: void DoSomething() { /* ... */ } }; class Bar : public virtual Foo { public: void DoSpecific() { /* ... */ } }; </code></pre>
[ { "answer_id": 21598, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 1, "selected": false, "text": "<p>It means a call to a virtual function will be forwarded to the \"right\" class.</p>\n\n<p>C++ <a href=\"https://isocpp.org/wiki/faq/multiple-inheritance\" rel=\"nofollow noreferrer\">FAQ Lite</a> FTW.</p>\n\n<p>In short, it is often used in multiple-inheritance scenarios, where a \"diamond\" hierarchy is formed. Virtual inheritance will then break the ambiguity created in the bottom class, when you call function in that class and the function needs to be resolved to either class D1 or D2 above that bottom class. See the <a href=\"https://isocpp.org/wiki/faq/multiple-inheritance#virtual-inheritance-where\" rel=\"nofollow noreferrer\">FAQ item</a> for a diagram and details.</p>\n\n<p>It is also used in <em>sister delegation</em>, a powerful feature (though not for the faint of heart). See <a href=\"https://isocpp.org/wiki/faq/multiple-inheritance#mi-delegate-to-sister\" rel=\"nofollow noreferrer\">this</a> FAQ.</p>\n\n<p>Also see Item 40 in Effective C++ 3rd edition (43 in 2nd edition).</p>\n" }, { "answer_id": 21607, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 10, "selected": true, "text": "<p>Virtual base classes, used in virtual inheritance, is a way of preventing multiple \"instances\" of a given class appearing in an inheritance hierarchy when using multiple inheritance.</p>\n\n<p>Consider the following scenario:</p>\n\n<pre><code>class A { public: void Foo() {} };\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\n</code></pre>\n\n<p>The above class hierarchy results in the \"dreaded diamond\" which looks like this:</p>\n\n<pre><code> A\n / \\\nB C\n \\ /\n D\n</code></pre>\n\n<p>An instance of D will be made up of B, which includes A, and C which also includes A. So you have two \"instances\" (for want of a better expression) of A.</p>\n\n<p>When you have this scenario, you have the possibility of ambiguity. What happens when you do this:</p>\n\n<pre><code>D d;\nd.Foo(); // is this B's Foo() or C's Foo() ??\n</code></pre>\n\n<p>Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.</p>\n\n<pre><code>class A { public: void Foo() {} };\nclass B : public virtual A {};\nclass C : public virtual A {};\nclass D : public B, public C {};\n</code></pre>\n\n<p>This means that there is only one \"instance\" of A included in the hierarchy. Hence</p>\n\n<pre><code>D d;\nd.Foo(); // no longer ambiguous\n</code></pre>\n\n<p>This is a mini summary. For more information, have a read of <a href=\"http://en.wikipedia.org/wiki/Virtual_inheritance\" rel=\"noreferrer\">this</a> and <a href=\"https://isocpp.org/wiki/faq/multiple-inheritance\" rel=\"noreferrer\">this</a>. A good example is also available <a href=\"http://www.learncpp.com/cpp-tutorial/118-virtual-base-classes/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 21612, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>A virtual base class is a class that\n cannot be instantiated : you cannot\n create direct object out of it.</p>\n</blockquote>\n\n<p>I think you are confusing two very different things. Virtual inheritance is not the same thing as an abstract class. Virtual inheritance modifies the behaviour of function calls; sometimes it resolves function calls that otherwise would be ambiguous, sometimes it defers function call handling to a class other than that one would expect in a non-virtual inheritance.</p>\n" }, { "answer_id": 21613, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 1, "selected": false, "text": "<p>You're being a little confusing. I dont' know if you're mixing up some concepts.</p>\n\n<p>You don't have a virtual base class in your OP. You just have a base class. </p>\n\n<p>You did virtual inheritance. This is usually used in multiple inheritance so that multiple derived classes use the members of the base class without reproducing them.</p>\n\n<p>A base class with a pure virtual function is not be instantiated. this requires the syntax that Paul gets at. It is typically used so that derived classes must define those functions. </p>\n\n<p>I don't want to explain any more about this because I don't totally get what you're asking. </p>\n" }, { "answer_id": 21616, "author": "bradtgmurray", "author_id": 1546, "author_profile": "https://Stackoverflow.com/users/1546", "pm_score": 0, "selected": false, "text": "<p>Virtual classes are <strong>not</strong> the same as virtual inheritance. Virtual classes you cannot instantiate, virtual inheritance is something else entirely.</p>\n\n<p>Wikipedia describes it better than I can. <a href=\"http://en.wikipedia.org/wiki/Virtual_inheritance\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Virtual_inheritance</a></p>\n" }, { "answer_id": 21629, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 3, "selected": false, "text": "<p>I'd like to add to OJ's kind clarifications.</p>\n\n<p>Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.</p>\n\n<p>Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:</p>\n\n<pre><code> B\n / \\\nD11 D12\n | |\nD21 D22\n \\ /\n DD\n</code></pre>\n\n<p>None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.</p>\n\n<p>Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.</p>\n" }, { "answer_id": 112474, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": false, "text": "<h2>About the memory layout</h2>\n<p>As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:</p>\n<pre><code> A\n / \\\nB C\n \\ /\n D\n</code></pre>\n<p>But in the memory layout, you have:</p>\n<pre><code>A A\n| |\nB C\n \\ /\n D\n</code></pre>\n<p>This explain why when call <code>D::foo()</code>, you have an ambiguity problem. But the <strong>real</strong> problem comes when you want to use a member variable of <code>A</code>. For example, let's say we have:</p>\n<pre><code>class A\n{\n public :\n foo() ;\n int m_iValue ;\n} ;\n</code></pre>\n<p>When you'll try to access <code>m_iValue</code> from <code>D</code>, the compiler will protest, because in the hierarchy, it'll see two <code>m_iValue</code>, not one. And if you modify one, say, <code>B::m_iValue</code> (that is the <code>A::m_iValue</code> parent of <code>B</code>), <code>C::m_iValue</code> won't be modified (that is the <code>A::m_iValue</code> parent of <code>C</code>).</p>\n<p>This is where virtual inheritance comes handy, as with it, you'll get back to a true diamond layout, with not only one <code>foo()</code> method only, but also one and only one <code>m_iValue</code>.</p>\n<h2>What could go wrong?</h2>\n<p>Imagine:</p>\n<ul>\n<li><code>A</code> has some basic feature.</li>\n<li><code>B</code> adds to it some kind of cool array of data (for example)</li>\n<li><code>C</code> adds to it some cool feature like an observer pattern (for example, on <code>m_iValue</code>).</li>\n<li><code>D</code> inherits from <code>B</code> and <code>C</code>, and thus from <code>A</code>.</li>\n</ul>\n<p>With normal inheritance, modifying <code>m_iValue</code> from <code>D</code> is ambiguous and this must be resolved. Even if it is, there are two <code>m_iValues</code> inside <code>D</code>, so you'd better remember that and update the two at the same time.</p>\n<p>With virtual inheritance, modifying <code>m_iValue</code> from <code>D</code> is ok... But... Let's say that you have <code>D</code>. Through its <code>C</code> interface, you attached an observer. And through its <code>B</code> interface, you update the cool array, which has the side effect of directly changing <code>m_iValue</code>...</p>\n<p>As the change of <code>m_iValue</code> is done directly (without using a virtual accessor method), the observer &quot;listening&quot; through <code>C</code> won't be called, because the code implementing the listening is in <code>C</code>, and <code>B</code> doesn't know about it...</p>\n<h2>Conclusion</h2>\n<p>If you're having a diamond in your hierarchy, it means that you have 95% probability to have done something wrong with said hierarchy.</p>\n" }, { "answer_id": 112722, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 3, "selected": false, "text": "<p>In addition to what has already been said about multiple and virtual inheritance(s), there is a very interesting article on Dr Dobb's Journal: <a href=\"http://www.ddj.com/cpp/184402074\" rel=\"noreferrer\">Multiple Inheritance Considered Useful</a></p>\n" }, { "answer_id": 991723, "author": "lenkite", "author_id": 120959, "author_profile": "https://Stackoverflow.com/users/120959", "pm_score": 5, "selected": false, "text": "<p>Explaining multiple-inheritance with virtual bases requires a knowledge of the C++ object model. And explaining the topic clearly is best done in an article and not in a comment box.</p>\n\n<p>The best, readable explanation I found that solved all my doubts on this subject was this article: <a href=\"https://web.archive.org/web/20160413064252/http://www.phpcompiler.org/articles/virtualinheritance.html\" rel=\"noreferrer\">http://www.phpcompiler.org/articles/virtualinheritance.html</a></p>\n\n<p>You really won't need to read anything else on the topic (unless you are a compiler writer) after reading that...</p>\n" }, { "answer_id": 41026159, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 2, "selected": false, "text": "<p><strong>Diamond inheritance runnable usage example</strong></p>\n<p>This example shows how to use a virtual base class in the typical scenario: to solve diamond inheritance problems.</p>\n<p>Consider the following working example:</p>\n<p>main.cpp</p>\n<pre><code>#include &lt;cassert&gt;\n\nclass A {\n public:\n A(){}\n A(int i) : i(i) {}\n int i;\n virtual int f() = 0;\n virtual int g() = 0;\n virtual int h() = 0;\n};\n\nclass B : public virtual A {\n public:\n B(int j) : j(j) {}\n int j;\n virtual int f() { return this-&gt;i + this-&gt;j; }\n};\n\nclass C : public virtual A {\n public:\n C(int k) : k(k) {}\n int k;\n virtual int g() { return this-&gt;i + this-&gt;k; }\n};\n\nclass D : public B, public C {\n public:\n D(int i, int j, int k) : A(i), B(j), C(k) {}\n virtual int h() { return this-&gt;i + this-&gt;j + this-&gt;k; }\n};\n\nint main() {\n D d = D(1, 2, 4);\n assert(d.f() == 3);\n assert(d.g() == 5);\n assert(d.h() == 7);\n}\n</code></pre>\n<p>Compile and run:</p>\n<pre><code>g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\n./main.out\n</code></pre>\n<p>If we remove the <code>virtual</code> into:</p>\n<pre><code>class B : public virtual A\n</code></pre>\n<p>we would get a wall of errors about GCC being unable to resolve D members and methods that were inherited twice via A:</p>\n<pre><code>main.cpp:27:7: warning: virtual base ‘A’ inaccessible in ‘D’ due to ambiguity [-Wextra]\n 27 | class D : public B, public C {\n | ^\nmain.cpp: In member function ‘virtual int D::h()’:\nmain.cpp:30:40: error: request for member ‘i’ is ambiguous\n 30 | virtual int h() { return this-&gt;i + this-&gt;j + this-&gt;k; }\n | ^\nmain.cpp:7:13: note: candidates are: ‘int A::i’\n 7 | int i;\n | ^\nmain.cpp:7:13: note: ‘int A::i’\nmain.cpp: In function ‘int main()’:\nmain.cpp:34:20: error: invalid cast to abstract class type ‘D’\n 34 | D d = D(1, 2, 4);\n | ^\nmain.cpp:27:7: note: because the following virtual functions are pure within ‘D’:\n 27 | class D : public B, public C {\n | ^\nmain.cpp:8:21: note: ‘virtual int A::f()’\n 8 | virtual int f() = 0;\n | ^\nmain.cpp:9:21: note: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\nmain.cpp:34:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’\n 34 | D d = D(1, 2, 4);\n | ^\nIn file included from /usr/include/c++/9/cassert:44,\n from main.cpp:1:\nmain.cpp:35:14: error: request for member ‘f’ is ambiguous\n 35 | assert(d.f() == 3);\n | ^\nmain.cpp:8:21: note: candidates are: ‘virtual int A::f()’\n 8 | virtual int f() = 0;\n | ^\nmain.cpp:17:21: note: ‘virtual int B::f()’\n 17 | virtual int f() { return this-&gt;i + this-&gt;j; }\n | ^\nIn file included from /usr/include/c++/9/cassert:44,\n from main.cpp:1:\nmain.cpp:36:14: error: request for member ‘g’ is ambiguous\n 36 | assert(d.g() == 5);\n | ^\nmain.cpp:9:21: note: candidates are: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\nmain.cpp:24:21: note: ‘virtual int C::g()’\n 24 | virtual int g() { return this-&gt;i + this-&gt;k; }\n | ^\nmain.cpp:9:21: note: ‘virtual int A::g()’\n 9 | virtual int g() = 0;\n | ^\n./main.out\n</code></pre>\n<p>Tested on GCC 9.3.0, Ubuntu 20.04.</p>\n" }, { "answer_id": 62281777, "author": "Lewis Kelsey", "author_id": 7194773, "author_profile": "https://Stackoverflow.com/users/7194773", "pm_score": 2, "selected": false, "text": "<h2>Regular Inheritance</h2>\n<img src=\"https://i.stack.imgur.com/7ski1.png\" width=\"200\">\n<p>With typical 3 level non-diamond non-virtual-inheritance inheritance, when you instantiate a new most-derived-object, <code>new</code> is called and the size required for the object on the heap is resolved from the class type by the compiler and passed to new.</p>\n<p><code>new</code> has a signature:</p>\n<pre><code>_GLIBCXX_WEAK_DEFINITION void *\noperator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)\n</code></pre>\n<p>And makes a call to <code>malloc</code>, returning the void pointer</p>\n<p>This address is then passed to the constructor of the most derived object, which will immediately call the middle constructor and then the middle constructor will immediately call the base constructor. The base then stores a pointer to its virtual table at the start of the object and then its attributes after it. This then returns to the middle constructor which will store its virtual table pointer at the same location and then its attributes after the attributes that would have been stored by the base constructor. It then returns to the most derived constructor, which stores a pointer to its virtual table at the same location and and then stores its attributes after the attributes that would have been stored by the middle constructor.</p>\n<p>Because the virtual table pointer is overwritten, the virtual table pointer ends up always being the one of the most derived class. Virtualness propagates towards the most derived class so if a function is virtual in the middle class, it will be virtual in the most derived class but not the base class. If you polymorphically cast an instance of the most derived class to a pointer to the base class then the compiler will not resolve this to an indirect call to the virtual table and instead will call the function directly <code>A::function()</code>. If a function is virtual for the type you have cast it to then it will resolve to a call into the virtual table which will always be that of the most derived class. If it is not virtual for that type then it will just call <code>Type::function()</code> and pass the object pointer to it, cast to Type.</p>\n<p>Actually when I say pointer to its virtual table, it's actually always an offset of 16 into the virtual table.</p>\n<pre><code>vtable for Base:\n .quad 0\n .quad typeinfo for Base\n .quad Base::CommonFunction()\n .quad Base::VirtualFunction()\n\npointer is typically to the first function i.e. \n\n mov edx, OFFSET FLAT:vtable for Base+16\n</code></pre>\n<p><code>virtual</code> is not required again in more-derived classes if it is virtual in a less-derived class because it propagates downwards in the direction of the most derived class. But it can be used to show that the function is indeed a virtual function, without having to check the classes it inherits's type definitions. When a function is declared virtual, from that point on, only the last implementation in the inheritance chain is used, but before that, it can still be used non-virtually if the object is cast to a type of a class before that in the inheritance chain that defines that method. It can be defined non-virtually in multiple classes before it in the chain before the virtualhood begins for a method of that name and signature, and they will use their own methods when referenced (and all classes after that definition in the chain will use that definition if they do not have their own definition, as opposed to virtual, which always uses the final definition). When a method is declared virtual, it must be implemented in that class or a more derived class in the inheritance chain for the full object that was constructed in order to be used.</p>\n<p><code>override</code> is another compiler guard that says that this function is overriding something and if it isn't then throw a compiler error.</p>\n<p><code>= 0</code> means that this is an abstract function</p>\n<p><code>final</code> prevents a virtual function from being implemented again in a more derived class and will make sure that the virtual table of the most derived class contains the final function of that class.</p>\n<p><code>= default</code> makes it explicit in documentation that the compiler will use the default implementation</p>\n<p><code>= delete</code> give a compiler error if a call to this is attempted</p>\n<p>If you call a non-virtual function, it will resolve to the correct method definition without going through the virtual table. If you call a virtual-function that has its final definition in an inherited class then it will use its virtual table and will pass the subobject to it automatically if you don't cast the object pointer to that type when calling the method. If you call a virtual function defined in the most derived class on a pointer of that type then it will use its virtual table, which will be the one at the start of the object. If you call it on a pointer of an inherited type and the function is also virtual in that class then it will use the vtable pointer of that subobject, which in the case of the first subobject will be the same pointer as the most derived class, which will not contain a thunk as the address of the object and the subobject are the same, and therefore it's just as simple as the method automatically recasting this pointer, but in the case of a 2nd sub object, its vtable will contain a non-virtual thunk to convert the pointer of the object of inherited type to the type the implementation in the most derived class expects, which is the full object, and therefore offsets the subobject pointer to point to the full object, and in the case of base subobject, will require a virtual thunk to offset the pointer to the base to the full object, such that it can be recast by the method hidden object parameter type.</p>\n<p>Using the object with a reference operator and not through a pointer (dereference operator) breaks polymorphism and will treat virtual methods as regular methods. This is because polymorphic casting on non-pointer types can't occur due to slicing.</p>\n<h2>Virtual Inheritance</h2>\n<p>Consider</p>\n<pre><code>class Base\n {\n int a = 1;\n int b = 2;\n public:\n void virtual CommonFunction(){} ; //define empty method body\n void virtual VirtualFunction(){} ;\n };\n\n\nclass DerivedClass1: virtual public Base\n {\n int c = 3;\n public:\n void virtual DerivedCommonFunction(){} ;\n void virtual VirtualFunction(){} ;\n };\n \n class DerivedClass2 : virtual public Base\n {\n int d = 4;\n public:\n //void virtual DerivedCommonFunction(){} ; \n void virtual VirtualFunction(){} ;\n void virtual DerivedCommonFunction2(){} ;\n };\n\nclass DerivedDerivedClass : public DerivedClass1, public DerivedClass2\n {\n int e = 5;\n public:\n void virtual DerivedDerivedCommonFunction(){} ;\n void virtual VirtualFunction(){} ;\n };\n \n int main () {\n DerivedDerivedClass* d = new DerivedDerivedClass;\n d-&gt;VirtualFunction();\n d-&gt;DerivedCommonFunction();\n d-&gt;DerivedCommonFunction2();\n d-&gt;DerivedDerivedCommonFunction();\n ((DerivedClass2*)d)-&gt;DerivedCommonFunction2();\n ((Base*)d)-&gt;VirtualFunction();\n }\n</code></pre>\n<p>Without virtually inheriting the bass class you will get an object that looks like this:</p>\n<img src=\"https://i.stack.imgur.com/Z00no.png\" width=\"200\">\n<p>Instead of this:</p>\n<img src=\"https://i.stack.imgur.com/XifNw.png\" width=\"200\">\n<p>I.e. there will be 2 base objects.</p>\n<p>In the virtual diamond inheritance situation above, after <code>new</code> is called, it passes the address of the allocated space for the object to the most derived constructor <code>DerivedDerivedClass::DerivedDerivedClass()</code>, which calls <code>Base::Base()</code> first, which writes its vtable in the base's dedicated subobject, it then <code>DerivedDerivedClass::DerivedDerivedClass()</code> calls <code>DerivedClass1::DerivedClass1()</code>, which writes its virtual table pointer to its subobject as well as overwriting the base subobject's pointer at the end of the object by consulting the passed VTT, and then calls <code>DerivedClass1::DerivedClass1()</code> to do the same, and finally <code>DerivedDerivedClass::DerivedDerivedClass()</code> overwrites all 3 pointers with its virtual table pointer for that inherited class. This is instead of (as illustrated in the 1st image above) <code>DerivedDerivedClass::DerivedDerivedClass()</code> calling <code>DerivedClass1::DerivedClass1()</code> and that calling <code>Base::Base()</code> (which overwrites the virtual pointer), returning, offsetting the address to the next subobject, calling <code>DerivedClass2::DerivedClass2()</code> and then that also calling <code>Base::Base()</code>, overwriting that virtual pointer, returning and then <code>DerivedDerivedClass</code> constructor overwriting both virtual pointers with its virtual table pointer (in this instance, the virtual table of the most derived constructor contains 2 subtables instead of 3).</p>\n<p>The following is all compiled in debug mode -O0 so there will be redundant assembly</p>\n<pre><code>main:\n.LFB8:\n push rbp\n mov rbp, rsp\n push rbx\n sub rsp, 24\n mov edi, 48 //pass size to new\n call operator new(unsigned long) //call new\n mov rbx, rax //move the address of the allocation to rbx\n mov rdi, rbx //move it to rdi i.e. pass to the call\n call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor] //construct on this address\n mov QWORD PTR [rbp-24], rbx //store the address of the object on the stack as the d pointer variable on -O0, will be optimised off on -Ofast if the address of the pointer itself isn't taken in the code, because this address does not need to be on the stack, it can just be passed in a register to the subsequent methods\n</code></pre>\n<p>Parenthetically, if the code were <code>DerivedDerivedClass d = DerivedDerivedClass()</code>, the <code>main</code> function would look like this:</p>\n<pre><code>main:\n push rbp\n mov rbp, rsp\n sub rsp, 48 // make room for and zero 48 bytes on the stack for the 48 byte object, no extra padding required as the frame is 64 bytes with `rbp` and return address of the function it calls (no stack params are passed to any function it calls), hence rsp will be aligned by 16 assuming it was aligned at the start of this frame\n mov QWORD PTR [rbp-48], 0\n mov QWORD PTR [rbp-40], 0\n mov QWORD PTR [rbp-32], 0\n mov QWORD PTR [rbp-24], 0\n mov QWORD PTR [rbp-16], 0\n mov QWORD PTR [rbp-8], 0\n lea rax, [rbp-48] // load the address of the cleared 48 bytes\n mov rdi, rax // pass the address as a pointer to the 48 bytes cleared as the first parameter to the constructor\n call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]\n //address is not stored on the stack because the object is used directly -- there is no pointer variable -- d refers to the object on the stack as opposed to being a pointer\n</code></pre>\n<p>Moving back to the original example, the <code>DerivedDerivedClass</code> constructor:</p>\n<pre><code>DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]:\n.LFB20:\n push rbp\n mov rbp, rsp\n sub rsp, 16\n mov QWORD PTR [rbp-8], rdi\n.LBB5:\n mov rax, QWORD PTR [rbp-8] // object address now in rax \n add rax, 32 //increment address by 32\n mov rdi, rax // move object address+32 to rdi i.e. pass to call\n call Base::Base() [base object constructor]\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+8 //move address of VTT+8 to edx\n mov rsi, rdx //pass VTT+8 address as 2nd parameter \n mov rdi, rax //object address as first (DerivedClass1 subobject)\n call DerivedClass1::DerivedClass1() [base object constructor]\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n add rax, 16 //increment object address by 16\n mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+24 //store address of VTT+24 in edx\n mov rsi, rdx //pass address of VTT+24 as second parameter\n mov rdi, rax //address of DerivedClass2 subobject as first\n call DerivedClass2::DerivedClass2() [base object constructor]\n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+24 //move this to edx\n mov rax, QWORD PTR [rbp-8] // object address now in rax\n mov QWORD PTR [rax], rdx. //store address of vtable for DerivedDerivedClass+24 at the start of the object\n mov rax, QWORD PTR [rbp-8] // object address now in rax\n add rax, 32 // increment object address by 32\n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+120 //move this to edx\n mov QWORD PTR [rax], rdx //store vtable for DerivedDerivedClass+120 at object+32 (Base) \n mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+72 //store this in edx\n mov rax, QWORD PTR [rbp-8] //move object address to rax\n mov QWORD PTR [rax+16], rdx //store vtable for DerivedDerivedClass+72 at object+16 (DerivedClass2)\n mov rax, QWORD PTR [rbp-8]\n mov DWORD PTR [rax+28], 5 // stores e = 5 in the object\n.LBE5:\n nop\n leave\n ret\n</code></pre>\n<p>The <code>DerivedDerivedClass</code> constructor calls <code>Base::Base()</code> with a pointer to the object offset 32. Base stores a pointer to its virtual table at the address it receives and its members after it.</p>\n<pre><code>Base::Base() [base object constructor]:\n.LFB11:\n push rbp\n mov rbp, rsp\n mov QWORD PTR [rbp-8], rdi //stores address of object on stack (-O0)\n.LBB2:\n mov edx, OFFSET FLAT:vtable for Base+16 //puts vtable for Base+16 in edx\n mov rax, QWORD PTR [rbp-8] //copies address of object from stack to rax\n mov QWORD PTR [rax], rdx //stores it address of object\n mov rax, QWORD PTR [rbp-8] //copies address of object on stack to rax again\n mov DWORD PTR [rax+8], 1 //stores a = 1 in the object\n mov rax, QWORD PTR [rbp-8] //junk from -O0\n mov DWORD PTR [rax+12], 2 //stores b = 2 in the object\n.LBE2:\n nop\n pop rbp\n ret\n</code></pre>\n<p><code>DerivedDerivedClass::DerivedDerivedClass()</code> then calls <code>DerivedClass1::DerivedClass1()</code> with a pointer to the object offset 0 and also passes the address of <code>VTT for DerivedDerivedClass+8</code></p>\n<pre><code>DerivedClass1::DerivedClass1() [base object constructor]:\n.LFB14:\n push rbp\n mov rbp, rsp\n mov QWORD PTR [rbp-8], rdi //address of object\n mov QWORD PTR [rbp-16], rsi //address of VTT+8\n.LBB3:\n mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax\n mov rdx, QWORD PTR [rax] //address of DerivedClass1-in-DerivedDerivedClass+24 now in rdx\n mov rax, QWORD PTR [rbp-8] //address of object now in rax\n mov QWORD PTR [rax], rdx //store address of DerivedClass1-in-.. in the object\n mov rax, QWORD PTR [rbp-8] // address of object now in rax\n mov rax, QWORD PTR [rax] //address of DerivedClass1-in.. now implicitly in rax\n sub rax, 24 //address of DerivedClass1-in-DerivedDerivedClass+0 now in rax\n mov rax, QWORD PTR [rax] //value of 32 now in rax\n mov rdx, rax // now in rdx\n mov rax, QWORD PTR [rbp-8] //address of object now in rax\n add rdx, rax //address of object+32 now in rdx\n mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax\n mov rax, QWORD PTR [rax+8] //derference VTT+8+8; address of DerivedClass1-in-DerivedDerivedClass+72 (Base::CommonFunction()) now in rax\n mov QWORD PTR [rdx], rax //store at address object+32 (offset to Base)\n mov rax, QWORD PTR [rbp-8] //store address of object in rax, return\n mov DWORD PTR [rax+8], 3 //store its attribute c = 3 in the object\n.LBE3:\n nop\n pop rbp\n ret\n</code></pre>\n<pre><code>VTT for DerivedDerivedClass:\n .quad vtable for DerivedDerivedClass+24\n .quad construction vtable for DerivedClass1-in-DerivedDerivedClass+24 //(DerivedClass1 uses this to write its vtable pointer)\n .quad construction vtable for DerivedClass1-in-DerivedDerivedClass+72 //(DerivedClass1 uses this to overwrite the base vtable pointer)\n .quad construction vtable for DerivedClass2-in-DerivedDerivedClass+24\n .quad construction vtable for DerivedClass2-in-DerivedDerivedClass+72\n .quad vtable for DerivedDerivedClass+120 // DerivedDerivedClass supposed to use this to overwrite Bases's vtable pointer\n .quad vtable for DerivedDerivedClass+72 // DerivedDerivedClass supposed to use this to overwrite DerivedClass2's vtable pointer\n//although DerivedDerivedClass uses vtable for DerivedDerivedClass+72 and DerivedDerivedClass+120 directly to overwrite them instead of going through the VTT\n\nconstruction vtable for DerivedClass1-in-DerivedDerivedClass:\n .quad 32\n .quad 0\n .quad typeinfo for DerivedClass1\n .quad DerivedClass1::DerivedCommonFunction()\n .quad DerivedClass1::VirtualFunction()\n .quad -32\n .quad 0\n .quad -32\n .quad typeinfo for DerivedClass1\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedClass1::VirtualFunction()\nconstruction vtable for DerivedClass2-in-DerivedDerivedClass:\n .quad 16\n .quad 0\n .quad typeinfo for DerivedClass2\n .quad DerivedClass2::VirtualFunction()\n .quad DerivedClass2::DerivedCommonFunction2()\n .quad -16\n .quad 0\n .quad -16\n .quad typeinfo for DerivedClass2\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedClass2::VirtualFunction()\nvtable for DerivedDerivedClass:\n .quad 32\n .quad 0\n .quad typeinfo for DerivedDerivedClass\n .quad DerivedClass1::DerivedCommonFunction()\n .quad DerivedDerivedClass::VirtualFunction()\n .quad DerivedDerivedClass::DerivedDerivedCommonFunction()\n .quad 16\n .quad -16\n .quad typeinfo for DerivedDerivedClass\n .quad non-virtual thunk to DerivedDerivedClass::VirtualFunction()\n .quad DerivedClass2::DerivedCommonFunction2()\n .quad -32\n .quad 0\n .quad -32\n .quad typeinfo for DerivedDerivedClass\n .quad Base::CommonFunction()\n .quad virtual thunk to DerivedDerivedClass::VirtualFunction()\n\nvirtual thunk to DerivedClass1::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK0\nvirtual thunk to DerivedClass2::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK1\nvirtual thunk to DerivedDerivedClass::VirtualFunction():\n mov r10, QWORD PTR [rdi]\n add rdi, QWORD PTR [r10-32]\n jmp .LTHUNK2\nnon-virtual thunk to DerivedDerivedClass::VirtualFunction():\n sub rdi, 16\n jmp .LTHUNK3\n\n .set .LTHUNK0,DerivedClass1::VirtualFunction()\n .set .LTHUNK1,DerivedClass2::VirtualFunction()\n .set .LTHUNK2,DerivedDerivedClass::VirtualFunction()\n .set .LTHUNK3,DerivedDerivedClass::VirtualFunction()\n\n\n</code></pre>\n<p>Each inherited class has its own construction virtual table and the most derived class, <code>DerivedDerivedClass</code>, has a virtual table with a subtable for each, and it uses the pointer to the subtable to overwrite construction vtable pointer that the inherited class's constructor stored for each subobject. Each virtual method that needs a thunk (virtual thunk offsets the object pointer from the base to the start of the object and a non-virtual thunk offsets the object pointer from an inherited class's object that isn't the base object to the start of the whole object of the type <code>DerivedDerivedClass</code>). The <code>DerivedDerivedClass</code> constructor also uses a virtual table table (VTT) as a serial list of all the virtual table pointers that it needs to use and passes it to each constructor (along with the subobject address that the constructor is for), which they use to overwrite their and the base's vtable pointer.</p>\n<p><code>DerivedDerivedClass::DerivedDerivedClass()</code> then passes the address of the object+16 and the address of VTT for <code>DerivedDerivedClass+24</code> to <code>DerivedClass2::DerivedClass2()</code> whose assembly is identical to <code>DerivedClass1::DerivedClass1()</code> except for the line <code>mov DWORD PTR [rax+8], 3</code> which obviously has a 4 instead of 3 for <code>d = 4</code>.</p>\n<p>After this, it replaces all 3 virtual table pointers in the object with pointers to offsets in <code>DerivedDerivedClass</code>'s vtable to the representation for that class.</p>\n<p>The call to <code>d-&gt;VirtualFunction()</code> in <code>main</code>:</p>\n<pre><code> mov rax, QWORD PTR [rbp-24] //store pointer to object (and hence vtable pointer) in rax\n mov rax, QWORD PTR [rax] //dereference this pointer to vtable pointer and store virtual table pointer in rax\n add rax, 8 // add 8 to the pointer to get the 2nd function pointer in the table\n mov rdx, QWORD PTR [rax] //dereference this pointer to get the address of the method to call\n mov rax, QWORD PTR [rbp-24] //restore pointer to object in rax (-O0 is inefficient, yes)\n mov rdi, rax //pass object to the method\n call rdx\n</code></pre>\n<p><code>d-&gt;DerivedCommonFunction();</code>:</p>\n<pre><code> mov rax, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rdx]\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax //pass object to method\n call rdx //call the first function in the table\n</code></pre>\n<p><code>d-&gt;DerivedCommonFunction2();</code>:</p>\n<pre><code> mov rax, QWORD PTR [rbp-24] //get the object pointer\n lea rdx, [rax+16] //get the address of the 2nd subobject in the object\n mov rax, QWORD PTR [rbp-24] //get the object pointer\n mov rax, QWORD PTR [rax+16] // get the vtable pointer of the 2nd subobject\n add rax, 8 //call the 2nd function in this table\n mov rax, QWORD PTR [rax] //get the address of the 2nd function\n mov rdi, rdx //call it and pass the 2nd subobject to it\n call rax\n</code></pre>\n<p><code>d-&gt;DerivedDerivedCommonFunction();</code>:</p>\n<pre><code> mov rax, QWORD PTR [rbp-24] //get the object pointer\n mov rax, QWORD PTR [rax] //get the vtable pointer\n add rax, 16 //get the 3rd function in the first virtual table (which is where virtual functions that that first appear in the most derived class go, because they belong to the full object which uses the virtual table pointer at the start of the object)\n mov rdx, QWORD PTR [rax] //get the address of the object\n mov rax, QWORD PTR [rbp-24]\n mov rdi, rax //call it and pass the whole object to it\n call rdx\n</code></pre>\n<p><code>((DerivedClass2*)d)-&gt;DerivedCommonFunction2();</code>:</p>\n<pre><code>//it casts the object to its subobject and calls the corresponding method in its virtual table, which will be a non-virtual thunk\n\n cmp QWORD PTR [rbp-24], 0\n je .L14\n mov rax, QWORD PTR [rbp-24]\n add rax, 16\n jmp .L15\n.L14:\n mov eax, 0\n.L15:\n cmp QWORD PTR [rbp-24], 0\n cmp QWORD PTR [rbp-24], 0\n je .L18\n mov rdx, QWORD PTR [rbp-24]\n add rdx, 16\n jmp .L19\n.L18:\n mov edx, 0\n.L19:\n mov rdx, QWORD PTR [rdx]\n add rdx, 8\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax\n call rdx\n</code></pre>\n<p><code>((Base*)d)-&gt;VirtualFunction();</code>:</p>\n<pre><code>//it casts the object to its subobject and calls the corresponding function in its virtual table, which will be a virtual thunk\n\n cmp QWORD PTR [rbp-24], 0\n je .L20\n mov rax, QWORD PTR [rbp-24]\n mov rax, QWORD PTR [rax]\n sub rax, 24\n mov rax, QWORD PTR [rax]\n mov rdx, rax\n mov rax, QWORD PTR [rbp-24]\n add rax, rdx\n jmp .L21\n.L20:\n mov eax, 0\n.L21:\n cmp QWORD PTR [rbp-24], 0\n cmp QWORD PTR [rbp-24], 0\n je .L24\n mov rdx, QWORD PTR [rbp-24]\n mov rdx, QWORD PTR [rdx]\n sub rdx, 24\n mov rdx, QWORD PTR [rdx]\n mov rcx, rdx\n mov rdx, QWORD PTR [rbp-24]\n add rdx, rcx\n jmp .L25\n.L24:\n mov edx, 0\n.L25:\n mov rdx, QWORD PTR [rdx]\n add rdx, 8\n mov rdx, QWORD PTR [rdx]\n mov rdi, rax\n call rdx\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
I want to know what a "*virtual base class*" is and what it means. Let me show an example: ``` class Foo { public: void DoSomething() { /* ... */ } }; class Bar : public virtual Foo { public: void DoSpecific() { /* ... */ } }; ```
Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance. Consider the following scenario: ``` class A { public: void Foo() {} }; class B : public A {}; class C : public A {}; class D : public B, public C {}; ``` The above class hierarchy results in the "dreaded diamond" which looks like this: ``` A / \ B C \ / D ``` An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A. When you have this scenario, you have the possibility of ambiguity. What happens when you do this: ``` D d; d.Foo(); // is this B's Foo() or C's Foo() ?? ``` Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance. ``` class A { public: void Foo() {} }; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; ``` This means that there is only one "instance" of A included in the hierarchy. Hence ``` D d; d.Foo(); // no longer ambiguous ``` This is a mini summary. For more information, have a read of [this](http://en.wikipedia.org/wiki/Virtual_inheritance) and [this](https://isocpp.org/wiki/faq/multiple-inheritance). A good example is also available [here](http://www.learncpp.com/cpp-tutorial/118-virtual-base-classes/).
21,564
<p>I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:</p> <pre><code>cat somefile.txt | prepend-timestamp </code></pre> <p>(Before you answer sed, I tried this:</p> <pre><code>cat somefile.txt | sed "s/^/`date`/" </code></pre> <p>But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)</p>
[ { "answer_id": 21602, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 5, "selected": false, "text": "<p>How about this?</p>\n\n<pre><code>cat somefile.txt | perl -pne 'print scalar(localtime()), \" \";'\n</code></pre>\n\n<p>Judging from your desire to get live timestamps, maybe you want to do live updating on a log file or something? Maybe</p>\n\n<pre><code>tail -f /path/to/log | perl -pne 'print scalar(localtime()), \" \";' &gt; /path/to/log-with-timestamps\n</code></pre>\n" }, { "answer_id": 21611, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": -1, "selected": false, "text": "<p>If the value you are prepending is the same on every line, fire up emacs with the file, then:</p>\n\n<p><kbd>Ctrl</kbd> + <kbd>&lt;space&gt;</kbd></p>\n\n<p>at the beginning of the of the file (to mark that spot), then scroll down to the beginning of the last line (Alt + &gt; will go to the end of file... which probably will involve the Shift key too, then Ctrl + a to go to the beginning of that line) and:</p>\n\n<p><kbd>Ctrl</kbd> + <kbd>x</kbd> <kbd>r</kbd> <kbd>t</kbd></p>\n\n<p>Which is the command to insert at the rectangle you just specified (a rectangle of 0 width).</p>\n\n<p>2008-8-21 6:45PM &lt;enter&gt;</p>\n\n<p>Or whatever you want to prepend... then you will see that text prepended to every line within the 0 width rectangle.</p>\n\n<p>UPDATE: I just realized you don't want the SAME date, so this won't work... though you may be able to do this in emacs with a slightly more complicated custom macro, but still, this kind of rectangle editing is pretty nice to know about...</p>\n" }, { "answer_id": 21614, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "<p>I'm not an Unix guy, but I think you can use</p>\n\n<pre><code>gawk '{print strftime(\"%d/%m/%y\",systime()) $0 }' &lt; somefile.txt\n</code></pre>\n" }, { "answer_id": 21620, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 9, "selected": true, "text": "<p>Could try using <code>awk</code>:</p>\n\n<pre><code>&lt;command&gt; | awk '{ print strftime(\"%Y-%m-%d %H:%M:%S\"), $0; fflush(); }'\n</code></pre>\n\n<p>You may need to make sure that <code>&lt;command&gt;</code> produces line buffered output, i.e. it flushes its output stream after each line; the timestamp <code>awk</code> adds will be the time that the end of the line appeared on its input pipe.</p>\n\n<p>If awk shows errors, then try <code>gawk</code> instead.</p>\n" }, { "answer_id": 21907, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "<p>Kieron's answer is the best one so far. If you have problems because the first program is buffering its out you can use the unbuffer program:</p>\n\n<pre><code>unbuffer &lt;command&gt; | awk '{ print strftime(\"%Y-%m-%d %H:%M:%S\"), $0; }'\n</code></pre>\n\n<p>It's installed by default on most linux systems. If you need to build it yourself it is part of the expect package</p>\n\n<p><a href=\"http://expect.nist.gov\" rel=\"noreferrer\">http://expect.nist.gov</a></p>\n" }, { "answer_id": 21909, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://jeroen.a-eskwadraat.nl/sw/annotate/annotate\" rel=\"noreferrer\">annotate</a>, available via that link or as <code>annotate-output</code> in the Debian <code>devscripts</code> package.</p>\n\n<pre><code>$ echo -e \"a\\nb\\nc\" &gt; lines\n$ annotate-output cat lines\n17:00:47 I: Started cat lines\n17:00:47 O: a\n17:00:47 O: b\n17:00:47 O: c\n17:00:47 I: Finished with exitcode 0\n</code></pre>\n" }, { "answer_id": 22441, "author": "caerwyn", "author_id": 2406, "author_profile": "https://Stackoverflow.com/users/2406", "pm_score": 3, "selected": false, "text": "<p>Use the read(1) command to read one line at a time from standard input, then output the line prepended with the date in the format of your choosing using date(1).</p>\n\n<pre><code>$ cat timestamp\n#!/bin/sh\nwhile read line\ndo\n echo `date` $line\ndone\n$ cat somefile.txt | ./timestamp\n</code></pre>\n" }, { "answer_id": 436536, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>#! /bin/sh\nunbuffer \"$@\" | perl -e '\nuse Time::HiRes (gettimeofday);\nwhile(&lt;&gt;) {\n ($s,$ms) = gettimeofday();\n print $s . \".\" . $ms . \" \" . $_;\n}'\n</code></pre>\n" }, { "answer_id": 5158624, "author": "ElGringoGeek", "author_id": 639872, "author_profile": "https://Stackoverflow.com/users/639872", "pm_score": 2, "selected": false, "text": "<p>Here's my awk solution (from a Windows/XP system with MKS Tools installed in the C:\\bin directory). It is designed to add the current date and time in the form mm/dd hh:mm to the beginning of each line having fetched that timestamp from the system as each line is read. You could, of course, use the BEGIN pattern to fetch the timestamp once and add that timestamp to each record (all the same). I did this to tag a log file that was being generated to stdout with the timestamp at the time the log message was generated.</p>\n\n<p><code>/\"pattern\"/ \"C\\:\\\\\\\\bin\\\\\\\\date '+%m/%d %R'\" | getline timestamp;</code><Br/>\n<code>print timestamp, $0;</code></p>\n\n<p>where \"pattern\" is a string or regex (without the quotes) to be matched in the input line, and is optional if you wish to match all input lines.</p>\n\n<p>This should work on Linux/UNIX systems as well, just get rid of the C\\:\\\\bin\\\\ leaving the line</p>\n\n<pre><code> \"date '+%m/%d %R'\" | getline timestamp;\n</code></pre>\n\n<p>This, of course, assumes that the command \"date\" gets you to the standard Linux/UNIX date display/set command without specific path information (that is, your environment PATH variable is correctly configured).</p>\n" }, { "answer_id": 9613514, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 4, "selected": false, "text": "<p>Just gonna throw this out there: there are a pair of utilities in <a href=\"http://cr.yp.to/daemontools.html\">daemontools</a> called <a href=\"http://cr.yp.to/daemontools/tai64n.html\">tai64n</a> and <a href=\"http://cr.yp.to/daemontools/tai64nlocal.html\">tai64nlocal</a> that are made for prepending timestamps to log messages.</p>\n\n<p>Example:</p>\n\n<pre><code>cat file | tai64n | tai64nlocal\n</code></pre>\n" }, { "answer_id": 9813614, "author": "Mark McKinstry", "author_id": 712655, "author_profile": "https://Stackoverflow.com/users/712655", "pm_score": 8, "selected": false, "text": "<p><code>ts</code> from <a href=\"http://kitenet.net/~joey/code/moreutils/\" rel=\"noreferrer\">moreutils</a> will prepend a timestamp to every line of input you give it. You can format it using strftime too.</p>\n\n<pre><code>$ echo 'foo bar baz' | ts\nMar 21 18:07:28 foo bar baz\n$ echo 'blah blah blah' | ts '%F %T'\n2012-03-21 18:07:30 blah blah blah\n$ \n</code></pre>\n\n<p>To install it:</p>\n\n<pre><code>sudo apt-get install moreutils\n</code></pre>\n" }, { "answer_id": 18923989, "author": "crumplecrap", "author_id": 2800436, "author_profile": "https://Stackoverflow.com/users/2800436", "pm_score": 1, "selected": false, "text": "<p>caerwyn's answer can be run as a subroutine, which would prevent the new processes per line:</p>\n\n<pre><code>timestamp(){\n while read line\n do\n echo `date` $line\n done\n}\n\necho testing 123 |timestamp\n</code></pre>\n" }, { "answer_id": 19662206, "author": "Willem", "author_id": 604515, "author_profile": "https://Stackoverflow.com/users/604515", "pm_score": 5, "selected": false, "text": "<p>Distilling the given answers to the simplest one possible:</p>\n\n<pre><code>unbuffer $COMMAND | ts\n</code></pre>\n\n<p>On Ubuntu, they come from the expect-dev and moreutils packages.</p>\n\n<pre><code>sudo apt-get install expect-dev moreutils\n</code></pre>\n" }, { "answer_id": 27001032, "author": "orion elenzil", "author_id": 230851, "author_profile": "https://Stackoverflow.com/users/230851", "pm_score": 0, "selected": false, "text": "<p>doing it with <code>date</code> and <code>tr</code> and <code>xargs</code> on OSX:</p>\n\n<pre><code>alias predate=\"xargs -I{} sh -c 'date +\\\"%Y-%m-%d %H:%M:%S\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n&lt;command&gt; | predate\n</code></pre>\n\n<p>if you want milliseconds:</p>\n\n<pre><code>alias predate=\"xargs -I{} sh -c 'date +\\\"%Y-%m-%d %H:%M:%S.%3N\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n</code></pre>\n\n<p>but note that on OSX, date doesn't give you the %N option, so you'll need to install gdate (<code>brew install coreutils</code>) and so finally arrive at this:</p>\n\n<pre><code>alias predate=\"xargs -I{} sh -c 'gdate +\\\"%Y-%m-%d %H:%M:%S.%3N\\\" | tr \\\"\\n\\\" \\\" \\\"; echo \\\"{}\\\"'\"\n</code></pre>\n" }, { "answer_id": 33218664, "author": "Keymon", "author_id": 395686, "author_profile": "https://Stackoverflow.com/users/395686", "pm_score": 2, "selected": false, "text": "<p>Mixing some answers above from <a href=\"https://stackoverflow.com/users/179583/natevw\">natevw</a> and Frank Ch. Eigler.</p>\n\n<p>It has milliseconds, performs better than calling a external <code>date</code> command each time and perl can be found in most of the servers.</p>\n\n<pre><code>tail -f log | perl -pne '\n use Time::HiRes (gettimeofday);\n use POSIX qw(strftime);\n ($s,$ms) = gettimeofday();\n print strftime \"%Y-%m-%dT%H:%M:%S+$ms \", gmtime($s);\n '\n</code></pre>\n\n<p>Alternative version with flush and read in a loop:</p>\n\n<pre><code>tail -f log | perl -pne '\n use Time::HiRes (gettimeofday); use POSIX qw(strftime);\n $|=1;\n while(&lt;&gt;) {\n ($s,$ms) = gettimeofday();\n print strftime \"%Y-%m-%dT%H:%M:%S+$ms $_\", gmtime($s);\n }'\n</code></pre>\n" }, { "answer_id": 44746681, "author": "Momchil Atanasov", "author_id": 2852445, "author_profile": "https://Stackoverflow.com/users/2852445", "pm_score": 1, "selected": false, "text": "<p><strong>Disclaimer</strong>: the solution I am proposing is not a Unix built-in utility.</p>\n\n<p>I faced a similar problem a few days ago. I did not like the syntax and limitations of the solutions above, so I quickly put together a program in Go to do the job for me.</p>\n\n<p>You can check the tool here: <strong><a href=\"https://github.com/mokiat/preftime\" rel=\"nofollow noreferrer\">preftime</a></strong></p>\n\n<p>There are prebuilt executables for Linux, MacOS, and Windows in the <a href=\"https://github.com/mokiat/preftime/releases\" rel=\"nofollow noreferrer\">Releases</a> section of the GitHub project.</p>\n\n<p>The tool handles incomplete output lines and has (from my point of view) a more compact syntax.</p>\n\n<p><code>&lt;command&gt; | preftime</code></p>\n\n<p>It's not ideal, but I though I'd share it in case it helps someone.</p>\n" }, { "answer_id": 44786469, "author": "aleksandr barakin", "author_id": 4827341, "author_profile": "https://Stackoverflow.com/users/4827341", "pm_score": 2, "selected": false, "text": "<blockquote>\n<pre><code>$ cat somefile.txt | sed \"s/^/`date`/\"\n</code></pre>\n</blockquote>\n\n<p>you can do this (with <em>gnu/sed</em>):</p>\n\n<pre><code>$ some-command | sed \"x;s/.*/date +%T/e;G;s/\\n/ /g\"\n</code></pre>\n\n<p>example:</p>\n\n<pre><code>$ { echo 'line1'; sleep 2; echo 'line2'; } | sed \"x;s/.*/date +%T/e;G;s/\\n/ /g\"\n20:24:22 line1\n20:24:24 line2\n</code></pre>\n\n<p>of course, you can use other options of the program <em>date</em>. just replace <code>date +%T</code> with what you need.</p>\n" }, { "answer_id": 71806202, "author": "Lucas Wiman", "author_id": 303931, "author_profile": "https://Stackoverflow.com/users/303931", "pm_score": 1, "selected": false, "text": "<p>The other answers mostly work, but have some drawbacks. In particular:</p>\n<ol>\n<li>Many require installing a command not commonly found on linux systems, which may not be possible or convenient.</li>\n<li>Since they use pipes, they don't put timestamps on stderr, and lose the exit status.</li>\n<li>If you use multiple pipes for stderr and stdout, then some do not have atomic printing, leading to intermingled lines of output like <code>[timestamp] [timestamp] stdout line \\nstderr line</code></li>\n<li>Buffering can cause problems, and <code>unbuffer</code> requires an extra dependency.</li>\n</ol>\n<p>To solve (4), we can use <code>stdbuf -i0 -o0 -e0</code> which is generally available on most linux systems (see <a href=\"https://stackoverflow.com/questions/3465619/how-to-make-output-of-any-shell-command-unbuffered\">How to make output of any shell command unbuffered?</a>).</p>\n<p>To solve (3), you just need to be careful to print the entire line at a time.</p>\n<ul>\n<li>Bad: <code>ruby -pe 'print Time.now.strftime(\\&quot;[%Y-%m-%d %H:%M:%S] \\&quot;)'</code> (Prints the timestamp, then prints the contents of <code>$_</code>.)</li>\n<li>Good: <code>ruby -pe '\\$_ = Time.now.strftime(\\&quot;[%Y-%m-%d %H:%M:%S] \\&quot;) + \\$_'</code> (Alters <code>$_</code>, then prints it.)</li>\n</ul>\n<p>To solve (2), we need to use multiple pipes and save the exit status:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>alias tslines-pipe=&quot;stdbuf -i0 -o0 ruby -pe '\\$_ = Time.now.strftime(\\&quot;[%Y-%m-%d %H:%M:%S] \\&quot;) + \\$_'&quot;\nfunction tslines() (\n stdbuf -o0 -e0 &quot;$@&quot; 2&gt; &gt;(tslines-pipe) &gt; &gt;(tslines-pipe)\n status=&quot;$?&quot;\n exit $status\n)\n</code></pre>\n<p>Then you can run a command with <code>tslines some command --options</code>.</p>\n<p>This <em>almost</em> works, except sometimes one of the pipes takes slightly longer to exit and the <code>tslines</code> function has exited, so the next prompt has printed. For example, this command seems to print all the output after the prompt for the next line has appeared, which can be a bit confusing:</p>\n<pre><code>tslines bash -c '(for (( i=1; i&lt;=20; i++ )); do echo stderr 1&gt;&amp;2; echo stdout; done)'\n</code></pre>\n<p>There needs to be some coordination method between the two pipe processes and the tslines function. There are presumably many ways to do this. One way I found is to have the pipes send some lines to a pipe that the main function can listen to, and only exit <em>after</em> it's received data from both pipe handlers. Putting that together:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>alias tslines-pipe=&quot;stdbuf -i0 -o0 ruby -pe '\\$_ = Time.now.strftime(\\&quot;[%Y-%m-%d %H:%M:%S] \\&quot;) + \\$_'&quot;\nfunction tslines() (\n # Pick a random name for the pipe to prevent collisions.\n pipe=&quot;/tmp/pipe-$RANDOM&quot;\n \n # Ensure the pipe gets deleted when the method exits.\n trap &quot;rm -f $pipe&quot; EXIT\n\n # Create the pipe. See https://www.linuxjournal.com/content/using-named-pipes-fifos-bash\n mkfifo &quot;$pipe&quot;\n # echo will block until the pipe is read.\n stdbuf -o0 -e0 &quot;$@&quot; 2&gt; &gt;(tslines-pipe; echo &quot;done&quot; &gt;&gt; $pipe) &gt; &gt;(tslines-pipe; echo &quot;done&quot; &gt;&gt; $pipe)\n status=&quot;$?&quot;\n\n # Wait until we've received data from both pipe commands before exiting.\n linecount=0\n while [[ $linecount -lt 2 ]]; do\n read line\n if [[ &quot;$line&quot; == &quot;done&quot; ]]; then\n ((linecount++))\n fi\n done &lt; &quot;$pipe&quot;\n exit $status\n)\n</code></pre>\n<p>That synchronization mechanism feels a bit convoluted; hopefully there's a simpler way to do it.</p>\n" }, { "answer_id": 71810273, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 0, "selected": false, "text": "<p>No need to specify all the parameters in <code>strftime()</code> unless you really want to customize the outputting format :</p>\n<pre><code> echo &quot;abc 123 xyz\\njan 765 feb&quot; \\\n \\\n | gawk -Sbe 'BEGIN {_=strftime()&quot; &quot;} sub(&quot;^&quot;,_)'\n\n Sat Apr 9 13:14:53 EDT 2022 abc 123 xyz\n Sat Apr 9 13:14:53 EDT 2022 jan 765 feb\n</code></pre>\n<p>works the same if you have <code>mawk 1.3.4.</code> Even on <code>awk</code>-variants without the time features, a quick getline could emulate it :</p>\n<pre><code>echo &quot;abc 123 xyz\\njan 765 feb&quot; \\\n\\\n| mawk2 'BEGIN { (__=&quot;date&quot;)|getline _;\n close(__)\n _=_&quot; &quot; } sub(&quot;^&quot;,_)'\n \nSat Apr 9 13:19:38 EDT 2022 abc 123 xyz\nSat Apr 9 13:19:38 EDT 2022 jan 765 feb\n</code></pre>\n<p>If you wanna skip all that getline and BEGIN { }, then something like this :</p>\n<pre><code>mawk2 'sub(&quot;^&quot;,_&quot; &quot;)' \\_=&quot;$(date)&quot;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156/" ]
I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: ``` cat somefile.txt | prepend-timestamp ``` (Before you answer sed, I tried this: ``` cat somefile.txt | sed "s/^/`date`/" ``` But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)
Could try using `awk`: ``` <command> | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }' ``` You may need to make sure that `<command>` produces line buffered output, i.e. it flushes its output stream after each line; the timestamp `awk` adds will be the time that the end of the line appeared on its input pipe. If awk shows errors, then try `gawk` instead.
21,574
<p>I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?</p>
[ { "answer_id": 21621, "author": "Tim Sullivan", "author_id": 722, "author_profile": "https://Stackoverflow.com/users/722", "pm_score": 8, "selected": true, "text": "<p>Sam Ruby has a <a href=\"http://slideshow.rubyforge.org/ruby19.html\" rel=\"noreferrer\">cool slideshow that outline the differences</a>.</p>\n\n<p>In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful.</p>\n\n<h1>Ruby 1.9 - Major Features</h1>\n\n<ul>\n<li>Performance</li>\n<li>Threads/Fibers</li>\n<li>Encoding/Unicode</li>\n<li>gems is (mostly) built-in now</li>\n<li>if statements do not introduce scope in Ruby.</li>\n</ul>\n\n<h1>What's changed?</h1>\n\n<h2>Single character strings.</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; ?c\n=&gt; \"c\"\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; ?c\n=&gt; 99\n</code></pre>\n\n<hr>\n\n<h2>String index.</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; \"cat\"[1]\n=&gt; \"a\"\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; \"cat\"[1]\n=&gt; 97\n</code></pre>\n\n<hr>\n\n<h2>{\"a\",\"b\"} No Longer Supported</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):002:0&gt; {1,2}\nSyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; {1,2}\n=&gt; {1=&gt;2}\n</code></pre>\n\n<p><strong>Action:</strong> Convert to {1 => 2}</p>\n\n<hr>\n\n<h2><code>Array.to_s</code> Now Contains Punctuation</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; [1,2,3].to_s\n=&gt; \"[1, 2, 3]\"\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; [1,2,3].to_s\n=&gt; \"123\"\n</code></pre>\n\n<p><strong>Action:</strong> Use .join instead</p>\n\n<hr>\n\n<h2>Colon No Longer Valid In When Statements</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; case 'a'; when /\\w/: puts 'word'; end\nSyntaxError: (irb):1: syntax error, unexpected ':',\nexpecting keyword_then or ',' or ';' or '\\n'\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; case 'a'; when /\\w/: puts 'word'; end\nword\n</code></pre>\n\n<p><strong>Action:</strong> Use semicolon, then, or newline</p>\n\n<hr>\n\n<h2>Block Variables Now Shadow Local Variables</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; i=0; [1,2,3].each {|i|}; i\n=&gt; 0\nirb(main):002:0&gt; i=0; for i in [1,2,3]; end; i\n=&gt; 3\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; i=0; [1,2,3].each {|i|}; i\n=&gt; 3\n</code></pre>\n\n<hr>\n\n<h2><code>Hash.index</code> Deprecated</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; {1=&gt;2}.index(2)\n(irb):18: warning: Hash#index is deprecated; use Hash#key\n=&gt; 1\nirb(main):002:0&gt; {1=&gt;2}.key(2)\n=&gt; 1\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; {1=&gt;2}.index(2)\n=&gt; 1\n</code></pre>\n\n<p><strong>Action:</strong> Use Hash.key</p>\n\n<hr>\n\n<h2><code>Fixnum.to_sym</code> Now Gone</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; 5.to_sym\nNoMethodError: undefined method 'to_sym' for 5:Fixnum\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; 5.to_sym\n=&gt; nil\n</code></pre>\n\n<p>(Cont'd) Ruby 1.9</p>\n\n<pre><code># Find an argument value by name or index.\ndef [](index)\n lookup(index.to_sym)\nend\n</code></pre>\n\n<p>svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb</p>\n\n<hr>\n\n<h2>Hash Keys Now Unordered</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; {:a=&gt;\"a\", :c=&gt;\"c\", :b=&gt;\"b\"}\n=&gt; {:a=&gt;\"a\", :c=&gt;\"c\", :b=&gt;\"b\"}\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; {:a=&gt;\"a\", :c=&gt;\"c\", :b=&gt;\"b\"}\n=&gt; {:a=&gt;\"a\", :b=&gt;\"b\", :c=&gt;\"c\"}\n</code></pre>\n\n<p>Order is insertion order</p>\n\n<hr>\n\n<h2>Stricter Unicode Regular Expressions</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; /\\x80/u\nSyntaxError: (irb):2: invalid multibyte escape: /\\x80/\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; /\\x80/u\n=&gt; /\\x80/u\n</code></pre>\n\n<hr>\n\n<h2><code>tr</code> and <code>Regexp</code> Now Understand Unicode</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).\n gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).\n gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}\n</code></pre>\n\n<hr>\n\n<h2><code>pack</code> and <code>unpack</code></h2>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>def xchr(escape=true)\n n = XChar::CP1252[self] || self\n case n when *XChar::VALID\n XChar::PREDEFINED[n] or \n (n&gt;128 ? n.chr : (escape ? \"&amp;##{n};\" : [n].pack('U*')))\n else\n Builder::XChar::REPLACEMENT_CHAR\n end\nend\nunpack('U*').map {|n| n.xchr(escape)}.join\n</code></pre>\n\n<hr>\n\n<h2><code>BasicObject</code> More Brutal Than <code>BlankSlate</code></h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; class C &lt; BasicObject; def f; Math::PI; end; end; C.new.f\nNameError: uninitialized constant C::Math\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; require 'blankslate'\n=&gt; true\nirb(main):002:0&gt; class C &lt; BlankSlate; def f; Math::PI; end; end; C.new.f\n=&gt; 3.14159265358979\n</code></pre>\n\n<p><strong>Action:</strong> Use ::Math::PI</p>\n\n<hr>\n\n<p><s></p>\n\n<h2>Delegation Changes</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):002:0&gt; class C &lt; SimpleDelegator; end\n=&gt; nil\nirb(main):003:0&gt; C.new('').class\n=&gt; String\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):002:0&gt; class C &lt; SimpleDelegator; end\n=&gt; nil\nirb(main):003:0&gt; C.new('').class\n=&gt; C\nirb(main):004:0&gt;\n</code></pre>\n\n<p><a href=\"http://rubyforge.org/tracker/index.php?func=detail&amp;aid=17700&amp;group_id=426&amp;atid=1698\" rel=\"noreferrer\">Defect 17700</a>\n</s></p>\n\n<hr>\n\n<h2>Use of $KCODE Produces Warnings</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):004:1&gt; $KCODE = 'UTF8'\n(irb):4: warning: variable $KCODE is no longer effective; ignored\n=&gt; \"UTF8\"\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; $KCODE = 'UTF8'\n=&gt; \"UTF8\"\n</code></pre>\n\n<hr>\n\n<h2><code>instance_methods</code> Now an Array of Symbols</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; {}.methods.sort.last\n=&gt; :zip\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>irb(main):001:0&gt; {}.methods.sort.last\n=&gt; \"zip\"\n</code></pre>\n\n<p><strong>Action:</strong> Replace instance_methods.include? with method_defined?</p>\n\n<hr>\n\n<h2>Source File Encoding</h2>\n\n<h3>Basic</h3>\n\n<pre><code># coding: utf-8\n</code></pre>\n\n<h3>Emacs</h3>\n\n<pre><code># -*- encoding: utf-8 -*-\n</code></pre>\n\n<h3>Shebang</h3>\n\n<pre><code>#!/usr/local/rubybook/bin/ruby\n# encoding: utf-8\n</code></pre>\n\n<hr>\n\n<h2>Real Threading</h2>\n\n<ul>\n<li>Race Conditions</li>\n<li>Implicit Ordering Assumptions</li>\n<li>Test Code</li>\n</ul>\n\n<hr>\n\n<h1>What's New?</h1>\n\n<h2>Alternate Syntax for Symbol as Hash Keys</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>{a: b}\n\nredirect_to action: show\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>{:a =&gt; b}\n\nredirect_to :action =&gt; show\n</code></pre>\n\n<hr>\n\n<h2>Block Local Variables</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>[1,2].each {|value; t| t=value*value}\n</code></pre>\n\n<hr>\n\n<h2>Inject Methods</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>[1,2].inject(:+)\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>[1,2].inject {|a,b| a+b}\n</code></pre>\n\n<hr>\n\n<h2><code>to_enum</code></h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>short_enum = [1, 2, 3].to_enum\nlong_enum = ('a'..'z').to_enum\nloop do\n puts \"#{short_enum.next} #{long_enum.next}\"\nend\n</code></pre>\n\n<hr>\n\n<h2>No block? Enum!</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>e = [1,2,3].each\n</code></pre>\n\n<hr>\n\n<h2>Lambda Shorthand</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>p = -&gt; a,b,c {a+b+c}\nputs p.(1,2,3)\nputs p[1,2,3]\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>p = lambda {|a,b,c| a+b+c}\nputs p.call(1,2,3)\n</code></pre>\n\n<hr>\n\n<h2>Complex Numbers</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>Complex(3,4) == 3 + 4.im\n</code></pre>\n\n<hr>\n\n<h2>Decimal Is Still Not The Default</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>irb(main):001:0&gt; 1.2-1.1\n=&gt; 0.0999999999999999\n</code></pre>\n\n<hr>\n\n<h2>Regex “Properties”</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>/\\p{Space}/\n</code></pre>\n\n<p>Ruby 1.8.6</p>\n\n<pre><code>/[:space:]/\n</code></pre>\n\n<hr>\n\n<h2>Splat in Middle</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>def foo(first, *middle, last)\n\n(-&gt;a, *b, c {p a-c}).(*5.downto(1))\n</code></pre>\n\n<hr>\n\n<h2>Fibers</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>f = Fiber.new do\n a,b = 0,1\n Fiber.yield a\n Fiber.yield b\n loop do\n a,b = b,a+b\n Fiber.yield b\n end\nend\n10.times {puts f.resume}\n</code></pre>\n\n<hr>\n\n<h2>Break Values</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>match =\n while line = gets\n next if line =~ /^#/\n break line if line.find('ruby')\n end\n</code></pre>\n\n<hr>\n\n<h2>“Nested” Methods</h2>\n\n<p>Ruby 1.9</p>\n\n<pre><code>def toggle\n def toggle\n \"subsequent times\"\n end\n \"first time\"\nend\n</code></pre>\n\n<hr>\n\n<p>HTH!</p>\n" }, { "answer_id": 21693, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "<p>One huge difference would be the move from Matz's interpreter to <a href=\"http://en.wikipedia.org/wiki/YARV\" rel=\"noreferrer\">YARV</a>, a bytecode virtual machine that helps significantly with performance.</p>\n" }, { "answer_id": 1426144, "author": "Dave Everitt", "author_id": 123033, "author_profile": "https://Stackoverflow.com/users/123033", "pm_score": 2, "selected": false, "text": "<p>Many now recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596516177\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Ruby Programming Language</a> over the Pickaxe - more to the point, it has all the details of the 1.8/1.9 differences.</p>\n" }, { "answer_id": 22941140, "author": "Wim Yedema", "author_id": 3224442, "author_profile": "https://Stackoverflow.com/users/3224442", "pm_score": 1, "selected": false, "text": "<p>Some more changes:</p>\n\n<p><strong>Returning a splat singleton array:</strong></p>\n\n<pre><code>def function\n return *[1]\nend\n\na=function\n</code></pre>\n\n<ul>\n<li>ruby 1.9 : [1]</li>\n<li>ruby 1.8 : 1</li>\n</ul>\n\n<p><strong>array arguments</strong></p>\n\n<pre><code>def function(array)\n array.each { |v| p v }\nend\nfunction \"1\"\n</code></pre>\n\n<ul>\n<li>ruby 1.8: \"1\"</li>\n<li>ruby 1.9: undefined method `each' for \"1\":String</li>\n</ul>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?
Sam Ruby has a [cool slideshow that outline the differences](http://slideshow.rubyforge.org/ruby19.html). In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful. Ruby 1.9 - Major Features ========================= * Performance * Threads/Fibers * Encoding/Unicode * gems is (mostly) built-in now * if statements do not introduce scope in Ruby. What's changed? =============== Single character strings. ------------------------- Ruby 1.9 ``` irb(main):001:0> ?c => "c" ``` Ruby 1.8.6 ``` irb(main):001:0> ?c => 99 ``` --- String index. ------------- Ruby 1.9 ``` irb(main):001:0> "cat"[1] => "a" ``` Ruby 1.8.6 ``` irb(main):001:0> "cat"[1] => 97 ``` --- {"a","b"} No Longer Supported ----------------------------- Ruby 1.9 ``` irb(main):002:0> {1,2} SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC ``` Ruby 1.8.6 ``` irb(main):001:0> {1,2} => {1=>2} ``` **Action:** Convert to {1 => 2} --- `Array.to_s` Now Contains Punctuation ------------------------------------- Ruby 1.9 ``` irb(main):001:0> [1,2,3].to_s => "[1, 2, 3]" ``` Ruby 1.8.6 ``` irb(main):001:0> [1,2,3].to_s => "123" ``` **Action:** Use .join instead --- Colon No Longer Valid In When Statements ---------------------------------------- Ruby 1.9 ``` irb(main):001:0> case 'a'; when /\w/: puts 'word'; end SyntaxError: (irb):1: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' ``` Ruby 1.8.6 ``` irb(main):001:0> case 'a'; when /\w/: puts 'word'; end word ``` **Action:** Use semicolon, then, or newline --- Block Variables Now Shadow Local Variables ------------------------------------------ Ruby 1.9 ``` irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 0 irb(main):002:0> i=0; for i in [1,2,3]; end; i => 3 ``` Ruby 1.8.6 ``` irb(main):001:0> i=0; [1,2,3].each {|i|}; i => 3 ``` --- `Hash.index` Deprecated ----------------------- Ruby 1.9 ``` irb(main):001:0> {1=>2}.index(2) (irb):18: warning: Hash#index is deprecated; use Hash#key => 1 irb(main):002:0> {1=>2}.key(2) => 1 ``` Ruby 1.8.6 ``` irb(main):001:0> {1=>2}.index(2) => 1 ``` **Action:** Use Hash.key --- `Fixnum.to_sym` Now Gone ------------------------ Ruby 1.9 ``` irb(main):001:0> 5.to_sym NoMethodError: undefined method 'to_sym' for 5:Fixnum ``` Ruby 1.8.6 ``` irb(main):001:0> 5.to_sym => nil ``` (Cont'd) Ruby 1.9 ``` # Find an argument value by name or index. def [](index) lookup(index.to_sym) end ``` svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb --- Hash Keys Now Unordered ----------------------- Ruby 1.9 ``` irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"} => {:a=>"a", :c=>"c", :b=>"b"} ``` Ruby 1.8.6 ``` irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"} => {:a=>"a", :b=>"b", :c=>"c"} ``` Order is insertion order --- Stricter Unicode Regular Expressions ------------------------------------ Ruby 1.9 ``` irb(main):001:0> /\x80/u SyntaxError: (irb):2: invalid multibyte escape: /\x80/ ``` Ruby 1.8.6 ``` irb(main):001:0> /\x80/u => /\x80/u ``` --- `tr` and `Regexp` Now Understand Unicode ---------------------------------------- Ruby 1.9 ``` unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT). gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR). gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]} ``` --- `pack` and `unpack` ------------------- Ruby 1.8.6 ``` def xchr(escape=true) n = XChar::CP1252[self] || self case n when *XChar::VALID XChar::PREDEFINED[n] or (n>128 ? n.chr : (escape ? "&##{n};" : [n].pack('U*'))) else Builder::XChar::REPLACEMENT_CHAR end end unpack('U*').map {|n| n.xchr(escape)}.join ``` --- `BasicObject` More Brutal Than `BlankSlate` ------------------------------------------- Ruby 1.9 ``` irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f NameError: uninitialized constant C::Math ``` Ruby 1.8.6 ``` irb(main):001:0> require 'blankslate' => true irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f => 3.14159265358979 ``` **Action:** Use ::Math::PI --- Delegation Changes ------------------ Ruby 1.9 ``` irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => String ``` Ruby 1.8.6 ``` irb(main):002:0> class C < SimpleDelegator; end => nil irb(main):003:0> C.new('').class => C irb(main):004:0> ``` [Defect 17700](http://rubyforge.org/tracker/index.php?func=detail&aid=17700&group_id=426&atid=1698) --- Use of $KCODE Produces Warnings ------------------------------- Ruby 1.9 ``` irb(main):004:1> $KCODE = 'UTF8' (irb):4: warning: variable $KCODE is no longer effective; ignored => "UTF8" ``` Ruby 1.8.6 ``` irb(main):001:0> $KCODE = 'UTF8' => "UTF8" ``` --- `instance_methods` Now an Array of Symbols ------------------------------------------ Ruby 1.9 ``` irb(main):001:0> {}.methods.sort.last => :zip ``` Ruby 1.8.6 ``` irb(main):001:0> {}.methods.sort.last => "zip" ``` **Action:** Replace instance\_methods.include? with method\_defined? --- Source File Encoding -------------------- ### Basic ``` # coding: utf-8 ``` ### Emacs ``` # -*- encoding: utf-8 -*- ``` ### Shebang ``` #!/usr/local/rubybook/bin/ruby # encoding: utf-8 ``` --- Real Threading -------------- * Race Conditions * Implicit Ordering Assumptions * Test Code --- What's New? =========== Alternate Syntax for Symbol as Hash Keys ---------------------------------------- Ruby 1.9 ``` {a: b} redirect_to action: show ``` Ruby 1.8.6 ``` {:a => b} redirect_to :action => show ``` --- Block Local Variables --------------------- Ruby 1.9 ``` [1,2].each {|value; t| t=value*value} ``` --- Inject Methods -------------- Ruby 1.9 ``` [1,2].inject(:+) ``` Ruby 1.8.6 ``` [1,2].inject {|a,b| a+b} ``` --- `to_enum` --------- Ruby 1.9 ``` short_enum = [1, 2, 3].to_enum long_enum = ('a'..'z').to_enum loop do puts "#{short_enum.next} #{long_enum.next}" end ``` --- No block? Enum! --------------- Ruby 1.9 ``` e = [1,2,3].each ``` --- Lambda Shorthand ---------------- Ruby 1.9 ``` p = -> a,b,c {a+b+c} puts p.(1,2,3) puts p[1,2,3] ``` Ruby 1.8.6 ``` p = lambda {|a,b,c| a+b+c} puts p.call(1,2,3) ``` --- Complex Numbers --------------- Ruby 1.9 ``` Complex(3,4) == 3 + 4.im ``` --- Decimal Is Still Not The Default -------------------------------- Ruby 1.9 ``` irb(main):001:0> 1.2-1.1 => 0.0999999999999999 ``` --- Regex “Properties” ------------------ Ruby 1.9 ``` /\p{Space}/ ``` Ruby 1.8.6 ``` /[:space:]/ ``` --- Splat in Middle --------------- Ruby 1.9 ``` def foo(first, *middle, last) (->a, *b, c {p a-c}).(*5.downto(1)) ``` --- Fibers ------ Ruby 1.9 ``` f = Fiber.new do a,b = 0,1 Fiber.yield a Fiber.yield b loop do a,b = b,a+b Fiber.yield b end end 10.times {puts f.resume} ``` --- Break Values ------------ Ruby 1.9 ``` match = while line = gets next if line =~ /^#/ break line if line.find('ruby') end ``` --- “Nested” Methods ---------------- Ruby 1.9 ``` def toggle def toggle "subsequent times" end "first time" end ``` --- HTH!
21,589
<p>I did some tests a while ago and never figured out how to make this work. </p> <p><strong>The ingredients:</strong></p> <ul> <li>COM+ transactional object (developed in VB6) </li> <li>.Net web application (with transaction) in IIS that...<br> makes a call to the COM+ component<br> updates a row in a SQL database</li> </ul> <p><strong>Testing:</strong> </p> <p>Run the .Net application and force an exception. </p> <p><strong>Result:</strong> </p> <p>The update made from the .Net application rolls back.<br> The update made by the COM+ object does not roll back.</p> <p>If I call the COM+ object from an old ASP page the rollback works.</p> <p>I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.</p>
[ { "answer_id": 21599, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>How are you implementing this? If you are using EnterpriseServices to manage the .NET transaction, then both transactions should get rolled back, since you're using the same context for them both.</p>\n" }, { "answer_id": 66513, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 3, "selected": true, "text": "<p>Because VB and .NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together.</p>\n\n<p><strong>From .NET</strong>, EnterpriseServices manages COM+ functionality, such as the DTC. In .NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code):</p>\n\n<pre><code>void SomeMethod()\n{\n EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full;\n using (TransactionScope s = new TransactionScope(e))\n {\n MyComPlusClass o = new MyComPlusClass();\n\n o.SomeTransactionalMethod();\n }\n}\n</code></pre>\n\n<p>I am not familiar enough with this to give you more advice at this point.</p>\n\n<p><strong>On the COM+ side</strong>, your object needs to be configured to use (most likely \"require\") a distributed transaction. You can do that from COM+ Explorer, by going to your object's <em>Properties</em>, selecting the <em>Transaction</em> tab, and clicking on \"<em>Required</em>\". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server).</p>\n\n<p>If everything works correctly, your COM+ object should be enlisting in the existing Context created by your .NET code.</p>\n\n<p>You can use the \"Distributed Transaction Coordinator\\Transaction List\" node in \"Component Services\" to check and see the distributed transaction being created during the call.</p>\n\n<p>Be aware that you cannot see the changes from the COM+ component reflected on data queries from the .NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328/" ]
I did some tests a while ago and never figured out how to make this work. **The ingredients:** * COM+ transactional object (developed in VB6) * .Net web application (with transaction) in IIS that... makes a call to the COM+ component updates a row in a SQL database **Testing:** Run the .Net application and force an exception. **Result:** The update made from the .Net application rolls back. The update made by the COM+ object does not roll back. If I call the COM+ object from an old ASP page the rollback works. I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.
Because VB and .NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together. **From .NET**, EnterpriseServices manages COM+ functionality, such as the DTC. In .NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code): ``` void SomeMethod() { EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full; using (TransactionScope s = new TransactionScope(e)) { MyComPlusClass o = new MyComPlusClass(); o.SomeTransactionalMethod(); } } ``` I am not familiar enough with this to give you more advice at this point. **On the COM+ side**, your object needs to be configured to use (most likely "require") a distributed transaction. You can do that from COM+ Explorer, by going to your object's *Properties*, selecting the *Transaction* tab, and clicking on "*Required*". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server). If everything works correctly, your COM+ object should be enlisting in the existing Context created by your .NET code. You can use the "Distributed Transaction Coordinator\Transaction List" node in "Component Services" to check and see the distributed transaction being created during the call. Be aware that you cannot see the changes from the COM+ component reflected on data queries from the .NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions.
21,640
<p>Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p> <p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p> <p>I need to return:</p> <p><code>http://www.mywebsite.com:80</code></p> <p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p> <p>Any suggestions?</p>
[ { "answer_id": 21653, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 5, "selected": false, "text": "<p>Request.Url will return you the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"noreferrer\">Uri</a> of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.scheme.aspx\" rel=\"noreferrer\">Scheme</a> property.</p>\n\n<p>Sample:</p>\n\n<pre><code>Uri url = Request.Url;\nstring protocol = url.Scheme;\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 22361, "author": "Rick", "author_id": 4367, "author_profile": "https://Stackoverflow.com/users/4367", "pm_score": 9, "selected": true, "text": "<p>The following (C#) code should do the trick</p>\n\n<pre><code>Uri uri = new Uri(\"http://www.mywebsite.com:80/pages/page1.aspx\");\nstring requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + \":\" + uri.Port;\n</code></pre>\n" }, { "answer_id": 578083, "author": "dthrasher", "author_id": 19112, "author_profile": "https://Stackoverflow.com/users/19112", "pm_score": 9, "selected": false, "text": "<p>Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.uri.getleftpart\" rel=\"noreferrer\"><code>Uri.GetLeftPart()</code></a> method.</p>\n<pre><code>Uri url = new Uri(&quot;http://www.mywebsite.com:80/pages/page1.aspx&quot;);\nstring output = url.GetLeftPart(UriPartial.Authority);\n</code></pre>\n<p>There is one catch to <code>GetLeftPart()</code>, however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of <code>GetLeftPart()</code> in my example above will be <code>http://www.mywebsite.com</code>.</p>\n<p>If the port number had been something other than 80, it would be included in the result.</p>\n" }, { "answer_id": 4195319, "author": "Holger", "author_id": 317431, "author_profile": "https://Stackoverflow.com/users/317431", "pm_score": 6, "selected": false, "text": "<p>Well if you are doing this in Asp.Net or have access to HttpContext.Current.Request\nI'd say these are easier and more general ways of getting them:</p>\n\n<pre><code>var scheme = Request.Url.Scheme; // will get http, https, etc.\nvar host = Request.Url.Host; // will get www.mywebsite.com\nvar port = Request.Url.Port; // will get the port\nvar path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx\n</code></pre>\n\n<p>I hope this helps. :)</p>\n" }, { "answer_id": 5238832, "author": "Haonan Tan", "author_id": 650550, "author_profile": "https://Stackoverflow.com/users/650550", "pm_score": 5, "selected": false, "text": "<p>A more structured way to get this is to use UriBuilder. This avoids direct string manipulation. </p>\n\n<pre><code>var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);\n</code></pre>\n" }, { "answer_id": 32615682, "author": "Mark Shapiro", "author_id": 789680, "author_profile": "https://Stackoverflow.com/users/789680", "pm_score": 5, "selected": false, "text": "<p>Even shorter way, may require newer ASP.Net:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)\n</code></pre>\n\n<p>The UriComponents enum lets you specify which component(s) of the URI you want to include.</p>\n" }, { "answer_id": 33714244, "author": "benscabbia", "author_id": 3828228, "author_profile": "https://Stackoverflow.com/users/3828228", "pm_score": 4, "selected": false, "text": "<p>Very similar to Holger's answer. If you need to grab the URL can do something like: </p>\n\n<pre><code>Uri uri = Context.Request.Url; \nvar scheme = uri.Scheme // returns http, https\nvar scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://\nvar host = uri.Host; // return www.mywebsite.com\nvar port = uri.Port; // returns port number\n</code></pre>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx\" rel=\"noreferrer\">Uri class</a> provides a whole range of methods, many which I have not listed. </p>\n\n<p>In my instance, I needed to grab <code>LocalHost</code> along with the <code>Port Number</code>, so this is what I did: </p>\n\n<pre><code>var Uri uri = Context.Request.Url;\nvar host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + \":\" + uri.Port; \n</code></pre>\n\n<p>Which successfully grabbed: <code>http://localhost:12345</code></p>\n" }, { "answer_id": 73877202, "author": "Kashif Usman I", "author_id": 15583595, "author_profile": "https://Stackoverflow.com/users/15583595", "pm_score": -1, "selected": false, "text": "<p>In my case</p>\n<pre><code>Uri uri = new Uri(&quot;http://www.mywebsite.com:80/pages/page1.aspx&quot;);\nstring requested = uri.Scheme + Uri.SchemeDelimiter + uri.Authority;\n</code></pre>\n<p>works to get</p>\n<p><a href=\"https://www.mywebsite.com:80\" rel=\"nofollow noreferrer\">https://www.mywebsite.com:80</a></p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2076253/" ]
Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL: `http://www.mywebsite.com:80/pages/page1.aspx` I need to return: `http://www.mywebsite.com:80` I know I can use `Request.Url.AbsoluteUri` to get the complete URL, and I know I can use `Request.Url.Authority` to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string. Any suggestions?
The following (C#) code should do the trick ``` Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; ```
21,647
<p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile &gt;&gt; x; cerr &lt;&lt; x &lt;&lt; endl; } return 0; } </code></pre> <p><strong>input.txt</strong>:</p> <pre><code>10 20 30 </code></pre> <p><strong>Output</strong>:</p> <pre><code>10 20 30 30 </code></pre> <p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>
[ { "answer_id": 21656, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 8, "selected": true, "text": "<p>Just follow closely the chain of events.</p>\n\n<ul>\n<li>Grab 10</li>\n<li>Grab 20</li>\n<li>Grab 30</li>\n<li>Grab EOF</li>\n</ul>\n\n<p>Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet (\"binarically\" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.</p>\n\n<p>Try this:</p>\n\n<pre><code>while (true) {\n int x;\n iFile &gt;&gt; x;\n if( iFile.eof() ) break;\n cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.</p>\n" }, { "answer_id": 21666, "author": "Patrick Loz", "author_id": 2091, "author_profile": "https://Stackoverflow.com/users/2091", "pm_score": 5, "selected": false, "text": "<p>I like this example, which for now, leaves out the check which you could add inside the while block:</p>\n\n<pre><code>ifstream iFile(\"input.txt\"); // input.txt has integers, one per line\nint x;\n\nwhile (iFile &gt;&gt; x) \n{\n cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Not sure how safe it is...</p>\n" }, { "answer_id": 21787, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "<p>There's an alternative approach to this:</p>\n\n<pre><code>#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n\n// ...\n\n copy(istream_iterator&lt;int&gt;(iFile), istream_iterator&lt;int&gt;(),\n ostream_iterator&lt;int&gt;(cerr, \"\\n\"));\n</code></pre>\n" }, { "answer_id": 14836904, "author": "Solostaran14", "author_id": 1033530, "author_profile": "https://Stackoverflow.com/users/1033530", "pm_score": 3, "selected": false, "text": "<p>Without to much modifications of the original code, it could become :</p>\n\n<pre><code>while (!iFile.eof())\n{ \n int x;\n iFile &gt;&gt; x;\n if (!iFile.eof()) break;\n cerr &lt;&lt; x &lt;&lt; endl;\n}\n</code></pre>\n\n<p>but I prefer the two other solutions above in general.</p>\n" }, { "answer_id": 15958291, "author": "user1384482", "author_id": 1384482, "author_profile": "https://Stackoverflow.com/users/1384482", "pm_score": 2, "selected": false, "text": "<pre><code>int x;\nifile &gt;&gt; x\n\nwhile (!iFile.eof())\n{ \n cerr &lt;&lt; x &lt;&lt; endl; \n iFile &gt;&gt; x; \n}\n</code></pre>\n" }, { "answer_id": 27273529, "author": "Brian Jack", "author_id": 669580, "author_profile": "https://Stackoverflow.com/users/669580", "pm_score": 3, "selected": false, "text": "<p>The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.</p>\n\n<p>What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.</p>\n\n<p>I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.</p>\n\n<ul>\n<li>0</li>\n</ul>\n\n<p>So add a prime read and move the loop's read to the end:</p>\n\n<pre><code>int x;\n\niFile &gt;&gt; x; // prime read here\nwhile (!iFile.eof()) {\n cerr &lt;&lt; x &lt;&lt; endl;\n iFile &gt;&gt; x;\n}\n</code></pre>\n" }, { "answer_id": 27585094, "author": "Raf", "author_id": 930502, "author_profile": "https://Stackoverflow.com/users/930502", "pm_score": 2, "selected": false, "text": "<p>At the end of the last line, you have a new line character, which is not read by >> operator and it is not an end of file.\nPlease, make an experiment and delete the new line (thelast character in file) - you will not get the duplication.\nTo have a flexible code and avoid unwanted effects just apply any solution given by other users.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
The following **C++** code uses a **ifstream** object to read integers from a text file (which has one number per line) until it hits **EOF**. Why does it read the integer on the last line twice? How to fix this? **Code:** ``` #include <iostream> #include <fstream> using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile >> x; cerr << x << endl; } return 0; } ``` **input.txt**: ``` 10 20 30 ``` **Output**: ``` 10 20 30 30 ``` **Note**: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
Just follow closely the chain of events. * Grab 10 * Grab 20 * Grab 30 * Grab EOF Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop. Try this: ``` while (true) { int x; iFile >> x; if( iFile.eof() ) break; cerr << x << endl; } ``` By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
21,651
<p>I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p>However, in Adobe AIR, there is a restriction on using <a href="http://labs.adobe.com/wiki/index.php/AIR:HTML_Security_FAQ#Why_restrict_eval.28.29_for_all_Application_content_if_there_are_legitimate_use_cases_for_using_it.3F" rel="nofollow noreferrer">eval()</a> for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately.</p> <p>Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now</p> <hr> <p><strong>Update:</strong></p> <p>Thanks to <a href="https://stackoverflow.com/a/24919/7750640">Theo</a> and <a href="https://stackoverflow.com/a/21716/7750640">jsight</a> for their answers; </p> <p>One important thing I learnt today is that I can actually make use of ActionScript libraries by using the <pre>&lt;script src="lib/myClasses.swf" type="application/x-shockwave-flash"&gt;&lt;/script&gt;</pre> tag extended by Adobe AIR. Check out <a href="https://stackoverflow.com/a/24919/7750640">Theo's</a> link for more details!</p>
[ { "answer_id": 21716, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 2, "selected": false, "text": "<p>Have you looked at <a href=\"http://code.google.com/p/as3corelib/\" rel=\"nofollow noreferrer\">as3corelib</a>? It appears to provide an AS3 parser for JSON data, and my hope would be that it doesn't rely upon eval (eval tends to be bad for security as you noted). There are similar libs for Javascript as well, and they tend to be the preferred way to parse json due to the security implications of calling eval on (potentially) evil data.</p>\n" }, { "answer_id": 22099, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "<p>JSON is Javascript Object Notation, so if you are using Javascript you are already there!\nHave a look at these links, they give examples of how to create Javascript objects from JSON:</p>\n\n<p><a href=\"http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)\" rel=\"nofollow noreferrer\">http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)</a></p>\n\n<p><a href=\"http://betterexplained.com/articles/using-json-to-exchange-data/\" rel=\"nofollow noreferrer\">http://betterexplained.com/articles/using-json-to-exchange-data/</a></p>\n\n<p>If you decide to go the Flex / AS3 route, then as the jsight said, as3corelib is a good place to start.</p>\n" }, { "answer_id": 24919, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": "<p>You can find a <a href=\"http://www.JSON.org/js.html\" rel=\"noreferrer\">JSON parser written in JavaScript here</a> (<a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"noreferrer\">source code here</a>). You can also use the as3corelib JSON parser from JavaScript, there's <a href=\"http://help.adobe.com/en_US/AIR/1.1/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7ed9.html\" rel=\"noreferrer\">a description of how to access ActionScript libraries from JavaScript here</a>.</p>\n" }, { "answer_id": 26614, "author": "John Lemberger", "author_id": 2882, "author_profile": "https://Stackoverflow.com/users/2882", "pm_score": 0, "selected": false, "text": "<p>I think this is possible if you use an iframe and sandbox bridge. You should be able to run eval() on downloaded code in the sandboxed iframe,</p>\n\n<p>Excerpt from <a href=\"http://help.adobe.com/en_US/AIR/1.1/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7f11.html#WS5b3ccc516d4fbf351e63e3d118666ade46-7e40\" rel=\"nofollow noreferrer\">Adobe AIR 1.1 Doc's</a>\n\"...it may be more convenient to run content in a sandboxed child frame so that the content can be run with no restrictions on eval()...\"</p>\n\n<p>Another related article: <a href=\"http://www.sitepen.com/blog/2008/08/21/building-on-air-working-with-the-sandbox-bridges/\" rel=\"nofollow noreferrer\">Building on AIR: Working with the Sandbox Bridges</a></p>\n" }, { "answer_id": 4524589, "author": "Chris Dolan", "author_id": 14783, "author_profile": "https://Stackoverflow.com/users/14783", "pm_score": 2, "selected": false, "text": "<p>The current AIR release (v2.5) bundles a newer WebKit that has native JSON support, via JSON.stringify() and JSON.parse().</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504504/" ]
I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ However, in Adobe AIR, there is a restriction on using [eval()](http://labs.adobe.com/wiki/index.php/AIR:HTML_Security_FAQ#Why_restrict_eval.28.29_for_all_Application_content_if_there_are_legitimate_use_cases_for_using_it.3F) for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately. Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now --- **Update:** Thanks to [Theo](https://stackoverflow.com/a/24919/7750640) and [jsight](https://stackoverflow.com/a/21716/7750640) for their answers; One important thing I learnt today is that I can actually make use of ActionScript libraries by using the ``` <script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script> ``` tag extended by Adobe AIR. Check out [Theo's](https://stackoverflow.com/a/24919/7750640) link for more details!
You can find a [JSON parser written in JavaScript here](http://www.JSON.org/js.html) ([source code here](https://github.com/douglascrockford/JSON-js/blob/master/json2.js)). You can also use the as3corelib JSON parser from JavaScript, there's [a description of how to access ActionScript libraries from JavaScript here](http://help.adobe.com/en_US/AIR/1.1/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7ed9.html).
21,652
<p>I have some code that gives a user id to a utility that then send email to that user.</p> <pre><code>emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } </code></pre> <p><code>MailException</code> could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.</p> <p>My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.</p> <p><strong>Edit:</strong> As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a <strong>valid</strong> email address, or it could fail.. etc.</p> <p>My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).</p> <p>Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.</p>
[ { "answer_id": 21667, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 1, "selected": false, "text": "<p>It depends on what your application is doing. You might want to throw individual exceptions in cases like </p>\n\n<ul>\n<li>The application is high availability </li>\n<li>Sending e-mail is particularly important </li>\n<li>The scope of the application is small and sending e-mail is a large part of it</li>\n<li>The application will be deployed to a site which is remote and you will only get logs for debugging</li>\n<li>You can recover from some subset of the exceptions encapsulated in the mailException but not others</li>\n</ul>\n\n<p>In most cases I would say just log the text of the exception and don't waste your time granularizing already pretty granular exceptions. </p>\n" }, { "answer_id": 21678, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 3, "selected": false, "text": "<p>In my code, I find that MOST exceptions percolate up to a UI layer where they are caught by my exception handlers which simply display a message to the user (and write to the log). It's an unexpected exception, after all.</p>\n\n<p>Sometimes, I do want to catch a specific exception (as you seem to want to do). You'll probably find, however, that this is somewhat rare and that it is indicative of using exceptions to control logic -- which is inefficient (slow) and often frowned upon.</p>\n\n<p>So using your example, if you want to run some special logic when the email server is not configured, you may want to add a method to the emailUtil object like:</p>\n\n<p>public bool isEmailConfigured()</p>\n\n<p>... call that first, instead of looking for a specific exception.</p>\n\n<p>When an exception does happen, it really means that the situation was completely unexpected and the code can't handle it -- so the best you can do is report it to the user (or write it to a log or restart )</p>\n\n<p>As for having an exception hierarchy vs exceptions-with-error-codes-in-them, I typically do the latter. It's easier to add new exceptions, if you just need to define a new error constant instead of a whole new class. But, it doesn't matter much as long as you try to be consistent throughout your project.</p>\n" }, { "answer_id": 21777, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "<p>Instead of using exceptions, I tend to return a list of status objects from methods that may have problems executing. The status objects contain a severity enum (information, warning, error, ...) a status object name like \"Email Address\" and a user readable message like \"Badly formatted Email Address\"</p>\n\n<p>The calling code would then decide which to filter up to the UI and which to handle itself.</p>\n\n<p>Personally, I think exceptions are strictly for when you can't implement a normal code solution. The performance hit and handling restrictions are just a bit too much for me.</p>\n\n<p>Another reason for using a list of status objects is that identifying multiple errors (such as during validation) is MUCH easier. After all, you can only throw one exception which must be handled before moving on. </p>\n\n<p>Imagine a user submitting an email that had a malformed destination address and contained language that you are blocking. Do you throw the malformed email exception, then, after they fix that and resubmit, throw a bad language exception? From a user experience perspective dealing with all of them at once is a better way to go.</p>\n\n<p><strong>UPDATE:</strong> combining answers</p>\n\n<p>@Jonathan: My point was that I can evaluate the action, in this case sending an email, and send back multiple failure reasons. For example, \"bad email address\", \"blank message title\", etc..</p>\n\n<p>With an exception, you're limited to just percolating the one problem then asking the user to resubmit at which point they find out about a second problem. This is really bad UI design.</p>\n\n<p>Reinventing the wheel.. possibly. However, most applications should analyze the whole transaction in order to give the best possible information to the user. Imagine if your compiler stopped dead at the first error. You then fix the error and hit compile again only to have it stop again for a different error. What a pain in the butt. To me, that's exactly the problem with throwing exceptions and hence the reason I said to use a different mechanism.</p>\n" }, { "answer_id": 21784, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>@Chris.Lively</p>\n\n<p>You know you can pass a message in your exception, or even the \"status codes\". You are reinventing the wheel here.</p>\n" }, { "answer_id": 21851, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 0, "selected": false, "text": "<p>I tend to have less Exception types, although it's not really the OO way to do it. Instead I put an enum to my custom Exceptions, which classifies the Exception. Most of the time I have a custom base Exception, which holds on to a couple of members, which can be overridden or customized in derived Exception types. </p>\n\n<p>A couple of months ago I <a href=\"http://dlinsin.blogspot.com/2008/04/how-to-internationalize-exceptions-ii.html\" rel=\"nofollow noreferrer\">blogged</a> about the idea of how to internationalize Exceptions. It includes some of the ideas mentioned above.</p>\n" }, { "answer_id": 21858, "author": "niklasfi", "author_id": 2275, "author_profile": "https://Stackoverflow.com/users/2275", "pm_score": -1, "selected": false, "text": "<p>I would just go by</p>\n\n<pre><code>throw new exception(\"WhatCausedIt\")\n</code></pre>\n\n<p>if you want to handle your exceptions, you could pass a code instead of \"WhatCausedIt\" an then react to the different answers with a switch statement. </p>\n" }, { "answer_id": 22633, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 0, "selected": false, "text": "<p>While you can differenciate the code execution looking the exception don't matter if it's done by the \"catch exceptionType hierarchy mode\" or by \"if(...) else...exception code mode\"</p>\n\n<p>but if you are developing software wich is going to be used by other people, like a library i think it's usefull create your own exception types to notice the other people that your sofware can throw other exceptions than the normal ones, and they better catch and resolve them.</p>\n\n<p>When i use a library and their methods simply launch an 'Exception' i allways wonder: What can cause this exception?, how must my program react?, if there is a javadoc maybe the cause will be explained, but mustly of times there is not a javadoc or the exception is not explained. Too much overhead witch can be avoided with a WellChossenExceptionTypeName</p>\n" }, { "answer_id": 27239, "author": "Jim", "author_id": 1208, "author_profile": "https://Stackoverflow.com/users/1208", "pm_score": 0, "selected": false, "text": "<p>It depends on whether the code that catches the exception needs to differentiate between exceptions or whether you are just using exceptions to fail out to an error page. If you need to differentiate between a NullReference exception and your custom MailException higher up in the call stack, then spend the time and write it. But most of the time programmers just use exceptions as a catch all to throw up an error on the web page. In this case you are just wasting effort on writing a new exception.</p>\n" }, { "answer_id": 27249, "author": "abigblackman", "author_id": 2279, "author_profile": "https://Stackoverflow.com/users/2279", "pm_score": 1, "selected": false, "text": "<p>I think a combination of the above is going to give you the best result. </p>\n\n<p>You can throw different exceptions depending on the problem. e.g. Missing email address = ArgumentException. </p>\n\n<p>But then in the UI layer you can check the exception type and, if need be, the message and then display a appropriate message to the user. I personally tend to only show a informational message to the user if a certain type of exception is thrown (UserException in my app). Of course you should scrub and verify user input as much as possible further up the stack to make sure any exceptions are generated by truly unlikely scenarios, not as a filter for malformed emails which can easily be checked with a regex.</p>\n\n<p>I also wouldn't worry about the performance implications of catching an exception from user input. The only time you are going to see performance problems from exceptions is when they are being thrown and caught in a loop or similar.</p>\n" }, { "answer_id": 138532, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 4, "selected": true, "text": "<p>I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.</p>\n\n<p>An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).</p>\n\n<p>This way you get the advantages of both, you don't have throw-clauses like:</p>\n\n<pre><code>throws SpecificException1, SpecificException2, SpecificException3 ...\n</code></pre>\n\n<p>a general</p>\n\n<pre><code>throws GeneralException\n</code></pre>\n\n<p>is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.</p>\n" }, { "answer_id": 433482, "author": "Thorbjørn Ravn Andersen", "author_id": 53897, "author_profile": "https://Stackoverflow.com/users/53897", "pm_score": 2, "selected": false, "text": "<p>I have found that if you need to have CODE deciding what to do based on the exception returned, create a well named exception subclassing a common base type. The message passed should be considered \"human eyes only\" and too fragile to make decisions upon. Let the compiler do the work! </p>\n\n<p>If you need to pass this up to a higher layer through a mechanism not aware of checked exceptions, you can wrap it in a suitable named subclass of RuntimeException (MailDomainException) which can be caught up high, and the original cause acted upon.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
I have some code that gives a user id to a utility that then send email to that user. ``` emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } ``` `MailException` could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened. **Edit:** As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a **valid** email address, or it could fail.. etc. My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well). Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific. An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more). This way you get the advantages of both, you don't have throw-clauses like: ``` throws SpecificException1, SpecificException2, SpecificException3 ... ``` a general ``` throws GeneralException ``` is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
21,697
<p>I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.</p> <p>So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:</p> <pre><code>public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view) : this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } </code></pre> <p>I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.</p> <p>Let's say the following Service Layer messages can show up:</p> <ul> <li>E-mail account already exists (failure)</li> <li>Refering user entered does not exist (failure)</li> <li>Password length exceeds datastore allowed length (failure)</li> <li>Member created successfully (success)</li> </ul> <p>Let's also say that more rules will be in the service layer that the UI cannot anticipate.</p> <p>Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.</p> <hr> <blockquote> <p><strong>Edit not by OP: merging in follow-up comments that were posted as answers by the OP</strong></p> </blockquote> <hr> <p>Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.</p> <p>tgmdbm, I like the clever use of the lambda expression there!</p> <hr> <p>Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.</p> <p>However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?</p> <p>Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:</p> <p><img src="https://i.stack.imgur.com/HOJU7.png" alt="Create a user"></p> <p>For this kind of error, it's nice to report it to the same view. </p> <p>Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.</p>
[ { "answer_id": 22043, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 5, "selected": true, "text": "<p>That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.</p>\n\n<p><strong>Don't catch Exception</strong></p>\n\n<p>However, <a href=\"https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception\">don't catch Exception</a> in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. </p>\n\n<p><strong>Plan a Simple Exception Hierarchy</strong></p>\n\n<p>If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. \nAt a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.</p>\n\n<p>Your presenter then has the option of doing</p>\n\n<pre><code>try {\n // call service etc.\n // handle success to view\n} \ncatch (AccountAlreadyExistsException) {\n // set the message and some other unique data in the view\n}\ncatch (ServiceLayerException) {\n // set the message in the view\n}\n// system exceptions, and unrecoverable exceptions are allowed to bubble \n// up the call stack so a general error can be shown to the user, rather \n// than showing the form again.\n</code></pre>\n\n<p>Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.</p>\n\n<p>I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.</p>\n" }, { "answer_id": 22586, "author": "tgmdbm", "author_id": 1851, "author_profile": "https://Stackoverflow.com/users/1851", "pm_score": 2, "selected": false, "text": "<p>As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception. </p>\n\n<p>Any validation exceptions however should be handled in the view but typically this logic is common to many parts of your application. So I like to have a helper like this</p>\n\n<pre><code>public static class Try {\n public static List&lt;string&gt; This( Action action ) {\n var errors = new List&lt;string&gt;();\n try {\n action();\n }\n catch ( SpecificException e ) {\n errors.Add( \"Something went 'orribly wrong\" );\n }\n catch ( ... )\n // ...\n return errors;\n }\n}\n</code></pre>\n\n<p>Then when calling your service just do the following</p>\n\n<pre><code>var errors = Try.This( () =&gt; {\n // call your service here\n tasks.CreateMember( ... );\n} );\n</code></pre>\n\n<p>Then in errors is empty, you're good to go.</p>\n\n<p>You can take this further and extend it with custome exception handlers which handle <em>uncommon</em> exceptions.</p>\n" }, { "answer_id": 25030, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 1, "selected": false, "text": "<p>In reply to the follow-up question:</p>\n\n<p>As for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds. </p>\n\n<p>However, in many real world applications, error handling can be 70% of the work, so it's all just part of the game really. </p>\n\n<p>As tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java's Spring MVC library does this very well. Here's a snippet from a config file for Spring MVC's Exception resolver - its for Java/Spring but you'll get the idea.</p>\n\n<p>This takes a huge amount of exception handling out of your presenters/controllers altogether.</p>\n\n<pre><code>&lt;bean id=\"exceptionResolver\"\n class=\"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver\"&gt;\n\n &lt;property name=\"exceptionMappings\"&gt;\n &lt;props&gt;\n &lt;prop key=\"UserNotFoundException\"&gt;\n rescues/UserNotFound\n &lt;/prop&gt;\n &lt;prop key=\"HibernateJdbcException\"&gt;\n rescues/databaseProblem\n &lt;/prop&gt;\n &lt;prop key=\"java.net.ConnectException\"&gt;\n rescues/networkTimeout\n &lt;/prop&gt;\n &lt;prop key=\"ValidationException\"&gt;\n rescues/validationError\n &lt;/prop&gt;\n &lt;prop key=\"EnvironmentNotConfiguredException\"&gt;\n rescues/environmentNotConfigured\n &lt;/prop&gt;\n &lt;prop key=\"MessageRejectedPleaseRetryException\"&gt;\n rescues/messageRejected\n &lt;/prop&gt;\n &lt;/props&gt;\n &lt;/property&gt;\n &lt;property name=\"defaultErrorView\" value=\"rescues/general\" /&gt;\n&lt;/bean&gt;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1894/" ]
I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: ``` public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view) : this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } ``` I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: * E-mail account already exists (failure) * Refering user entered does not exist (failure) * Password length exceeds datastore allowed length (failure) * Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. --- > > **Edit not by OP: merging in follow-up comments that were posted as answers by the OP** > > > --- Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! --- Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: ![Create a user](https://i.stack.imgur.com/HOJU7.png) For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.
That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem. **Don't catch Exception** However, [don't catch Exception](https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception) in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. **Plan a Simple Exception Hierarchy** If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException. Your presenter then has the option of doing ``` try { // call service etc. // handle success to view } catch (AccountAlreadyExistsException) { // set the message and some other unique data in the view } catch (ServiceLayerException) { // set the message in the view } // system exceptions, and unrecoverable exceptions are allowed to bubble // up the call stack so a general error can be shown to the user, rather // than showing the form again. ``` Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view. I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.
21,715
<p>Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable</p> <p>IE:</p> <pre><code>public class CollectionBase : IEnumerable </code></pre> <p>and then would derive their Business Object collections from that.</p> <pre><code>public class BusinessObjectCollection : CollectionBase </code></pre> <p>Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:</p> <pre><code>public class BusinessObjectCollection : List&lt;BusinessObject&gt; </code></pre> <p>I do this because I like to have strongly typed names instead of just passing Lists around.</p> <p>What is <strong>your</strong> approach?</p>
[ { "answer_id": 21720, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>I generally only derive my own collection classes if I need to \"add value\". Like, if the collection itself needed to have some \"metadata\" properties tagging along with it.</p>\n" }, { "answer_id": 21722, "author": "Scott Muc", "author_id": 1894, "author_profile": "https://Stackoverflow.com/users/1894", "pm_score": 2, "selected": false, "text": "<p>I've been going back and forth on 2 options:</p>\n\n<pre><code>public class BusinessObjectCollection : List&lt;BusinessObject&gt; {}\n</code></pre>\n\n<p>or methods that just do the following:</p>\n\n<pre><code>public IEnumerable&lt;BusinessObject&gt; GetBusinessObjects();\n</code></pre>\n\n<p>The benefits of the first approach is that you can change the underlying data store without having to mess with method signatures. Unfortunately if you inherit from a collection type that removes a method from the previous implementation, then you'll have to deal with those situations throughout your code.</p>\n" }, { "answer_id": 21724, "author": "jeremcc", "author_id": 1436, "author_profile": "https://Stackoverflow.com/users/1436", "pm_score": 2, "selected": false, "text": "<p>I do the exact same thing as you Jonathan... just inherit from <code>List&lt;T&gt;</code>. You get the best of both worlds. But I generally only do it when there is some value to add, like adding a <code>LoadAll()</code> method or whatever.</p>\n" }, { "answer_id": 21727, "author": "AdamSane", "author_id": 805, "author_profile": "https://Stackoverflow.com/users/805", "pm_score": 0, "selected": false, "text": "<p><strong>6 of 1, half dozen of another</strong> </p>\n\n<p>Either way its the same thing. I only do it when I have reason to add custom code into the BusinessObjectCollection. </p>\n\n<p>With out it having load methods return a list allows me to write more code in a common generic class and have it just work. Such as a Load method.</p>\n" }, { "answer_id": 21730, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 3, "selected": false, "text": "<p>I prefer just to use <code>List&lt;BusinessObject&gt;</code>. Typedefing it just adds unnecessary boilerplate to the code. <code>List&lt;BusinessObject&gt;</code> is a specific type, it's not just any <code>List</code> object, so it's still strongly typed.</p>\n\n<p>More importantly, declaring something <code>List&lt;BusinessObject&gt;</code> makes it easier for everyone reading the code to tell what types they are dealing with, they don't have to search through to figure out what a <code>BusinessObjectCollection</code> is and then remember that it's just a list. By typedefing, you'll have to require a consistent (re)naming convention that everyone has to follow in order for it to make sense.</p>\n" }, { "answer_id": 21731, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 2, "selected": false, "text": "<p>You should probably avoid creating your own collection for that purpose. It's pretty common to want to change the type of data structure a few times during refactorings or when adding new features. With your approach, you would wind up with a separate class for BusinessObjectList, BusinessObjectDictionary, BusinessObjectTree, etc.</p>\n\n<p>I don't really see any value in creating this class just because the classname is more readable. Yeah, the angle bracket syntax is kind of ugly, but it's standard in C++, C# and Java, so even if you don't write code that uses it you're going to run into it all the time.</p>\n" }, { "answer_id": 21733, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 4, "selected": false, "text": "<p>It's <a href=\"http://blogs.msdn.com/fxcop/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx\" rel=\"noreferrer\">recommended</a> that in public API's not to use List&lt;T&gt;, but to use Collection&lt;T&gt;</p>\n\n<p>If you are inheriting from it though, you should be fine, afaik.</p>\n" }, { "answer_id": 21786, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 7, "selected": true, "text": "<p>I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time.</p>\n\n<p>However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes.</p>\n\n<p>Basically, C# 3.0 allows any class that implements <code>IEnumerable</code> and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax:</p>\n\n<pre><code>var d = new Dictionary&lt;string, int&gt;\n{\n {\"hello\", 0},\n {\"the answer to life the universe and everything is:\", 42}\n};\n</code></pre>\n\n<p>The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection:</p>\n\n<pre><code>class c1 : IEnumerable\n{\n void Add(int x1, int x2, int x3)\n {\n //...\n }\n\n //...\n}\n</code></pre>\n\n<p>it would be possible to initialize it like so:</p>\n\n<pre><code>var x = new c1\n{\n {1,2,3},\n {4,5,6}\n}\n</code></pre>\n\n<p>This can be really useful if you need to create static tables of complex objects. For example, if you were just using <code>List&lt;Customer&gt;</code> and you wanted to create a static list of customer objects you would have to create it like so:</p>\n\n<pre><code>var x = new List&lt;Customer&gt;\n{\n new Customer(\"Scott Wisniewski\", \"555-555-5555\", \"Seattle\", \"WA\"),\n new Customer(\"John Doe\", \"555-555-1234\", \"Los Angeles\", \"CA\"),\n new Customer(\"Michael Scott\", \"555-555-8769\", \"Scranton PA\"),\n new Customer(\"Ali G\", \"\", \"Staines\", \"UK\")\n}\n</code></pre>\n\n<p>However, if you use a customized collection, like this one:</p>\n\n<pre><code>class CustomerList : List&lt;Customer&gt;\n{\n public void Add(string name, string phoneNumber, string city, string stateOrCountry)\n {\n Add(new Customer(name, phoneNumber, city, stateOrCounter));\n }\n}\n</code></pre>\n\n<p>You could then initialize the collection using this syntax:</p>\n\n<pre><code>var customers = new CustomerList\n{\n {\"Scott Wisniewski\", \"555-555-5555\", \"Seattle\", \"WA\"},\n {\"John Doe\", \"555-555-1234\", \"Los Angeles\", \"CA\"},\n {\"Michael Scott\", \"555-555-8769\", \"Scranton PA\"},\n {\"Ali G\", \"\", \"Staines\", \"UK\"}\n}\n</code></pre>\n\n<p>This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex. </p>\n\n<p>That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database.</p>\n\n<p>My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use <code>List&lt;T&gt;</code> directly.</p>\n" }, { "answer_id": 21806, "author": "Ryan Eastabrook", "author_id": 105, "author_profile": "https://Stackoverflow.com/users/105", "pm_score": 1, "selected": false, "text": "<p>I use generic lists for almost all scenarios. The only time that I would consider using a derived collection anymore is if I add collection specific members. However, the advent of LINQ has lessened the need for even that.</p>\n" }, { "answer_id": 43133, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": -1, "selected": false, "text": "<p>this is the way:</p>\n\n<p>return arrays, accept <code>IEnumerable&lt;T&gt;</code></p>\n\n<p>=)</p>\n" }, { "answer_id": 75319, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>As someone else pointed out, it is recommended not to expose List publicly, and FxCop will whinge if you do so. This includes inheriting from List as in:</p>\n\n<pre><code>public MyTypeCollection : List&lt;MyType&gt;\n</code></pre>\n\n<p>In most cases public APIs will expose IList (or ICollection or IEnumerable) as appropriate.</p>\n\n<p>In cases where you want your own custom collection, you can keep FxCop quiet by inheriting from Collection instead of List. </p>\n" }, { "answer_id": 93950, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 0, "selected": false, "text": "<p>If you choose to create your own collection class you should check out the types in <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx\" rel=\"nofollow noreferrer\">System.Collections.ObjectModel Namespace</a>. </p>\n\n<p>The namespace defines base classes thare are ment to make it easier for implementers to create a custom collections.</p>\n" }, { "answer_id": 94012, "author": "William Yeung", "author_id": 16371, "author_profile": "https://Stackoverflow.com/users/16371", "pm_score": 0, "selected": false, "text": "<p>I tend to do it with my own collection if I want to shield the access to the actual list. When you are writing business objects, chance is that you need a hook to know if your object is being added/removed, in such sense I think BOCollection is better idea. Of coz if that is not required, List is more lightweight. Also you might want to check using IList to provide additional abstraction interface if you need some kind of proxying (e.g. a fake collection triggers lazy load from database)</p>\n\n<p>But... why not consider Castle ActiveRecord or any other mature ORM framework? :)</p>\n" }, { "answer_id": 94032, "author": "Adam Vigh", "author_id": 1613872, "author_profile": "https://Stackoverflow.com/users/1613872", "pm_score": 0, "selected": false, "text": "<p>At the most of the time I simply go with the List way, as it gives me all the functionality I need at the 90% of the time, and when something 'extra' is needed, I inherit from it, and code that extra bit.</p>\n" }, { "answer_id": 192059, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I would do this:</p>\n\n<pre><code>using BusinessObjectCollection = List&lt;BusinessObject&gt;;\n</code></pre>\n\n<p>This just creates an alias rather than a completely new type. I prefer it to using List&lt;BusinessObject> directly because it leaves me free to change the underlying structure of the collection at some point in the future without changing code that uses it (as long as I provide the same properties and methods).</p>\n" }, { "answer_id": 394843, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 0, "selected": false, "text": "<p>try out this:</p>\n\n<pre><code>System.Collections.ObjectModel.Collection&lt;BusinessObject&gt;\n</code></pre>\n\n<p>it makes unnecessary to implement basic method like CollectionBase do</p>\n" }, { "answer_id": 483504, "author": "Ed Blackburn", "author_id": 27962, "author_profile": "https://Stackoverflow.com/users/27962", "pm_score": 2, "selected": false, "text": "<p>You can use both. For laziness - I mean productivity - List is a very useful class, it's also \"comprehensive\" and frankly full of YANGNI members. Coupled with the sensible argument / recommendation put forward by the <a href=\"http://blogs.msdn.com/fxcop/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx\" rel=\"nofollow noreferrer\">MSDN article</a> already linked about exposing List as a public member, I prefer the \"third\" way:</p>\n\n<p>Personally I use the decorator pattern to expose only what I need from List i.e:</p>\n\n<pre><code>public OrderItemCollection : IEnumerable&lt;OrderItem&gt; \n{\n private readonly List&lt;OrderItem&gt; _orderItems = new List&lt;OrderItem&gt;();\n\n void Add(OrderItem item)\n {\n _orderItems.Add(item)\n }\n\n //implement only the list members, which are required from your domain. \n //ie. sum items, calculate weight etc...\n\n private IEnumerator&lt;string&gt; Enumerator() {\n return _orderItems.GetEnumerator();\n }\n\n public IEnumerator&lt;string&gt; GetEnumerator() {\n return Enumerator();\n } \n}\n</code></pre>\n\n<p>Further still I'd probably abstract OrderItemCollection into IOrderItemCollection so I can swap my implementation of IOrderItemCollection over in the future in (I may prefer to use a different inner enumerable object such as Collection or more likley for perf use a Key Value Pair collection or Set.</p>\n" }, { "answer_id": 483590, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 2, "selected": false, "text": "<p>Use the type <code>List&lt;BusinessObject&gt;</code> where you have to declare a list of them. However,\nwhere you return a list of <code>BusinessObject</code>, consider returning <code>IEnumerable&lt;T&gt;</code>, <code>IList&lt;T&gt;</code> or <code>ReadOnlyCollection&lt;T&gt;</code> - i.e. return the weakest possible contract that satisfies the client. </p>\n\n<p>Where you want to \"add custom code\" to a list, code extension methods on the list type. Again, attach these methods to the weakest possible contract, e.g.</p>\n\n<pre><code>public static int SomeCount(this IEnumerable&lt;BusinessObject&gt; someList)\n</code></pre>\n\n<p>Of course, you can't and shouldn't add state with extension methods, so if you need to add a new property and a field behind it, use a subclass or better, a wrapper class to store this.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: ``` public class CollectionBase : IEnumerable ``` and then would derive their Business Object collections from that. ``` public class BusinessObjectCollection : CollectionBase ``` Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques: ``` public class BusinessObjectCollection : List<BusinessObject> ``` I do this because I like to have strongly typed names instead of just passing Lists around. What is **your** approach?
I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time. However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes. Basically, C# 3.0 allows any class that implements `IEnumerable` and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax: ``` var d = new Dictionary<string, int> { {"hello", 0}, {"the answer to life the universe and everything is:", 42} }; ``` The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection: ``` class c1 : IEnumerable { void Add(int x1, int x2, int x3) { //... } //... } ``` it would be possible to initialize it like so: ``` var x = new c1 { {1,2,3}, {4,5,6} } ``` This can be really useful if you need to create static tables of complex objects. For example, if you were just using `List<Customer>` and you wanted to create a static list of customer objects you would have to create it like so: ``` var x = new List<Customer> { new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"), new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"), new Customer("Michael Scott", "555-555-8769", "Scranton PA"), new Customer("Ali G", "", "Staines", "UK") } ``` However, if you use a customized collection, like this one: ``` class CustomerList : List<Customer> { public void Add(string name, string phoneNumber, string city, string stateOrCountry) { Add(new Customer(name, phoneNumber, city, stateOrCounter)); } } ``` You could then initialize the collection using this syntax: ``` var customers = new CustomerList { {"Scott Wisniewski", "555-555-5555", "Seattle", "WA"}, {"John Doe", "555-555-1234", "Los Angeles", "CA"}, {"Michael Scott", "555-555-8769", "Scranton PA"}, {"Ali G", "", "Staines", "UK"} } ``` This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex. That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database. My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use `List<T>` directly.
21,749
<p>I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window.</p> <p>If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight.</p> <p>I've tried setting the owner and the ParentWindow properties to the form it is related to:</p> <blockquote><code>dialog := TDialogForm.Create( parentForm );<br> dialog.ParentWindow := parentForm.Handle; </code></blockquote> <p>How can I fix this problem? What else should I be trying?</p> <p>Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order.</p> <p><b>Note</b>: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.</p>
[ { "answer_id": 21809, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<p>First of all, I am not completely sure I follow, you might need to provide some additional details to help us understand what is happening and what the problem is. I guess I am not sure I understand exactly what you're trying to accomplish and what the problem is.</p>\n\n<p>Second, you shouldn't need to set the dialog's parent since that is essentially what is happening with the call to Create (passing the parent). The dialogs you're describing sound like they could use some \"re-thinking\" a bit to be honest. Is this dialog to enter the properties of the image a child of the source window, or the WYSIWYG window?</p>\n" }, { "answer_id": 21915, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 1, "selected": false, "text": "<p>Is the dialog shown using ShowModal or just Show? You should probably set the PopupMode property correct of the your dialog. pmAuto would probably your best choice. Also see if you need to set the PopupParent property.</p>\n" }, { "answer_id": 21978, "author": "Marius", "author_id": 1008, "author_profile": "https://Stackoverflow.com/users/1008", "pm_score": 4, "selected": true, "text": "<p>I'd use this code... (Basically what Lars said)</p>\n\n<pre><code>dialog := TDialogForm.Create( parentForm );\ndialog.PopupParent := parentForm;\ndialog.PopupMode := pmExplicit; \ndialog.ShowModal();\n</code></pre>\n" }, { "answer_id": 22105, "author": "Andrew", "author_id": 1389, "author_profile": "https://Stackoverflow.com/users/1389", "pm_score": 0, "selected": false, "text": "<p>I'm not sure I quite understand what you are getting at, but here's a few things I can suggest you can try...</p>\n\n<ol>\n<li>This behaviour changes between different versions of Delphi. I'd suggest that this is due to the hoops they jumped through to support Windows Vista in Delphi 2007.</li>\n<li>If you are using Delphi 2007, try removing the line from the project source file that sets the Application.MainFormOnTaskBar boolean variable.</li>\n<li>With this removed, you should be able to use the various Form's BringToFront / SendToBack methods to achieve the Z-ordering that you are after.</li>\n</ol>\n\n<p>I suspect that what you've discovered has been discussed on <a href=\"http://www.stevetrefethen.com/blog/TheNewVCLPropertyTApplicationMainFormOnTaskbarInDelphi2007.aspx\" rel=\"nofollow noreferrer\">this link</a>\nOf course, I may have just missed your point entirely, so apologies in advance! </p>\n" }, { "answer_id": 29257, "author": "garethm", "author_id": 2219, "author_profile": "https://Stackoverflow.com/users/2219", "pm_score": 2, "selected": false, "text": "<p>I ultimately ended up finding the <a href=\"http://groups.google.com/group/borland.public.delphi.winapi/browse_frm/thread/36b3d5a199be91f4/7de8dab437f6aa1e?lnk=st&amp;q=delphi+main+form+modal+dialog+z-order#7de8dab437f6aa1e\" rel=\"nofollow noreferrer\">answer</a> using Google Groups. In a nutshell, all the modal dialogs need to have the following added to them:</p>\n\n<blockquote><pre><code>\nprocedure TDialogForm.CreateParams(var Params: TCreateParams);\nbegin\n inherited;\n Params.Style := Params.Style or WS_POPUP;\n Params.WndParent := (Owner as TWinControl).Handle;\nend;\n</code></pre></blockquote>\n\n<p>I'm guessing this does the equivalent of Lars' and Marius' answers in Delphi 7.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2219/" ]
I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window. If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight. I've tried setting the owner and the ParentWindow properties to the form it is related to: > `dialog := TDialogForm.Create( parentForm ); > > dialog.ParentWindow := parentForm.Handle;` How can I fix this problem? What else should I be trying? Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order. **Note**: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.
I'd use this code... (Basically what Lars said) ``` dialog := TDialogForm.Create( parentForm ); dialog.PopupParent := parentForm; dialog.PopupMode := pmExplicit; dialog.ShowModal(); ```
21,817
<p>The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?</p> <pre><code>public interface ITest { public static String test(); } </code></pre> <p>The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public &amp; abstract are permitted".</p>
[ { "answer_id": 21819, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 3, "selected": false, "text": "<p>Static methods are not instance methods. There's no instance context, therefore to implement it from the interface makes little sense.</p>\n" }, { "answer_id": 21823, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 4, "selected": false, "text": "<p>I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:</p>\n\n<pre><code>Math.add(2, 3);\n</code></pre>\n\n<p>If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.</p>\n" }, { "answer_id": 21826, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 5, "selected": false, "text": "<p>The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.</p>\n" }, { "answer_id": 21837, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.</p>\n" }, { "answer_id": 21845, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p>Perhaps a code example would help, I'm going to use C#, but you should be able to follow along.</p>\n\n<p>Lets pretend we have an interface called IPayable</p>\n\n<pre><code>public interface IPayable\n{\n public Pay(double amount);\n}\n</code></pre>\n\n<p>Now, we have two concrete classes that implement this interface:</p>\n\n<pre><code>public class BusinessAccount : IPayable\n{\n public void Pay(double amount)\n {\n //Logic\n }\n}\n\npublic class CustomerAccount : IPayable\n{\n public void Pay(double amount)\n {\n //Logic\n }\n}\n</code></pre>\n\n<p>Now, lets pretend we have a collection of various accounts, to do this we will use a generic list of the type IPayable</p>\n\n<pre><code>List&lt;IPayable&gt; accountsToPay = new List&lt;IPayable&gt;();\naccountsToPay.add(new CustomerAccount());\naccountsToPay.add(new BusinessAccount());\n</code></pre>\n\n<p>Now, we want to pay $50.00 to all those accounts:</p>\n\n<pre><code>foreach (IPayable account in accountsToPay)\n{\n account.Pay(50.00);\n}\n</code></pre>\n\n<p>So now you see how interfaces are incredibly useful. </p>\n\n<p>They are used on instantiated objects only. Not on static classes. </p>\n\n<p>If you had made pay static, when looping through the IPayable's in accountsToPay there would be no way to figure out if it should call pay on BusinessAcount or CustomerAccount.</p>\n" }, { "answer_id": 22497, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 7, "selected": true, "text": "<p>There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between</p>\n\n<pre><code>public interface Foo {\n public static int bar();\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public interface Foo {\n public static int bar() {\n ...\n }\n}\n</code></pre>\n\n<p>The first is impossible for the reasons that <a href=\"https://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface#21826\">Espo</a> mentions: you don't know which implementing class is the correct definition.</p>\n\n<p>Java <em>could</em> allow the latter; and in fact, starting in Java 8, it does!</p>\n" }, { "answer_id": 138340, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 4, "selected": false, "text": "<p>The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:</p>\n\n<pre><code>public class A {\n public method x() {...}\n}\npublic class B {\n public method x() {...}\n}\npublic class C extends A, B { ... }\n</code></pre>\n\n<p>Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.</p>\n\n<p>Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:</p>\n\n<pre><code>public interface A {\n public static method x() {...}\n}\npublic interface B {\n public static method x() {...}\n}\npublic class C implements A, B { ... }\n</code></pre>\n\n<p>Same problem here, what happen if you call C.x()?</p>\n" }, { "answer_id": 520094, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 2, "selected": false, "text": "<p>There's a very nice and concise answer to your question <a href=\"https://stackoverflow.com/questions/370962/why-cant-static-methods-be-abstract-in-java/370967#370967\">here</a>. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)</p>\n" }, { "answer_id": 18841163, "author": "Lenik", "author_id": 217071, "author_profile": "https://Stackoverflow.com/users/217071", "pm_score": 2, "selected": false, "text": "<p>It seems the static method in the interface might be supported in <a href=\"http://www.techempower.com/blog/2013/03/26/everything-about-java-8/\" rel=\"nofollow\">Java 8</a>, well, my solution is just define them in the inner class.</p>\n\n<pre><code>interface Foo {\n // ...\n class fn {\n public static void func1(...) {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>The same technique can also be used in annotations:</p>\n\n<pre><code>public @interface Foo {\n String value();\n\n class fn {\n public static String getValue(Object obj) {\n Foo foo = obj.getClass().getAnnotation(Foo.class);\n return foo == null ? null : foo.value();\n }\n }\n}\n</code></pre>\n\n<p>The inner class should always be accessed in the form of <code>Interface.fn...</code> instead of <code>Class.fn...</code>, then, you can get rid of ambiguous problem.</p>\n" }, { "answer_id": 19134923, "author": "Sankar", "author_id": 1690448, "author_profile": "https://Stackoverflow.com/users/1690448", "pm_score": 0, "selected": false, "text": "<p>Illegal combination of modifiers : static and abstract</p>\n\n<p>If a member of a class is declared as static, it can be used with its class name which is confined to that class, without creating an object.</p>\n\n<p>If a member of a class is declared as abstract, you need to declare the class as abstract and you need to provide the implementation of the abstract member in its inherited class (Sub-Class).</p>\n\n<p>You need to provide an implementation to the abstract member of a class in sub-class where you are going to change the behaviour of static method, also declared as abstract which is a confined to the base class, which is not correct</p>\n" }, { "answer_id": 20591367, "author": "ip_x", "author_id": 1705343, "author_profile": "https://Stackoverflow.com/users/1705343", "pm_score": 0, "selected": false, "text": "<p>Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .</p>\n" }, { "answer_id": 22711415, "author": "Anandaraja_Srinivasan", "author_id": 2978567, "author_profile": "https://Stackoverflow.com/users/2978567", "pm_score": 3, "selected": false, "text": "<p>Now Java8 allows us to define even Static Methods in Interface.</p>\n\n<pre><code>interface X {\n static void foo() {\n System.out.println(\"foo\");\n }\n}\n\nclass Y implements X {\n //...\n}\n\npublic class Z {\n public static void main(String[] args) {\n X.foo();\n // Y.foo(); // won't compile because foo() is a Static Method of X and not Y\n }\n}\n</code></pre>\n\n<p>Note: Methods in Interface are still public abstract by default if we don't explicitly use the keywords default/static to make them Default methods and Static methods resp.</p>\n" }, { "answer_id": 35220948, "author": "Kumar Abhishek", "author_id": 5772982, "author_profile": "https://Stackoverflow.com/users/5772982", "pm_score": 1, "selected": false, "text": "<p>Java 8 Had changed the world you can have static methods in interface but it forces you to provide implementation for that.</p>\n\n<pre><code>public interface StaticMethodInterface {\npublic static int testStaticMethod() {\n return 0;\n}\n\n/**\n * Illegal combination of modifiers for the interface method\n * testStaticMethod; only one of abstract, default, or static permitted\n * \n * @param i\n * @return\n */\n// public static abstract int testStaticMethod(float i);\n\ndefault int testNonStaticMethod() {\n return 1;\n}\n\n/**\n * Without implementation.\n * \n * @param i\n * @return\n */\nint testNonStaticMethod(float i);\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 54805877, "author": "Ishara", "author_id": 9433614, "author_profile": "https://Stackoverflow.com/users/9433614", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>With <strong>Java 8</strong>, interfaces can now have static methods.</p>\n</blockquote>\n\n<p>For example, Comparator has a static naturalOrder() method.</p>\n\n<p>The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare \"default\" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? ``` public interface ITest { public static String test(); } ``` The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between ``` public interface Foo { public static int bar(); } ``` and ``` public interface Foo { public static int bar() { ... } } ``` The first is impossible for the reasons that [Espo](https://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface#21826) mentions: you don't know which implementing class is the correct definition. Java *could* allow the latter; and in fact, starting in Java 8, it does!
21,848
<p>There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.</p> <p>Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch?</p> <p>Thanks for all the (quick) answers! They're all good.</p>
[ { "answer_id": 21897, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 3, "selected": false, "text": "<p>This is relatively easy:</p>\n\n<pre><code>git checkout -b fake_master master # fake_master now points to the same commit as master\ngit branch -D master # get rid of incorrect master\ngit checkout -b master real_master # master now points to your actual master\ngit checkout master # optional -- switch on to your master branch\n</code></pre>\n" }, { "answer_id": 21905, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 4, "selected": false, "text": "<p>Start on <code>master</code>, create a branch called <code>in-progress</code>, then reset <code>master</code> to an earlier commit.</p>\n\n<pre><code>$ git branch in-progress\n$ git reset --hard HEAD^\n</code></pre>\n" }, { "answer_id": 21932, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master:</p>\n\n<pre><code>git branch -m master crap_work\ngit branch -m previous_master master\n</code></pre>\n" }, { "answer_id": 24012, "author": "Brian Riehman", "author_id": 2063, "author_profile": "https://Stackoverflow.com/users/2063", "pm_score": 5, "selected": false, "text": "<p>I think you should consider a different development strategy to prevent issues like this. One that seems to work best for me is to never do development directly on my master branch. Regardless of the changes I'm making, I always create a new branch for new code:</p>\n\n<pre>\ngit checkout -b topic/topic_name master\n</pre>\n\n<p>From there, I can push out the changes to public repositories:</p>\n\n<pre>\ngit push pu topic/topic_name\n</pre>\n\n<p>or eventually just merge it back in with my master branch:</p>\n\n<pre>\ngit checkout master && git merge topic/topic_name\n</pre>\n\n<p>If you truly need to go back to an older point in time and set that as your master, you can rename the current branch to something else and then check out an older version to be your master:</p>\n\n<pre>\n git branch -m master junk\n git co -b master old_sha1_value\n</pre>\n" }, { "answer_id": 12021187, "author": "Penghe Geng", "author_id": 814145, "author_profile": "https://Stackoverflow.com/users/814145", "pm_score": 0, "selected": false, "text": "<p>This will set your master to any point in one step:</p>\n\n<pre><code>git checkout -B master new_point\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427/" ]
There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch. Some ways this could be asked/solved: How do I rename my master branch to something else and then rename something else to master? How do I back up master and then cause all commits I've backed up past to be on a different branch? Thanks for all the (quick) answers! They're all good.
In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master: ``` git branch -m master crap_work git branch -m previous_master master ```
21,877
<p>What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. </p> <p>I have done this by using </p> <pre><code> Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); </code></pre> <p>but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?</p>
[ { "answer_id": 21883, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 0, "selected": false, "text": "<p>We actually just released some classes that help with exactly this kind of thing:</p>\n\n<p><a href=\"http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449\" rel=\"nofollow noreferrer\">http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449</a></p>\n\n<p>Specifically, check out the DatabaseImage sample.</p>\n" }, { "answer_id": 21885, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>You can BASE64 encode the content of the image directly into the SRC attribute, however, I believe only Firefox will parse this back into an image.</p>\n\n<p>What I typically do is a create a very lightweight HTTPHandler to serve the images:</p>\n\n<pre><code>using System;\nusing System.Web;\n\nnamespace Example\n{ \n public class GetImage : IHttpHandler\n {\n\n public void ProcessRequest(HttpContext context)\n {\n if (context.Request.QueryString(\"id\") != null)\n {\n Blob = GetBlobFromDataBase(id);\n context.Response.Clear();\n context.Response.ContentType = \"image/pjpeg\";\n context.Response.BinaryWrite(Blob);\n context.Response.End();\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n }\n}\n</code></pre>\n\n<p>You can reference this directly in your img tag:</p>\n\n<pre><code>&lt;img src=\"GetImage.ashx?id=111\"/&gt;\n</code></pre>\n\n<p>Or, you could even create a server control that does it for you:</p>\n\n<pre><code>using System;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Example.WebControl\n{\n\n [ToolboxData(\"&lt;{0}:DatabaseImage runat=server&gt;&lt;/{0}:DatabaseImage&gt;\")]\n public class DatabaseImage : Control\n {\n\n public int DatabaseId\n {\n get\n {\n if (ViewState[\"DatabaseId\" + this.ID] == null)\n return 0;\n else\n return ViewState[\"DataBaseId\"];\n }\n set\n {\n ViewState[\"DatabaseId\" + this.ID] = value;\n }\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(\"&lt;img src='getImage.ashx?id=\" + this.DatabaseId + \"'/&gt;\");\n base.RenderContents(output);\n }\n }\n}\n</code></pre>\n\n<p>This could be used like</p>\n\n<pre><code>&lt;cc:DatabaseImage id=\"db1\" DatabaseId=\"123\" runat=\"server/&gt;\n</code></pre>\n\n<p>And of course, you could set the databaseId in the codebehind as needed.</p>\n" }, { "answer_id": 21887, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 5, "selected": true, "text": "<p>Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:</p>\n\n<pre><code>public class ImageHandler : IHttpHandler\n{\n\n public void ProcessRequest(HttpContext context)\n {\n using(Image image = GetImage(context.Request.QueryString[\"ID\"]))\n { \n context.Response.ContentType = \"image/jpeg\";\n image.Save(context.Response.OutputStream, ImageFormat.Jpeg);\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>Now just implement the GetImage method to load the image with the given ID, and you can use</p>\n\n<pre><code>&lt;asp:Image runat=\"server\" ImageUrl=\"~/Image.ashx?ID=myImageId\" /&gt; \n</code></pre>\n\n<p>to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).</p>\n" }, { "answer_id": 21889, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<p>Add the code to a handler to return the image bytes with the appropriate mime-type. Then you can just add the url to your handler like it is an image. For example: </p>\n\n<pre><code>&lt;img src=\"myhandler.ashx?imageid=5\"&gt; \n</code></pre>\n\n<p>Make sense?</p>\n" }, { "answer_id": 2310342, "author": "Taliesin", "author_id": 124968, "author_profile": "https://Stackoverflow.com/users/124968", "pm_score": 3, "selected": false, "text": "<p>You don't want to be serving blobs from a database without implementing client side caching. </p>\n\n<p>You will need to handle the following headers to support client side caching:</p>\n\n<ul>\n<li>ETag</li>\n<li>Expires</li>\n<li>Last-Modified</li>\n<li>If-Match</li>\n<li>If-None-Match</li>\n<li>If-Modified-Since</li>\n<li>If-Unmodified-Since</li>\n<li>Unless-Modified-Since </li>\n</ul>\n\n<p>For an http handler that does this, check out:\n<a href=\"http://code.google.com/p/talifun-web/wiki/StaticFileHandler\" rel=\"nofollow noreferrer\">http://code.google.com/p/talifun-web/wiki/StaticFileHandler</a></p>\n\n<p>It has a nice helper to serve the content. It should be easy to pass in database stream to it. It also does server side caching which should help alleviate some of the pressure on the database. </p>\n\n<p>If you ever decide to serve streaming content from the database, pdfs or large files the handler also supports 206 partial requests. </p>\n\n<p>It also supports gzip and deflate compression.</p>\n\n<p>These file types will benefit from further compression:</p>\n\n<ul>\n<li>css, js, htm, html, swf, xml, xslt, txt</li>\n<li>doc, xls, ppt </li>\n</ul>\n\n<p>There are some file types that will not benefit from further compression:</p>\n\n<ul>\n<li>pdf (causes problems with certain versions in IE and it is usually well compressed)</li>\n<li>png, jpg, jpeg, gif, ico</li>\n<li>wav, mp3, m4a, aac (wav is often compressed)</li>\n<li>3gp, 3g2, asf, avi, dv, flv, mov, mp4, mpg, mpeg, wmv</li>\n<li>zip, rar, 7z, arj </li>\n</ul>\n" }, { "answer_id": 19257098, "author": "Fidel Orozco", "author_id": 1260174, "author_profile": "https://Stackoverflow.com/users/1260174", "pm_score": 2, "selected": false, "text": "<p>Using ASP.Net with MVC this is pretty forward easy. You code a controller with a method like this:</p>\n\n<pre><code>public FileContentResult Image(int id)\n{\n //Get data from database. The Image BLOB is return like byte[]\n SomeLogic ItemsDB= new SomeLogic(\"[ImageId]=\" + id.ToString());\n FileContentResult MyImage = null;\n if (ItemsDB.Count &gt; 0)\n {\n MyImage= new FileContentResult(ItemsDB.Image, \"image/jpg\");\n }\n\n return MyImage;\n}\n</code></pre>\n\n<p>In your ASP.NET Web View or in this example, in your ASP.NET Web Form you can fill an Image Control with the URL to your method like this:</p>\n\n<pre><code> this.imgExample.ImageUrl = \"~/Items/Image/\" + MyItem.Id.ToString();\n this.imgExample.Height = new Unit(120);\n this.imgExample.Width = new Unit(120);\n</code></pre>\n\n<p>Voilá. Not HttpModules hassle was needed.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932/" ]
What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. I have done this by using ``` Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); ``` but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?
Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this: ``` public class ImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { using(Image image = GetImage(context.Request.QueryString["ID"])) { context.Response.ContentType = "image/jpeg"; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } public bool IsReusable { get { return true; } } } ``` Now just implement the GetImage method to load the image with the given ID, and you can use ``` <asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" /> ``` to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
21,879
<p>I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are <a href="http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/" rel="noreferrer">here</a> if you're interested in helping out). </p> <p>My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??</p> <p>What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?</p> <p>Thank!</p>
[ { "answer_id": 21962, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "<p>Here's how my school did it:</p>\n\n<pre><code>base:\n algebra\n trigonometry\n analytic geometry\n\ntrack 1 track 2 track 3\n calc 1 linear algebra statistics\n calc 2 discrete math 1\n calc 3 (multivariable) discrete math 2\n differential equations \n</code></pre>\n\n<p>The base courses were a prerequisite for everything, the tracks were independent and taken in order.</p>\n\n<p>So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these:</p>\n\n<pre><code>algebra, discrete\nalgebra, linear algebra, discrete (if you want to cover matrices first)\n</code></pre>\n\n<p>HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!</p>\n" }, { "answer_id": 22052, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 1, "selected": false, "text": "<p>Usually, an overview of each field is a good thing to have when looking at any topic, but it's rare to have a genuine dependence the way we'd think of it. Algebra is always needed. I can't think of a time I've needed any trigonometry. (except to expand it with new things from calculus) I'm even quite sure people wouldn't agree on what a dependency graph would look like, or even in which field each topic belongs.</p>\n\n<p>I think the right way to approach it is to just collect a wide range of topics from all of branches and read them in whatever order you feel like, recording dependencies between topics as you go. (respecting them, or not, as you please.) This should have the far more important property of <strong>keeping the student interested</strong>.</p>\n\n<p>It's also my experience that if something just has you stumped, just mark it and set it aside for later.</p>\n\n<p>As for my school, well, it was similar to Harrison's:</p>\n\n<ul>\n<li>cominatorics,</li>\n<li>linear algebra,</li>\n<li>calculus,</li>\n<li>numerical analysis (error analysis in particular.)</li>\n<li>logic,</li>\n<li>statistics, (with operations research / queueing therory.)</li>\n</ul>\n" }, { "answer_id": 76938, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 3, "selected": false, "text": "<p>My advice is to lazily evaluate your own dependency tree. Study something you think is interesting -- when you hit something you don't know, go learn about it. </p>\n\n<p>I always find it easier to learn something new when I already have a context in which I want to use it.</p>\n" }, { "answer_id": 90607, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 2, "selected": false, "text": "<p>This is a particularly cool site for visualizing how everything in the math world fits together:</p>\n\n<p><a href=\"http://www.math.niu.edu/Papers/Rusin/known-math/index/mathmap.html\" rel=\"nofollow noreferrer\">http://www.math.niu.edu/Papers/Rusin/known-math/index/mathmap.html</a></p>\n\n<p>It's also got short summaries of many subfields you've probably never heard of, which is fun.</p>\n" }, { "answer_id": 90617, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 1, "selected": false, "text": "<p>Take a look at <a href=\"http://mathworld.wolfram.com/\" rel=\"nofollow noreferrer\">MathWorld</a>. Browse topics or search for one, you'll get your position in the overall tree.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1588/" ]
I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are [here](http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/) if you're interested in helping out). My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it?? What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")? Thank!
Here's how my school did it: ``` base: algebra trigonometry analytic geometry track 1 track 2 track 3 calc 1 linear algebra statistics calc 2 discrete math 1 calc 3 (multivariable) discrete math 2 differential equations ``` The base courses were a prerequisite for everything, the tracks were independent and taken in order. So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these: ``` algebra, discrete algebra, linear algebra, discrete (if you want to cover matrices first) ``` HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!
21,938
<p>Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.</p>
[ { "answer_id": 21942, "author": "Philippe", "author_id": 920, "author_profile": "https://Stackoverflow.com/users/920", "pm_score": 3, "selected": false, "text": "<p>Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.</p>\n\n<p>In conclusion, you will catch both <code>IOException</code> and <code>NullPointerException</code> with a generic <code>Exception</code>, but the way your program should react is probably different.</p>\n" }, { "answer_id": 21943, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.</p>\n" }, { "answer_id": 21946, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 0, "selected": false, "text": "<p>Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.</p>\n" }, { "answer_id": 21947, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 5, "selected": false, "text": "<p>Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.</p>\n\n<p>My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.</p>\n\n<p>If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.</p>\n" }, { "answer_id": 21948, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<p>The point is twofold I think.</p>\n\n<p>Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.</p>\n\n<p>Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.</p>\n" }, { "answer_id": 21950, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 8, "selected": true, "text": "<p>Obviously this is one of those questions where the only real answer is \"it depends.\"</p>\n\n<p>The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.</p>\n\n<p>The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like \"OutOfMemoryException\" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.</p>\n\n<p>The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:</p>\n\n<pre><code>try { \n something(); \n} catch (Exception ex) {}\n</code></pre>\n\n<p>or this in Python:</p>\n\n<pre><code>try:\n something()\nexcept:\n pass\n</code></pre>\n\n<p>Because these can be some of the hardest issues to track down.</p>\n\n<p>A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.</p>\n" }, { "answer_id": 21955, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 4, "selected": false, "text": "<p>Yes! (except at the \"top\" of your application)</p>\n\n<p>By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is <strong>a recoverable situation</strong>. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these. </p>\n\n<p>In a well organised application, these unrecoverable problems should be handled high up the stack.</p>\n\n<p>In addition, as code evolves, you don't want your function to catch a new exception that is added <em>in the future</em> to a called method.</p>\n" }, { "answer_id": 21959, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 4, "selected": false, "text": "<p>In my opinion you should catch all exceptions you <strong>expect</strong>, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.</p>\n\n<p>Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.</p>\n" }, { "answer_id": 21995, "author": "jammycakes", "author_id": 886, "author_profile": "https://Stackoverflow.com/users/886", "pm_score": 2, "selected": false, "text": "<p>The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should <strong>not</strong> be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.</p>\n\n<p>To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.</p>\n\n<p>Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the \"very uncommon\" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.</p>\n\n<p>So in general, catching generic exceptions is bad unless you are 100% sure that you know <strong>exactly</strong> which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.</p>\n\n<p>A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.</p>\n\n<p>(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)</p>\n" }, { "answer_id": 22234, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 3, "selected": false, "text": "<p>There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.</p>\n" }, { "answer_id": 24032373, "author": "Tzen", "author_id": 766096, "author_profile": "https://Stackoverflow.com/users/766096", "pm_score": 0, "selected": false, "text": "<p>Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.</p>\n\n<p>Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.</p>\n" }, { "answer_id": 28156836, "author": "slashdottir", "author_id": 901444, "author_profile": "https://Stackoverflow.com/users/901444", "pm_score": 2, "selected": false, "text": "<p>I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with. </p>\n" }, { "answer_id": 48695129, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.</p>\n\n<p>The second, however, is to stop your program from breaking when it could continue. These cases are:</p>\n\n<ul>\n<li>The top of all threads (By default, exceptions will vanish without a trace!)</li>\n<li>Inside a main processing loop that you expect to never exit</li>\n<li>Inside a Loop processing a list of objects where one failure shouldn't stop others</li>\n<li>Top of the \"main\" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.</li>\n<li>If you have a \"Runner\" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.</li>\n</ul>\n\n<p>These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.</p>\n" }, { "answer_id": 53328948, "author": "Peter Griffin", "author_id": 3839722, "author_profile": "https://Stackoverflow.com/users/3839722", "pm_score": -1, "selected": false, "text": "<p>For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.</p>\n\n<p>I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.</p>\n\n<p>I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.</p>\n\n<p>Before:</p>\n\n<pre><code> catch (final RemoteException exc)\n {\n exc.printStackTrace();\n }\n catch (final IntentSender.SendIntentException exc)\n {\n exc.printStackTrace();\n }\n catch (final IabHelper.IabAsyncInProgressException exc)\n {\n exc.printStackTrace();\n }\n catch (final NullPointerException exc)\n {\n exc.printStackTrace();\n }\n catch (final IllegalStateException exc)\n {\n exc.printStackTrace();\n }\n</code></pre>\n\n<p>After:</p>\n\n<pre><code> catch (final Exception exc)\n {\n exc.printStackTrace();\n }\n</code></pre>\n" }, { "answer_id": 54563389, "author": "Beefster", "author_id": 5079779, "author_profile": "https://Stackoverflow.com/users/5079779", "pm_score": 1, "selected": false, "text": "<p>Unpopular opinion: Not really.</p>\n\n<p>Catch all of the errors you can meaningfully recover from. Sometimes that's all of them.</p>\n\n<p>In my experience, it matters more <em>where</em> the exception came from than which exception is actually thrown. If you keep your exceptions in tight quarters, you won't usually be swallowing anything that would otherwise be useful. Most of the information encoded in the type of an error is ancillary information, so you generally end up effectively catching <em>all</em> of them anyway (but you now have to look up the API docs to get the total set of possible Exceptions).</p>\n\n<p>Keep in mind that some exceptions that should bubble up to the top in almost every case, such as Python's <code>KeyboardInterrupt</code> and <code>SystemExit</code>. Fortunately for Python, these are kept in a separate branch of the exception hierarchy, so you can let them bubble up by catching <code>Exception</code>. A well-designed exception hierarchy makes this type of thing really straightforward.</p>\n\n<p>The main time catching general exceptions will cause serious problems is when dealing with resources that need to be cleaned up (perhaps in a <code>finally</code> clause), since a catch-all handler can easily miss that sort of thing. Fortunately this isn't really an issue for languages with <code>defer</code>, constructs like Python's <code>with</code>, or RAII in C++ and Rust.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1731/" ]
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
Obviously this is one of those questions where the only real answer is "it depends." The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch. The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here. The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java: ``` try { something(); } catch (Exception ex) {} ``` or this in Python: ``` try: something() except: pass ``` Because these can be some of the hardest issues to track down. A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
21,961
<pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime("01-31-2009", "%m-%d-%Y") (2009, 1, 31, 0, 0, 0, 5, 31, -1) &gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233378000.0 &gt;&gt;&gt; 60*60*24 # seconds in a day 86400 &gt;&gt;&gt; 1233378000.0 / 86400 14275.208333333334 </code></pre> <p><code>time.mktime</code> should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
[ { "answer_id": 21973, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "<pre><code>mktime(...)\n mktime(tuple) -&gt; floating point number\n\n Convert a time tuple in local time to seconds since the Epoch.\n</code></pre>\n\n<p>local time... fancy that.</p>\n\n<p>The time tuple:</p>\n\n<pre><code>The other representation is a tuple of 9 integers giving local time.\nThe tuple items are:\n year (four digits, e.g. 1998)\n month (1-12)\n day (1-31)\n hours (0-23)\n minutes (0-59)\n seconds (0-59)\n weekday (0-6, Monday is 0)\n Julian day (day in the year, 1-366)\n DST (Daylight Savings Time) flag (-1, 0 or 1)\nIf the DST flag is 0, the time is given in the regular time zone;\nif it is 1, the time is given in the DST time zone;\nif it is -1, mktime() should guess based on the date and time.\n</code></pre>\n\n<p>Incidentally, we seem to be 6 hours apart:</p>\n\n<pre><code>&gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233356400.0\n&gt;&gt;&gt; (1233378000.0 - 1233356400)/(60*60)\n6.0\n</code></pre>\n" }, { "answer_id": 21974, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "<p>Interesting. I don't know, but I did try this:</p>\n\n<pre><code>&gt;&gt;&gt; now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))\n&gt;&gt;&gt; tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))\n&gt;&gt;&gt; tomorrow - now\n86400.0\n</code></pre>\n\n<p>which is what you expected. My guess? Maybe some time correction was done since the epoch. This could be only a few seconds, something like a leap year. I think I heard something like this before, but can't remember exactly how and when it is done...</p>\n" }, { "answer_id": 21975, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 3, "selected": false, "text": "<p>Short answer: Because of timezones.</p>\n\n<p>The Epoch is in UTC.</p>\n\n<p>For example, I'm on IST (Irish Standard Time) or UTC+1. <a href=\"https://docs.python.org/3/library/time.html#time.gmtime\" rel=\"nofollow noreferrer\"><code>time.mktime()</code></a> is relative to my timezone, so on my system this refers to</p>\n\n<pre><code>&gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233360000.0\n</code></pre>\n\n<p>Because you got the result 1233378000, that would suggest that you're 5 hours behind me</p>\n\n<pre><code>&gt;&gt;&gt; (1233378000 - 1233360000) / (60*60) \n5\n</code></pre>\n\n<p>Have a look at the <a href=\"https://docs.python.org/3/library/time.html#time.gmtime\" rel=\"nofollow noreferrer\"><code>time.gmtime()</code></a> function which works off UTC.</p>\n" }, { "answer_id": 22021, "author": "Daniel Benamy", "author_id": 2427, "author_profile": "https://Stackoverflow.com/users/2427", "pm_score": 2, "selected": false, "text": "<p>Phil's answer really solved it, but I'll elaborate a little more. Since the epoch is in UTC, if I want to compare other times to the epoch, I need to interpret them as UTC as well.</p>\n\n<pre><code>&gt;&gt;&gt; calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))\n1233360000\n&gt;&gt;&gt; 1233360000 / (60*60*24)\n14275\n</code></pre>\n\n<p>By converting the time tuple to a timestamp treating is as UTC time, I get a number which <em>is</em> evenly divisible by the number of seconds in a day.</p>\n\n<p>I can use this to convert a date to a days-from-the-epoch representation which is what I'm ultimately after.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2427/" ]
``` >>> import time >>> time.strptime("01-31-2009", "%m-%d-%Y") (2009, 1, 31, 0, 0, 0, 5, 31, -1) >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233378000.0 >>> 60*60*24 # seconds in a day 86400 >>> 1233378000.0 / 86400 14275.208333333334 ``` `time.mktime` should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?
Short answer: Because of timezones. The Epoch is in UTC. For example, I'm on IST (Irish Standard Time) or UTC+1. [`time.mktime()`](https://docs.python.org/3/library/time.html#time.gmtime) is relative to my timezone, so on my system this refers to ``` >>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233360000.0 ``` Because you got the result 1233378000, that would suggest that you're 5 hours behind me ``` >>> (1233378000 - 1233360000) / (60*60) 5 ``` Have a look at the [`time.gmtime()`](https://docs.python.org/3/library/time.html#time.gmtime) function which works off UTC.
21,987
<p>I am developing an application that controls an Machine.<br/> When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.</p> <p>There's one little annoyance using the <code>FlashWindowEx</code> function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing).</p> <p><a href="https://i.stack.imgur.com/GOS2r.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GOS2r.gif" alt="" /></a></p> <pre><code>[Flags] public enum FlashMode { /// &lt;summary&gt; /// Stop flashing. The system restores the window to its original state. /// &lt;/summary&gt; FLASHW_STOP = 0, /// &lt;summary&gt; /// Flash the window caption. /// &lt;/summary&gt; FLASHW_CAPTION = 1, /// &lt;summary&gt; /// Flash the taskbar button. /// &lt;/summary&gt; FLASHW_TRAY = 2, /// &lt;summary&gt; /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// &lt;/summary&gt; FLASHW_ALL = 3, /// &lt;summary&gt; /// Flash continuously, until the FLASHW_STOP flag is set. /// &lt;/summary&gt; FLASHW_TIMER = 4, /// &lt;summary&gt; /// Flash continuously until the window comes to the foreground. /// &lt;/summary&gt; FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } </code></pre> <p>In my case I use <code>FLASHW_TRAY</code> to start flashing and <code>FLASHW_STOP</code> to stop the flashing.</p> <p>Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?</p>
[ { "answer_id": 23285, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 4, "selected": true, "text": "<p>Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use <code>FLASHW_STOP</code>, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered <em>which</em> window was trying to get her attention. Keeping the button coloured keeps that information available.</p>\n" }, { "answer_id": 37615, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 0, "selected": false, "text": "<p>If that's the expected functionality I think it's not so useful, at least there should be a reset.</p>\n<p>I fixed it now just using the <code>FLASHW_ALL | FLASHW_TIMERNOFG</code> combination.</p>\n" }, { "answer_id": 22200798, "author": "norekhov", "author_id": 2794542, "author_profile": "https://Stackoverflow.com/users/2794542", "pm_score": 2, "selected": false, "text": "<p>Here's an error:</p>\n\n<blockquote>\n <p>fInfo.uCount = UInt32.MaxValue;</p>\n</blockquote>\n\n<p>You should set fInfo.uCount to zero when calling with FLASHW_STOP parameter. \nOtherwise when you try to call stop when taskbar button is active it will stay active.</p>\n\n<p>You can check a note about undefined behavior here:\n<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348(v=vs.85).aspx</a></p>\n\n<p>I know that's an old post but it can help other people to solve this problem fast.</p>\n" }, { "answer_id": 36740046, "author": "Sean", "author_id": 4143886, "author_profile": "https://Stackoverflow.com/users/4143886", "pm_score": -1, "selected": false, "text": "<p>Just set uCount to 0 to stop the flashing.</p>\n" }, { "answer_id": 67506261, "author": "flyguille", "author_id": 2784000, "author_profile": "https://Stackoverflow.com/users/2784000", "pm_score": -1, "selected": false, "text": "<p>fixed with uCount=0</p>\n<p>if (flags = FLASHW_STOP) { .uCount = 0 } else { .uCount = 800 }</p>\n<p>The misbehaviour is that if you are calling flashw_stop from a click/kb event from inside the Window itself, the taskbar button stay colored if a that moment was colored.</p>\n<p>With that new logic line, done.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/21987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090/" ]
I am developing an application that controls an Machine. When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing. There's one little annoyance using the `FlashWindowEx` function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing). [![](https://i.stack.imgur.com/GOS2r.gif)](https://i.stack.imgur.com/GOS2r.gif) ``` [Flags] public enum FlashMode { /// <summary> /// Stop flashing. The system restores the window to its original state. /// </summary> FLASHW_STOP = 0, /// <summary> /// Flash the window caption. /// </summary> FLASHW_CAPTION = 1, /// <summary> /// Flash the taskbar button. /// </summary> FLASHW_TRAY = 2, /// <summary> /// Flash both the window caption and taskbar button. /// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags. /// </summary> FLASHW_ALL = 3, /// <summary> /// Flash continuously, until the FLASHW_STOP flag is set. /// </summary> FLASHW_TIMER = 4, /// <summary> /// Flash continuously until the window comes to the foreground. /// </summary> FLASHW_TIMERNOFG = 12 } public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) { FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = (UInt32)fm; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; return FlashWindowEx(ref fInfo); } [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } ``` In my case I use `FLASHW_TRAY` to start flashing and `FLASHW_STOP` to stop the flashing. Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?
Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use `FLASHW_STOP`, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered *which* window was trying to get her attention. Keeping the button coloured keeps that information available.
22,001
<p>I'm learning objective-C and Cocoa. In the Apple tutorial I'm working through there's a side note that says: </p> <blockquote> <p><code>IBOutlet</code> is a null-defined macro, which the C preprocessor removes at compile time.</p> </blockquote> <p>I'm curious - what's a null-defined macro?</p>
[ { "answer_id": 22003, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<pre><code>#define IBOutlet\n</code></pre>\n\n<p>Whenever IBOutlet is used in program text, it will be replaced with nothing at all.</p>\n" }, { "answer_id": 22455, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 3, "selected": false, "text": "<p>FYI, in this particular case, the reason the <code>IBOutlet</code> even exists is simply so that Interface Builder can parse the source file and glean bits of understanding from it. It's a clue (well, a bit stronger than a clue) that the variable preceded by <code>IBOutlet</code> should show up as an Outlet in Interface Builder when designing your UIs.</p>\n" }, { "answer_id": 45364, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 3, "selected": false, "text": "<p>A null-defined macro is a macro which will be replaced by nothing (will be removed) by the preprocessor. It's role is to give a hint about something in code, such as:</p>\n\n<pre>\n#define IN\n#define OUT\n#define INOUT\n\nint myFunction(IN char *name, INOUT char *address, OUT char *phone);\n</pre>\n\n<p>This declaration suggests that <code>name</code> is a input variable for the function, <code>address</code> is both input and output, <code>phone</code> is an output variable.</p>\n" }, { "answer_id": 146270, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 0, "selected": false, "text": "<p>Also - if you're unsure how anything is defined - command double-click it and Xcode will open the definition in the original source file.</p>\n" }, { "answer_id": 146273, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 0, "selected": false, "text": "<p>Oh and while I'm at it. Option double click will (attempt to) open up the documentation for the double clicked symbol.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm learning objective-C and Cocoa. In the Apple tutorial I'm working through there's a side note that says: > > `IBOutlet` is a null-defined macro, which the C preprocessor removes at compile time. > > > I'm curious - what's a null-defined macro?
``` #define IBOutlet ``` Whenever IBOutlet is used in program text, it will be replaced with nothing at all.
22,012
<p>My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.</p> <p>Is there a way to tell the runtime that the dlls are in a seperate subfolder?</p>
[ { "answer_id": 22022, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>&lt;probing&gt;</code> element in a manifest file to tell the Runtime to look in different directories for its assembly files.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/823z9h8w.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/823z9h8w.aspx</a></p>\n\n<p>e.g.:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;runtime&gt;\n &lt;assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\"&gt;\n &lt;probing privatePath=\"bin;bin2\\subbin;bin3\"/&gt;\n &lt;/assemblyBinding&gt;\n &lt;/runtime&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 22026, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 5, "selected": true, "text": "<p>One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.</p>\n\n<pre><code>AppDomain currentDomain = AppDomain.CurrentDomain;\ncurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);\n</code></pre>\n\n<p>Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.</p>\n\n<p>EDIT:</p>\n\n<p>Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.</p>\n" }, { "answer_id": 22029, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 1, "selected": false, "text": "<p>You can use the <code>&lt;codeBase&gt;</code> element found in the application configuration file. More information on \"<a href=\"http://msdn.microsoft.com/en-us/library/15hyw9x3.aspx\" rel=\"nofollow noreferrer\">Locating the Assembly through Codebases or Probing</a>\".</p>\n\n<blockquote>\n <p>Well, the loaded assembly doesn't have\n an application configuration file.</p>\n</blockquote>\n\n<p>Well if you know the specific folders at runtime you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx\" rel=\"nofollow noreferrer\">Assembly.LoadFrom</a>. </p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374/" ]
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in a seperate subfolder?
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event. ``` AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); ``` Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method. EDIT: Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
22,135
<p>I am trying to implement NTLM authentication on one of our internal sites and everything is working. The one piece of the puzzle I do not have is how to take the information from NTLM and authenticate with Active Directory.</p> <p>There is a <a href="http://www.innovation.ch/personal/ronald/ntlm.html" rel="nofollow noreferrer">good description of NTLM</a> and the <a href="http://us1.samba.org/samba/docs/man/Samba-Developers-Guide/pwencrypt.html" rel="nofollow noreferrer">encryption used for the passwords</a>, which I used to implement this, but I am not sure of how to verify if the user's password is valid.</p> <p>I am using ColdFusion but a solution to this problem can be in any language (Java, Python, PHP, etc).</p> <p>Edit:</p> <p>I am using ColdFusion on Redhat Enterprise Linux. Unfortunately we cannot use IIS to manage this and instead have to write or use a 3rd party tool for this.</p> <hr> <p><strong>Update</strong> - <em>I got this working and here is what I did</em></p> <p>I went with the <a href="http://jcifs.samba.org/" rel="nofollow noreferrer">JCIFS library from samba.org.</a></p> <blockquote> <p>Note that the method below will only work with NTLMv1 and <strong>DOES NOT</strong> work with NTLMv2. If you are unable to use NTLMv1 you can try <a href="http://www.ioplex.com/jespa.html" rel="nofollow noreferrer">Jespa</a>, which supports NTLMv2 but is not open source, or you can use <a href="http://spnego.sourceforge.net" rel="nofollow noreferrer">Kerberos/SPNEGO.</a></p> </blockquote> <p>Here is my web.xml:</p> <pre><code>&lt;web-app&gt; &lt;display-name&gt;Ntlm&lt;/display-name&gt; &lt;filter&gt; &lt;filter-name&gt;NtlmHttpFilter&lt;/filter-name&gt; &lt;filter-class&gt;jcifs.http.NtlmHttpFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;jcifs.http.domainController&lt;/param-name&gt; &lt;param-value&gt;dc01.corp.example.com&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;jcifs.smb.client.domain&lt;/param-name&gt; &lt;param-value&gt;CORP.EXAMPLE.COM&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;NtlmHttpFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/admin/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;/web-app&gt; </code></pre> <p>Now all URLs matching <code>/admin/*</code> will require NTLM authentication.</p>
[ { "answer_id": 22185, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 0, "selected": false, "text": "<p>Hm, I'm not sure what you're trying to accomplish.</p>\n\n<p>Usually implementing NTLM on an internal site is as simple as unchecking \"Enable Anonymous Access\" in \"Authentication and Access Control\" in the \"Directory Security\" tab of website properties in IIS. If that is cleared, then your web application users will see a pop-up NTLM dialog.</p>\n\n<p>There's no need for you to write any code that interfaces with Active Directory. IIS takes care of the authentication for you.</p>\n\n<p>Can you be more specific about what you're trying to do?</p>\n" }, { "answer_id": 22191, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 2, "selected": false, "text": "<p>As I understand it.<br>\nNTLM is one of IIS built in authentication methods. If the the Host is registered on the domain of said active directory, it should be automatic. One thing to watch out for is the username should be in one of two formats. </p>\n\n<ul>\n<li>domain\\username</li>\n<li>[email protected]</li>\n</ul>\n\n<p>If you are trying to go against a different active directory you should be using a forms style authentication and some LDAP code. </p>\n\n<p>If you are trying to do the Intranet No Zero Login thing with IIS Integrated authentication </p>\n\n<ul>\n<li>the domain needs to be listed as a trusted site in IEx browser</li>\n<li>or use a url the uses the netbios name instead of the DNS name.</li>\n<li>for it to work in firefox read <a href=\"https://calshare.berkeley.edu/Resources0/Pages/FirefoxonWindows.aspx\" rel=\"nofollow noreferrer\">here</a></li>\n</ul>\n" }, { "answer_id": 22194, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>i assume that you are wanting get to some of the attributes that are set against the LDAP account - role - department etc.</p>\n\n<p>for coldfusion check this out <a href=\"http://www.adobe.com/devnet/server_archive/articles/integrating_cf_apps_w_ms_active_directory.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/server_archive/articles/integrating_cf_apps_w_ms_active_directory.html</a></p>\n\n<p>and the cfldap tag <a href=\"http://livedocs.adobe.com/coldfusion/6.1/htmldocs/tags-p69.htm#wp1100581\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/coldfusion/6.1/htmldocs/tags-p69.htm#wp1100581</a></p>\n\n<p>As to other languages - others will do it with there respective APIs </p>\n" }, { "answer_id": 64075, "author": "Matt Everson", "author_id": 7300, "author_profile": "https://Stackoverflow.com/users/7300", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://modntlm.sourceforge.net/\" rel=\"nofollow noreferrer\">ModNTLM</a> source for Apache may provide you with the right pointers.</p>\n\n<p>If possible, you should consider using <a href=\"http://grolmsnet.de/kerbtut/\" rel=\"nofollow noreferrer\">Kerberos</a> instead. It lets you authenticate Apache against AD, and it's a more active project space than NTLM.</p>\n" }, { "answer_id": 464096, "author": "user8134", "author_id": 8134, "author_profile": "https://Stackoverflow.com/users/8134", "pm_score": 4, "selected": false, "text": "<p>What you're really asking is: Is there any way to validate the \"WWW-Authenticate: NTLM\" tokens submitted by IE and other HTTP clients when doing Single Sign-On (SSO). SSO is when the user enters their password a \"single\" time when they do Ctrl-Alt-Del and the workstation remembers and uses it as necessary to transparently access other resources without prompting the user for a password again.</p>\n\n<p>Note that Kerberos, like NTLM, can also be used to implement SSO authentication. When presented with a \"WWW-Authenticate: Negotiate\" header, IE and other browsers will send SPNEGO wrapped Kerberos and / or NTLM tokens. More on this later but first I will answer the question as asked.</p>\n\n<p>The only way to validate an NTLMSSP password \"response\" (like the ones encoded in \"WWW-Authenticate: NTLM\" headers submitted by IE and other browsers) is with a NetrLogonSamLogon(Ex) DCERPC call with the NETLOGON service of an Active Directory domain controller that is an authority for, or has a \"trust\" with an authority for, the target account. Additionally, to properly secure the NETLOGON communication, Secure Channel encryption should be used and is required as of Windows Server 2008.</p>\n\n<p>Needless to say, there are very few packages that implement the necessary NETLOGON service calls. The only ones I'm aware of are:</p>\n\n<ol>\n<li><p>Windows (of course)</p></li>\n<li><p>Samba - Samba is a set of software programs for UNIX that implements a number of Windows protocols including the necessary NETLOGON service calls. In fact, Samba 3 has a special daemon for this called \"winbind\" that other programs like PAM and Apache modules can (and do) interface with. On a Red Hat system you can do a <code>yum install samba-winbind</code> and <code>yum install mod_auth_ntlm_winbind</code>. But that's the easy part - setting these things up is another story.</p></li>\n<li><p>Jespa - Jespa (<a href=\"http://www.ioplex.com/jespa.html\" rel=\"noreferrer\">http://www.ioplex.com/jespa.html</a>) is a 100% Java library that implements all of the necessary NETLOGON service calls. It also provides implementations of standard Java interfaces for authenticating clients in various ways such as with an HTTP Servlet Filter, SASL server, JAAS LoginModule, etc.</p></li>\n</ol>\n\n<p>Beware that there are a number of NTLM authentication acceptors that do not implement the necessary NETLOGON service calls but instead do something else that ultimately leads to failure in one scenario or another. For example, for years, the way to do this in Java was with the NTLM HTTP authentication Servlet Filter from a project called JCIFS. But that Filter uses a man-in-the-middle technique that has been responsible for a long-standing \"hiccup bug\" and, more important, it does not support NTLMv2. For these reasons and others it is scheduled to be removed from JCIFS. There are several projects that have been unintentionally inspired by that package that are now also equally doomed. There are also a lot of code fragments posted in Java forums that decode the header token and pluck out the domain and username but do absolutely nothing to actually validate the password responses. Suffice it to say, if you use one of those code fragments, you might as well walk around with your pants down.</p>\n\n<p>As I eluded to earlier, NTLM is only one of several Windows Security Support Providers (SSP). There's also a Digest SSP, Kerberos SSP, etc. But the Negotiate SSP, which is also known as SPNEGO, is usually the provider that MS uses in their own protocol clients. The Negotiate SSP actually just negotiates either the NTLM SSP or Kerberos SSP. Note that Kerberos can only be used if both the server and client have accounts in the target domain and the client can communicate with the domain controller sufficiently to acquire a Kerberos ticket. If these conditions are not satisfied, the NTLM SSP is used directly. So NTLM is by no means obsolete.</p>\n\n<p>Finally, some people have mentioned using an LDAP \"simple bind\" as a make-shift password validation service. LDAP is not really designed as an authentication service and for this reason it is not efficient. It is also not possible to implement SSO using LDAP. SSO requires NTLM or SPNEGO. If you can find a NETLOGON or SPNEGO acceptor, you should use that instead.</p>\n\n<p>Mike</p>\n" }, { "answer_id": 3344275, "author": "dB.", "author_id": 123094, "author_profile": "https://Stackoverflow.com/users/123094", "pm_score": 1, "selected": false, "text": "<p>Check out <a href=\"http://waffle.codeplex.com\" rel=\"nofollow noreferrer\">Waffle</a>. It implements SSO for Java servers using Win32 API. There're servlet, tomcat valve, spring-security and other filters.</p>\n" }, { "answer_id": 19856659, "author": "Imran Vohra", "author_id": 1629418, "author_profile": "https://Stackoverflow.com/users/1629418", "pm_score": 1, "selected": false, "text": "<p>You can resolve the Firefox authentication popup by performing the following steps in Firefox:</p>\n\n<ol>\n<li>Open Mozilla Firefox</li>\n<li>Type about:config in address bar</li>\n<li>Enter network.automatic-ntlm-auth.trusted-uris in Search texfield</li>\n<li>Double click preference name and key in your server name as String value</li>\n<li>Close the tab</li>\n<li>Restart Firefox.</li>\n</ol>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/309844/" ]
I am trying to implement NTLM authentication on one of our internal sites and everything is working. The one piece of the puzzle I do not have is how to take the information from NTLM and authenticate with Active Directory. There is a [good description of NTLM](http://www.innovation.ch/personal/ronald/ntlm.html) and the [encryption used for the passwords](http://us1.samba.org/samba/docs/man/Samba-Developers-Guide/pwencrypt.html), which I used to implement this, but I am not sure of how to verify if the user's password is valid. I am using ColdFusion but a solution to this problem can be in any language (Java, Python, PHP, etc). Edit: I am using ColdFusion on Redhat Enterprise Linux. Unfortunately we cannot use IIS to manage this and instead have to write or use a 3rd party tool for this. --- **Update** - *I got this working and here is what I did* I went with the [JCIFS library from samba.org.](http://jcifs.samba.org/) > > Note that the method below will only work with NTLMv1 and **DOES NOT** work with NTLMv2. If you are unable to use NTLMv1 you can try [Jespa](http://www.ioplex.com/jespa.html), which supports NTLMv2 but is not open source, or you can use [Kerberos/SPNEGO.](http://spnego.sourceforge.net) > > > Here is my web.xml: ``` <web-app> <display-name>Ntlm</display-name> <filter> <filter-name>NtlmHttpFilter</filter-name> <filter-class>jcifs.http.NtlmHttpFilter</filter-class> <init-param> <param-name>jcifs.http.domainController</param-name> <param-value>dc01.corp.example.com</param-value> </init-param> <init-param> <param-name>jcifs.smb.client.domain</param-name> <param-value>CORP.EXAMPLE.COM</param-value> </init-param> </filter> <filter-mapping> <filter-name>NtlmHttpFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping> </web-app> ``` Now all URLs matching `/admin/*` will require NTLM authentication.
What you're really asking is: Is there any way to validate the "WWW-Authenticate: NTLM" tokens submitted by IE and other HTTP clients when doing Single Sign-On (SSO). SSO is when the user enters their password a "single" time when they do Ctrl-Alt-Del and the workstation remembers and uses it as necessary to transparently access other resources without prompting the user for a password again. Note that Kerberos, like NTLM, can also be used to implement SSO authentication. When presented with a "WWW-Authenticate: Negotiate" header, IE and other browsers will send SPNEGO wrapped Kerberos and / or NTLM tokens. More on this later but first I will answer the question as asked. The only way to validate an NTLMSSP password "response" (like the ones encoded in "WWW-Authenticate: NTLM" headers submitted by IE and other browsers) is with a NetrLogonSamLogon(Ex) DCERPC call with the NETLOGON service of an Active Directory domain controller that is an authority for, or has a "trust" with an authority for, the target account. Additionally, to properly secure the NETLOGON communication, Secure Channel encryption should be used and is required as of Windows Server 2008. Needless to say, there are very few packages that implement the necessary NETLOGON service calls. The only ones I'm aware of are: 1. Windows (of course) 2. Samba - Samba is a set of software programs for UNIX that implements a number of Windows protocols including the necessary NETLOGON service calls. In fact, Samba 3 has a special daemon for this called "winbind" that other programs like PAM and Apache modules can (and do) interface with. On a Red Hat system you can do a `yum install samba-winbind` and `yum install mod_auth_ntlm_winbind`. But that's the easy part - setting these things up is another story. 3. Jespa - Jespa (<http://www.ioplex.com/jespa.html>) is a 100% Java library that implements all of the necessary NETLOGON service calls. It also provides implementations of standard Java interfaces for authenticating clients in various ways such as with an HTTP Servlet Filter, SASL server, JAAS LoginModule, etc. Beware that there are a number of NTLM authentication acceptors that do not implement the necessary NETLOGON service calls but instead do something else that ultimately leads to failure in one scenario or another. For example, for years, the way to do this in Java was with the NTLM HTTP authentication Servlet Filter from a project called JCIFS. But that Filter uses a man-in-the-middle technique that has been responsible for a long-standing "hiccup bug" and, more important, it does not support NTLMv2. For these reasons and others it is scheduled to be removed from JCIFS. There are several projects that have been unintentionally inspired by that package that are now also equally doomed. There are also a lot of code fragments posted in Java forums that decode the header token and pluck out the domain and username but do absolutely nothing to actually validate the password responses. Suffice it to say, if you use one of those code fragments, you might as well walk around with your pants down. As I eluded to earlier, NTLM is only one of several Windows Security Support Providers (SSP). There's also a Digest SSP, Kerberos SSP, etc. But the Negotiate SSP, which is also known as SPNEGO, is usually the provider that MS uses in their own protocol clients. The Negotiate SSP actually just negotiates either the NTLM SSP or Kerberos SSP. Note that Kerberos can only be used if both the server and client have accounts in the target domain and the client can communicate with the domain controller sufficiently to acquire a Kerberos ticket. If these conditions are not satisfied, the NTLM SSP is used directly. So NTLM is by no means obsolete. Finally, some people have mentioned using an LDAP "simple bind" as a make-shift password validation service. LDAP is not really designed as an authentication service and for this reason it is not efficient. It is also not possible to implement SSO using LDAP. SSO requires NTLM or SPNEGO. If you can find a NETLOGON or SPNEGO acceptor, you should use that instead. Mike
22,181
<p>I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ... </p> <p>What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...</p> <pre><code>Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While </code></pre>
[ { "answer_id": 22186, "author": "Slavo", "author_id": 1801, "author_profile": "https://Stackoverflow.com/users/1801", "pm_score": 0, "selected": false, "text": "<p>Why don't you use LinqToSql - everything you need is done automatically. For the sake of being general you can use any other <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM tool</a> for .NET</p>\n" }, { "answer_id": 22189, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>I would call <code>reader.GetOrdinal</code> for each field name before starting the while loop. Unfortunately <code>GetOrdinal</code> throws an <code>IndexOutOfRangeException</code> if the field doesn't exist, so it won't be very performant.</p>\n\n<p>You could probably store the results in a <code>Dictionary&lt;string, int&gt;</code> and use its <code>ContainsKey</code> method to determine if the field was supplied.</p>\n" }, { "answer_id": 22195, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>Also check out this <a href=\"http://www.madprops.org/blog/another-idbcommand-extension-fill/\" rel=\"noreferrer\">extension method I wrote</a> for use on data commands:</p>\n\n<pre><code>public static void Fill&lt;T&gt;(this IDbCommand cmd,\n IList&lt;T&gt; list, Func&lt;IDataReader, T&gt; rowConverter)\n{\n using (var rdr = cmd.ExecuteReader())\n {\n while (rdr.Read())\n {\n list.Add(rowConverter(rdr));\n }\n }\n}\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>cmd.Fill(products, r =&gt; r.GetProduct());\n</code></pre>\n\n<p>Where \"products\" is the IList&lt;Product&gt; you want to populate, and \"GetProduct\" contains the logic to create a Product instance from a data reader. It won't help with this specific problem of not having all the fields present, but if you're doing a lot of old-fashioned ADO.NET like this it can be quite handy.</p>\n" }, { "answer_id": 22199, "author": "FantaMango77", "author_id": 2374, "author_profile": "https://Stackoverflow.com/users/2374", "pm_score": 1, "selected": false, "text": "<p>Use the <code>GetSchemaTable()</code> method to retrieve the metadata of the <code>DataReader</code>. The <code>DataTable</code> that is returned can be used to check if a specific column is present or not.</p>\n" }, { "answer_id": 22201, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 1, "selected": false, "text": "<p>Why not just have each sproc return complete column set, using null, -1, or acceptable values where you don't have the data. Avoids having to catch IndexOutOfRangeException or re-writing everything in LinqToSql.</p>\n" }, { "answer_id": 22273, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 0, "selected": false, "text": "<p>If you don't want to use an ORM you can also use reflection for things like this (though in this case because ProductID is not named the same on both sides, you couldn't do it in the simplistic fashion demonstrated here):\n<a href=\"http://wiki.lessthandot.com/index.php/Generic_List_Provider_in_CSharp\" rel=\"nofollow noreferrer\">List Provider in C#</a></p>\n" }, { "answer_id": 26103, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 2, "selected": true, "text": "<p>Although connection.GetSchema(\"Tables\") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns. </p>\n\n<p>For example, if you throw in some random ad-hoc column like *SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products\" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object \"GetSchemaTable()\"</p>\n\n<p>If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists.</p>\n\n<p><strong>Updated Source Code</strong></p>\n\n<pre><code>Using reader As SqlDataReader = cmd.ExecuteReader() \nDim table As DataTable = reader.GetSchemaTable()\nDim colNames As New DataTable()\nFor Each row As DataRow In table.Rows\n colNames.Columns.Add(row.ItemArray(0))\nNext\nDim product As Product While reader.Read() \nproduct = New Product() \nIf Not colNames.Columns(\"ProductID\") Is Nothing Then\n product.ID = Convert.ToInt32(reader(\"ProductID\"))\nEnd If \nproduct.SupplierID = Convert.ToInt32(reader(\"SupplierID\")) \nproduct.CategoryID = Convert.ToInt32(reader(\"CategoryID\")) \nproduct.ProductName = Convert.ToString(reader(\"ProductName\")) \nproduct.QuantityPerUnit = Convert.ToString(reader(\"QuantityPerUnit\")) \nproduct.UnitPrice = Convert.ToDouble(reader(\"UnitPrice\")) \nproduct.UnitsInStock = Convert.ToInt32(reader(\"UnitsInStock\")) \nproduct.UnitsOnOrder = Convert.ToInt32(reader(\"UnitsOnOrder\")) \nproduct.ReorderLevel = Convert.ToInt32(reader(\"ReorderLevel\")) \nproductList.Add(product) \nEnd While\n</code></pre>\n\n<p>This is a hack to be honest, as you <em>should</em> return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema.</p>\n\n<p>This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario. </p>\n" }, { "answer_id": 20476167, "author": "Nat Wallbank", "author_id": 2841771, "author_profile": "https://Stackoverflow.com/users/2841771", "pm_score": 0, "selected": false, "text": "<p>I ended up writing my own, but this mapper is pretty good (and simple): <a href=\"https://code.google.com/p/dapper-dot-net/\" rel=\"nofollow\">https://code.google.com/p/dapper-dot-net/</a></p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ... What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ... ``` Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = Convert.ToInt32(reader("ProductID")) product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While ```
Although connection.GetSchema("Tables") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns. For example, if you throw in some random ad-hoc column like \*SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object "GetSchemaTable()" If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists. **Updated Source Code** ``` Using reader As SqlDataReader = cmd.ExecuteReader() Dim table As DataTable = reader.GetSchemaTable() Dim colNames As New DataTable() For Each row As DataRow In table.Rows colNames.Columns.Add(row.ItemArray(0)) Next Dim product As Product While reader.Read() product = New Product() If Not colNames.Columns("ProductID") Is Nothing Then product.ID = Convert.ToInt32(reader("ProductID")) End If product.SupplierID = Convert.ToInt32(reader("SupplierID")) product.CategoryID = Convert.ToInt32(reader("CategoryID")) product.ProductName = Convert.ToString(reader("ProductName")) product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit")) product.UnitPrice = Convert.ToDouble(reader("UnitPrice")) product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock")) product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder")) product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel")) productList.Add(product) End While ``` This is a hack to be honest, as you *should* return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema. This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario.
22,187
<p>What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)?</p> <p>Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.</p>
[ { "answer_id": 22197, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>Microsoft <a href=\"http://msdn.microsoft.com/en-us/library/bb648752.aspx\" rel=\"noreferrer\">Concurrency and Coordination Runtime</a> for .NET.</p>\n\n<blockquote>\n <p>The CCR is appropriate for an\n application model that separates\n components into pieces that can\n interact only through messages.\n Components in this model need means to\n coordinate between messages, deal with\n complex failure scenarios, and\n effectively deal with asynchronous\n programming.</p>\n</blockquote>\n" }, { "answer_id": 22226, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 3, "selected": false, "text": "<p>Scala supports actors. But I would not call scala intentionally similar to Erlang.</p>\n\n<p>Nonetheless scala is absolutely worth taking a look!</p>\n" }, { "answer_id": 22231, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 3, "selected": false, "text": "<p>Also <a href=\"http://www.malhar.net/sriram/kilim/\" rel=\"noreferrer\">kilim</a> is a library for java, that brings erlang style message passing/actors to the Java language. </p>\n" }, { "answer_id": 22285, "author": "jcsalterego", "author_id": 1416, "author_profile": "https://Stackoverflow.com/users/1416", "pm_score": 4, "selected": true, "text": "<p>Message Passing Interface (MPI) (<a href=\"http://www-unix.mcs.anl.gov/mpi/\" rel=\"noreferrer\">http://www-unix.mcs.anl.gov/mpi/</a>) is a highly scalable and robust library for parallel programming, geared original towards C but now available in several flavors <a href=\"http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations</a>. While the library doesn't introduce new syntax, it provides a communication protocol to orchestrate the sharing of data between routines which are parallelizable.</p>\n\n<p>Traditionally, it is used in large cluster computing rather than on a single system for concurrency, although multi-core systems can certainly take advantage of this library.</p>\n\n<p>Another interesting solution to the problem of parallel programming is OpenMP, which is an attempt to provide a portable extension on various platforms to provide hints to the compiler about what sections of code are easily parallelizable.</p>\n\n<p>For example (<a href=\"http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs</a>):</p>\n\n<pre><code>#define N 100000\nint main(int argc, char *argv[])\n{\n int i, a[N];\n #pragma omp parallel for\n for (i=0;i&lt;N;i++) \n a[i]= 2*i;\n return 0;\n}\n</code></pre>\n\n<p>There are advantages and disadvantages to both, of course, but the former has proven to be extremely successful in academia and other heavy scientific computing applications. YMMV.</p>\n" }, { "answer_id": 22451, "author": "cnu", "author_id": 1448, "author_profile": "https://Stackoverflow.com/users/1448", "pm_score": 2, "selected": false, "text": "<p>For python you can try using <a href=\"http://pyprocessing.berlios.de/\" rel=\"nofollow noreferrer\">processing module</a>.</p>\n" }, { "answer_id": 22456, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 3, "selected": false, "text": "<p>Mike Rettig created a .NET library called <a href=\"http://code.google.com/p/retlang/\" rel=\"noreferrer\">Retlang</a> and a Java port called Jetlang that is inspired by Erlang's concurrency model.</p>\n" }, { "answer_id": 54452, "author": "argv0", "author_id": 5595, "author_profile": "https://Stackoverflow.com/users/5595", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://ulf.wiger.net/weblog/2008/02/06/what-is-erlang-style-concurrency/\" rel=\"noreferrer\">Ulf Wiger</a> had a great post recently on this topic - here are the properties he defines as required before you can call something \"Erlang Style Concurrency\":</p>\n\n<ul>\n<li>Fast process creation/destruction</li>\n<li>Ability to support >> 10 000 concurrent processes with largely unchanged characteristics.</li>\n<li>Fast asynchronous message passing.</li>\n<li>Copying message-passing semantics (share-nothing concurrency).</li>\n<li>Process monitoring.</li>\n<li>Selective message reception.</li>\n</ul>\n\n<p>Number 2 above is the hardest to support in VMs and language implementations that weren't initially designed for concurrency. This is not to knock Erlang-ish concurrency implementations in other languages, but a lot of Erlang's value comes from being able to create <i>millions</i> of processes, which is pretty damn hard if the process abstraction has a 1-1 relationship with an OS-level thread or process. Ulf has a lot more on this in the link above.</p>\n" }, { "answer_id": 274310, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://code.google.com/p/termite/\" rel=\"nofollow noreferrer\">Termite</a> for Gambit Scheme.</p>\n" }, { "answer_id": 502340, "author": "Volker Stolz", "author_id": 60462, "author_profile": "https://Stackoverflow.com/users/60462", "pm_score": 2, "selected": false, "text": "<p>Warning: shameless plug!</p>\n\n<p>I developed a library for this kind of message passing in Haskell:\n<a href=\"http://www.iist.unu.edu/~vs/haskell/dhs/\" rel=\"nofollow noreferrer\">Erlang-style Distributed Haskell</a>.</p>\n\n<p>Volker</p>\n" }, { "answer_id": 971146, "author": "luccastera", "author_id": 76372, "author_profile": "https://Stackoverflow.com/users/76372", "pm_score": 2, "selected": false, "text": "<p>If you are using Ruby, take a look at <a href=\"http://revactor.org/\" rel=\"nofollow noreferrer\">Revactor</a>.</p>\n<p>Revactor is an Actor model implementation for Ruby 1.9 built on top of the Rev high performance event library. Revactor is primarily designed for writing Erlang-like network services and tools.</p>\n<p>Take a look at this code sample:</p>\n<pre><code> myactor = Actor.spawn do\n Actor.receive do |filter|\n filter.when(:dog) { puts &quot;I got a dog!&quot; }\n end\n end\n</code></pre>\n<p>Revactor only runs on Ruby 1.9. I believe the author of the library has discontinued maintaining it but the documentation on their site is very good.</p>\n<p>You might also want to take a look at Reia: a ruby-like scripting language built on top of the Erlang VM. Reia is the new project of the creator of Revactor: Tony Arcieri.</p>\n" }, { "answer_id": 971197, "author": "Hans Van Slooten", "author_id": 28585, "author_profile": "https://Stackoverflow.com/users/28585", "pm_score": 2, "selected": false, "text": "<p>Microsoft's Not-Production-Ready Answer to Erlang: <a href=\"http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx\" rel=\"nofollow noreferrer\">Microsoft Axum</a></p>\n" }, { "answer_id": 1605757, "author": "ygrek", "author_id": 118799, "author_profile": "https://Stackoverflow.com/users/118799", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://jocaml.inria.fr/\" rel=\"nofollow noreferrer\">JoCaml</a> extends OCaml with join calculus for concurrent and distributed programming.</p>\n" }, { "answer_id": 7693016, "author": "pondermatic", "author_id": 43836, "author_profile": "https://Stackoverflow.com/users/43836", "pm_score": 2, "selected": false, "text": "<p>Akka (<a href=\"http://akka.io/\" rel=\"nofollow\">http://akka.io</a>) is heavily influenced by erlangs OTP. It has built on scala's actors and is great for concurrency on the JVM.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)? Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.
Message Passing Interface (MPI) (<http://www-unix.mcs.anl.gov/mpi/>) is a highly scalable and robust library for parallel programming, geared original towards C but now available in several flavors <http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations>. While the library doesn't introduce new syntax, it provides a communication protocol to orchestrate the sharing of data between routines which are parallelizable. Traditionally, it is used in large cluster computing rather than on a single system for concurrency, although multi-core systems can certainly take advantage of this library. Another interesting solution to the problem of parallel programming is OpenMP, which is an attempt to provide a portable extension on various platforms to provide hints to the compiler about what sections of code are easily parallelizable. For example (<http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs>): ``` #define N 100000 int main(int argc, char *argv[]) { int i, a[N]; #pragma omp parallel for for (i=0;i<N;i++) a[i]= 2*i; return 0; } ``` There are advantages and disadvantages to both, of course, but the former has proven to be extremely successful in academia and other heavy scientific computing applications. YMMV.
22,239
<p>(I'm using Visual C++ 2008) I've always heard that main() is <em>required</em> to return an integer, but here I didn't put in <code>return 0;</code> and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a <code>return;</code> also causes the error to appear. But leaving it out completely, it compiles just fine.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Hey look I'm supposed to return an int but I'm not gonna!\n"; } </code></pre> <p>Could this be a bug in VC++?</p>
[ { "answer_id": 22251, "author": "bradtgmurray", "author_id": 1546, "author_profile": "https://Stackoverflow.com/users/1546", "pm_score": 2, "selected": false, "text": "<p>I'm pretty sure VC++ just inserts a return 0 if you don't include one in main functions. The same thing can happen with functions too, but in those cases at least you'll get a warning.</p>\n" }, { "answer_id": 22253, "author": "On Freund", "author_id": 2150, "author_profile": "https://Stackoverflow.com/users/2150", "pm_score": 4, "selected": false, "text": "<p>This is part of the C++ language standard. An implicit return 0 is generated for you if there's no explicit return statement in main.</p>\n" }, { "answer_id": 22262, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 7, "selected": true, "text": "<blockquote>\n<h1>3.6.1 Main function</h1>\n<p>....</p>\n<p>2 An implementation shall not predefine the <code>main</code> function. This function shall not be overloaded. It shall have a return type of type <code>int</code>, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:</p>\n<pre><code>int main() { /* ... */ }\n</code></pre>\n<p>and</p>\n<pre><code>int main(int argc, char* argv[]) {\n/* ... */\n}\n</code></pre>\n<p>.... and it continues to add ...</p>\n<p>5 A <code>return</code> statement in <code>main</code> has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling <code>exit</code> with the return value as the argument. <strong>If control reaches the end of <code>main</code> without encountering a return statement, the effect is that of executing return 0</strong>;</p>\n</blockquote>\n<p>attempting to find an online copy of the C++ standard so I could quote this passage <a href=\"http://zamanbakshifirst.blogspot.com/2006/11/c-c-main-should-return-void.html\" rel=\"noreferrer\">I found a blog post that quotes all the right bits better than I could.</a></p>\n" }, { "answer_id": 3492633, "author": "Chubsdad", "author_id": 418110, "author_profile": "https://Stackoverflow.com/users/418110", "pm_score": 2, "selected": false, "text": "<p>Section 6.6.3/2 states- \"Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.\".</p>\n\n<p>An example is the code below which at best gives warning on VS 2010/g++</p>\n\n<pre><code>int f(){\n if(0){\n if(1)\n return true;\n }\n}\n\nint main(){\n f();\n}\n</code></pre>\n\n<p>So the whole point is that 'main' is special as the previous responses have pointed out.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2222/" ]
(I'm using Visual C++ 2008) I've always heard that main() is *required* to return an integer, but here I didn't put in `return 0;` and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a `return;` also causes the error to appear. But leaving it out completely, it compiles just fine. ``` #include <iostream> using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; } ``` Could this be a bug in VC++?
> > 3.6.1 Main function > =================== > > > .... > > > 2 An implementation shall not predefine the `main` function. This function shall not be overloaded. It shall have a return type of type `int`, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: > > > > ``` > int main() { /* ... */ } > > ``` > > and > > > > ``` > int main(int argc, char* argv[]) { > /* ... */ > } > > ``` > > .... and it continues to add ... > > > 5 A `return` statement in `main` has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling `exit` with the return value as the argument. **If control reaches the end of `main` without encountering a return statement, the effect is that of executing return 0**; > > > attempting to find an online copy of the C++ standard so I could quote this passage [I found a blog post that quotes all the right bits better than I could.](http://zamanbakshifirst.blogspot.com/2006/11/c-c-main-should-return-void.html)
22,259
<p>I want to allow users to upload avatar-type images in a variety of formats (<strong>GIF, JPEG, and PNG at least</strong>), but to save them all as <strong>PNG database BLOBs</strong>. If the images are oversized, pixelwise, I want to resize them before DB-insertion.</p> <p><strong>What is the best way to use GD to do the resizing and PNG conversion?</strong></p> <p>Edit: Sadly, only <a href="http://php.net/manual/en/book.image.php" rel="nofollow noreferrer">GD</a> is available on the server I need to use, no <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>.</p>
[ { "answer_id": 22267, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.phpit.net/article/image-manipulation-php-gd-part2/\" rel=\"nofollow noreferrer\">This article</a> seems like it would fit what you want. You'll need to change the saving imagejpeg() function to imagepng() and have it save the file to a string rather than output it to the page, but other than that it should be easy copy/paste into your existing code.</p>\n" }, { "answer_id": 22270, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "<p>Is GD absolutely required? <a href=\"http://imagemagick.org/\" rel=\"nofollow noreferrer\">ImageMagick</a> is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n" }, { "answer_id": 22271, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>I think <a href=\"http://codecaine.co.za/posts/zend-image-class-to-convert-and-resize-images\" rel=\"nofollow noreferrer\">this page</a> is a good starting point. It uses imagecreatefrom(jpeg/gif/png) and resize and converts the image and then outputs to the browser. Instead of outputting the browser you could output to a BLOB in a DB without many minuttes of code-rewrite.</p>\n" }, { "answer_id": 22282, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 2, "selected": false, "text": "<p>If you want to use gdlib, use gdlib 2 or higher. It has a function called imagecopyresampled(), which will interpolate pixels while resizing and look much better.</p>\n\n<p>Also, I've always heard noted around the net that storing images in the database is bad form:</p>\n\n<ul>\n<li>It's slower to access than the disk</li>\n<li>Your server will need to run a script to get to the image instead\nof simply serving a file</li>\n<li>Your script now is responsible for a lot of stuff the web server used\nto handle:\n\n<ul>\n<li>Setting the proper Content-Type header</li>\n<li>Setting the proper caching/timeout/E-tag headers, so clients can properly cache the image. If do not do this properly, the image serving script will be hit on every request, increasing the load on the server even more.</li>\n</ul></li>\n</ul>\n\n<p>The only advantage I can see is that you don't need to keep your database and image files synchronized. I would still recommend against it though.</p>\n" }, { "answer_id": 22300, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>Your process steps should look like this:</p>\n\n<ol>\n<li><a href=\"http://www.php.net/manual/en/function.exif-imagetype.php\" rel=\"nofollow noreferrer\">Verify</a> the <a href=\"http://www.php.net/manual/en/function.imagetypes.php\" rel=\"nofollow noreferrer\">filetype</a></li>\n<li>Load the image if it is a supported filetype into GD using <a href=\"http://www.php.net/manual/en/function.imagecreatefromjpeg.php\" rel=\"nofollow noreferrer\">imagecreatefrom*</a></li>\n<li>Resizing using <a href=\"http://www.php.net/manual/en/function.imagecopyresized.php\" rel=\"nofollow noreferrer\">imagecopyresize</a> or <a href=\"http://www.php.net/manual/en/function.imagecopyresampled.php\" rel=\"nofollow noreferrer\">imagecopyresampled</a></li>\n<li>Save the image using <a href=\"http://www.php.net/manual/en/function.imagepng.php\" rel=\"nofollow noreferrer\">imagepng($handle, 'filename.png', $quality, $filters)</a></li>\n</ol>\n\n<blockquote>\n <p>ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n</blockquote>\n\n<p>@ceejayoz Just wait for the new GD - it's OOP like MySQLi and it's actually not bad :)</p>\n" }, { "answer_id": 22324, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 2, "selected": false, "text": "<p>Are you sure you have no ImageMagick on server?</p>\n\n<p>I guest you use PHP (question is tagged with PHP). Hosting company which I use has no ImageMagick extension turned on according to phpinfo().</p>\n\n<p>But when I asked them about they said <em>here is the list of ImageMagick programs available from PHP code</em>. So simply -- there are no IM interface in PHP, but I can call IM programs directly from PHP.</p>\n\n<p>I hope you have the same option.</p>\n\n<p>And I <strong>strongly</strong> agree -- storing images in database is not good idea.</p>\n" }, { "answer_id": 22333, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "<p>Something like this, perhaps: </p>\n\n<pre><code>\n&lt;?php\n //Input file\n $file = \"myImage.png\";\n $img = ImageCreateFromPNG($file);\n\n //Dimensions\n $width = imagesx($img);\n $height = imagesy($img);\n $max_width = 300;\n $max_height = 300;\n $percentage = 1;\n\n //Image scaling calculations\n if ( $width > $max_width ) { \n $percentage = ($height / ($width / $max_width)) > $max_height ?\n $height / $max_height :\n $width / $max_width;\n }\n elseif ( $height > $max_height) {\n $percentage = ($width / ($height / $max_height)) > $max_width ? \n $width / $max_width :\n $height / $max_height;\n }\n $new_width = $width / $percentage;\n $new_height = $height / $percentage;\n\n //scaled image\n $out = imagecreatetruecolor($new_width, $new_height);\n imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n\n //output image\n imagepng($out);\n?&gt;\n</code></pre>\n\n<p>I haven't tested the code so there might be some syntax errors, however it should give you a fair presentation on how it could be done. Also, I assumed a PNG file. You might want to have some kind of switch statement to determine the file type.</p>\n" }, { "answer_id": 22403, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 6, "selected": true, "text": "<pre><code>&lt;?php \n/*\nResizes an image and converts it to PNG returning the PNG data as a string\n*/\nfunction imageToPng($srcFile, $maxSize = 100) { \n list($width_orig, $height_orig, $type) = getimagesize($srcFile); \n\n // Get the aspect ratio\n $ratio_orig = $width_orig / $height_orig;\n\n $width = $maxSize; \n $height = $maxSize;\n\n // resize to height (orig is portrait) \n if ($ratio_orig &lt; 1) {\n $width = $height * $ratio_orig;\n } \n // resize to width (orig is landscape)\n else {\n $height = $width / $ratio_orig;\n }\n\n // Temporarily increase the memory limit to allow for larger images\n ini_set('memory_limit', '32M'); \n\n switch ($type) \n {\n case IMAGETYPE_GIF: \n $image = imagecreatefromgif($srcFile); \n break; \n case IMAGETYPE_JPEG: \n $image = imagecreatefromjpeg($srcFile); \n break; \n case IMAGETYPE_PNG: \n $image = imagecreatefrompng($srcFile);\n break; \n default:\n throw new Exception('Unrecognized image type ' . $type);\n }\n\n // create a new blank image\n $newImage = imagecreatetruecolor($width, $height);\n\n // Copy the old image to the new image\n imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n // Output to a temp file\n $destFile = tempnam();\n imagepng($newImage, $destFile); \n\n // Free memory \n imagedestroy($newImage);\n\n if ( is_file($destFile) ) {\n $f = fopen($destFile, 'rb'); \n $data = fread($f); \n fclose($f);\n\n // Remove the tempfile\n unlink($destFile); \n return $data;\n }\n\n throw new Exception('Image conversion failed.');\n}\n</code></pre>\n" }, { "answer_id": 43836, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://phpthumb.sourceforge.net/\" rel=\"nofollow noreferrer\">phpThumb</a> is a high-level abstraction that may be worth looking at.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
I want to allow users to upload avatar-type images in a variety of formats (**GIF, JPEG, and PNG at least**), but to save them all as **PNG database BLOBs**. If the images are oversized, pixelwise, I want to resize them before DB-insertion. **What is the best way to use GD to do the resizing and PNG conversion?** Edit: Sadly, only [GD](http://php.net/manual/en/book.image.php) is available on the server I need to use, no [ImageMagick](http://www.imagemagick.org/script/index.php).
``` <?php /* Resizes an image and converts it to PNG returning the PNG data as a string */ function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.'); } ```
22,269
<p>I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution.</p> <p>The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that.</p> <p>Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized.</p>
[ { "answer_id": 22267, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.phpit.net/article/image-manipulation-php-gd-part2/\" rel=\"nofollow noreferrer\">This article</a> seems like it would fit what you want. You'll need to change the saving imagejpeg() function to imagepng() and have it save the file to a string rather than output it to the page, but other than that it should be easy copy/paste into your existing code.</p>\n" }, { "answer_id": 22270, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "<p>Is GD absolutely required? <a href=\"http://imagemagick.org/\" rel=\"nofollow noreferrer\">ImageMagick</a> is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n" }, { "answer_id": 22271, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>I think <a href=\"http://codecaine.co.za/posts/zend-image-class-to-convert-and-resize-images\" rel=\"nofollow noreferrer\">this page</a> is a good starting point. It uses imagecreatefrom(jpeg/gif/png) and resize and converts the image and then outputs to the browser. Instead of outputting the browser you could output to a BLOB in a DB without many minuttes of code-rewrite.</p>\n" }, { "answer_id": 22282, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 2, "selected": false, "text": "<p>If you want to use gdlib, use gdlib 2 or higher. It has a function called imagecopyresampled(), which will interpolate pixels while resizing and look much better.</p>\n\n<p>Also, I've always heard noted around the net that storing images in the database is bad form:</p>\n\n<ul>\n<li>It's slower to access than the disk</li>\n<li>Your server will need to run a script to get to the image instead\nof simply serving a file</li>\n<li>Your script now is responsible for a lot of stuff the web server used\nto handle:\n\n<ul>\n<li>Setting the proper Content-Type header</li>\n<li>Setting the proper caching/timeout/E-tag headers, so clients can properly cache the image. If do not do this properly, the image serving script will be hit on every request, increasing the load on the server even more.</li>\n</ul></li>\n</ul>\n\n<p>The only advantage I can see is that you don't need to keep your database and image files synchronized. I would still recommend against it though.</p>\n" }, { "answer_id": 22300, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>Your process steps should look like this:</p>\n\n<ol>\n<li><a href=\"http://www.php.net/manual/en/function.exif-imagetype.php\" rel=\"nofollow noreferrer\">Verify</a> the <a href=\"http://www.php.net/manual/en/function.imagetypes.php\" rel=\"nofollow noreferrer\">filetype</a></li>\n<li>Load the image if it is a supported filetype into GD using <a href=\"http://www.php.net/manual/en/function.imagecreatefromjpeg.php\" rel=\"nofollow noreferrer\">imagecreatefrom*</a></li>\n<li>Resizing using <a href=\"http://www.php.net/manual/en/function.imagecopyresized.php\" rel=\"nofollow noreferrer\">imagecopyresize</a> or <a href=\"http://www.php.net/manual/en/function.imagecopyresampled.php\" rel=\"nofollow noreferrer\">imagecopyresampled</a></li>\n<li>Save the image using <a href=\"http://www.php.net/manual/en/function.imagepng.php\" rel=\"nofollow noreferrer\">imagepng($handle, 'filename.png', $quality, $filters)</a></li>\n</ol>\n\n<blockquote>\n <p>ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for.</p>\n</blockquote>\n\n<p>@ceejayoz Just wait for the new GD - it's OOP like MySQLi and it's actually not bad :)</p>\n" }, { "answer_id": 22324, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 2, "selected": false, "text": "<p>Are you sure you have no ImageMagick on server?</p>\n\n<p>I guest you use PHP (question is tagged with PHP). Hosting company which I use has no ImageMagick extension turned on according to phpinfo().</p>\n\n<p>But when I asked them about they said <em>here is the list of ImageMagick programs available from PHP code</em>. So simply -- there are no IM interface in PHP, but I can call IM programs directly from PHP.</p>\n\n<p>I hope you have the same option.</p>\n\n<p>And I <strong>strongly</strong> agree -- storing images in database is not good idea.</p>\n" }, { "answer_id": 22333, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "<p>Something like this, perhaps: </p>\n\n<pre><code>\n&lt;?php\n //Input file\n $file = \"myImage.png\";\n $img = ImageCreateFromPNG($file);\n\n //Dimensions\n $width = imagesx($img);\n $height = imagesy($img);\n $max_width = 300;\n $max_height = 300;\n $percentage = 1;\n\n //Image scaling calculations\n if ( $width > $max_width ) { \n $percentage = ($height / ($width / $max_width)) > $max_height ?\n $height / $max_height :\n $width / $max_width;\n }\n elseif ( $height > $max_height) {\n $percentage = ($width / ($height / $max_height)) > $max_width ? \n $width / $max_width :\n $height / $max_height;\n }\n $new_width = $width / $percentage;\n $new_height = $height / $percentage;\n\n //scaled image\n $out = imagecreatetruecolor($new_width, $new_height);\n imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n\n //output image\n imagepng($out);\n?&gt;\n</code></pre>\n\n<p>I haven't tested the code so there might be some syntax errors, however it should give you a fair presentation on how it could be done. Also, I assumed a PNG file. You might want to have some kind of switch statement to determine the file type.</p>\n" }, { "answer_id": 22403, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 6, "selected": true, "text": "<pre><code>&lt;?php \n/*\nResizes an image and converts it to PNG returning the PNG data as a string\n*/\nfunction imageToPng($srcFile, $maxSize = 100) { \n list($width_orig, $height_orig, $type) = getimagesize($srcFile); \n\n // Get the aspect ratio\n $ratio_orig = $width_orig / $height_orig;\n\n $width = $maxSize; \n $height = $maxSize;\n\n // resize to height (orig is portrait) \n if ($ratio_orig &lt; 1) {\n $width = $height * $ratio_orig;\n } \n // resize to width (orig is landscape)\n else {\n $height = $width / $ratio_orig;\n }\n\n // Temporarily increase the memory limit to allow for larger images\n ini_set('memory_limit', '32M'); \n\n switch ($type) \n {\n case IMAGETYPE_GIF: \n $image = imagecreatefromgif($srcFile); \n break; \n case IMAGETYPE_JPEG: \n $image = imagecreatefromjpeg($srcFile); \n break; \n case IMAGETYPE_PNG: \n $image = imagecreatefrompng($srcFile);\n break; \n default:\n throw new Exception('Unrecognized image type ' . $type);\n }\n\n // create a new blank image\n $newImage = imagecreatetruecolor($width, $height);\n\n // Copy the old image to the new image\n imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);\n\n // Output to a temp file\n $destFile = tempnam();\n imagepng($newImage, $destFile); \n\n // Free memory \n imagedestroy($newImage);\n\n if ( is_file($destFile) ) {\n $f = fopen($destFile, 'rb'); \n $data = fread($f); \n fclose($f);\n\n // Remove the tempfile\n unlink($destFile); \n return $data;\n }\n\n throw new Exception('Image conversion failed.');\n}\n</code></pre>\n" }, { "answer_id": 43836, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://phpthumb.sourceforge.net/\" rel=\"nofollow noreferrer\">phpThumb</a> is a high-level abstraction that may be worth looking at.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution. The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that. Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized.
``` <?php /* Resizes an image and converts it to PNG returning the PNG data as a string */ function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.'); } ```
22,322
<p>I've got a problem similar to,but subtly different from, that described <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">here</a> (Loading assemblies and their dependencies).</p> <p>I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? </p> <p>Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?</p> <p>Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?</p>
[ { "answer_id": 22347, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 1, "selected": false, "text": "<p>I encountered a similar scenario a while back. A toolkit I was using did not behave well in a 64-bit environment and I wasn't able to find a way to dynamically force the assemblies to bind as 32 bit.</p>\n\n<p>It is possible to force your assemblies to work in 32 bit mode, but this requires patching the CLR header, (there is a tool that does that in the Framework) and if your assemblies are strongly-named, this does not work out.</p>\n\n<p>I'm afraid you'll need to build and publish two sets of binaries for 32 and 64 bit platforms.</p>\n" }, { "answer_id": 22414, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 2, "selected": false, "text": "<p>I was able to do this about a year ago, but I no longer remember all of the details. Basically, you can use IntPtr.Size to determine which DLL to load, then perform the actual LoadLibrary through p/Invoke. At that point, you've got the module in memory and you ought to be able to just p/Invoke functions from inside of it -- the same module name shouldn't get reloaded again.</p>\n\n<p>I think, though, that in my application I actually had the C++ DLL register itself as a COM server and then accessed its functionality through a generated .NET wrapper -- so I don't know if I ever tested p/Invoking directly.</p>\n" }, { "answer_id": 479664, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 4, "selected": true, "text": "<p>I finally have an answer for this that appears to work.</p>\n\n<p>Compile both 32 &amp; 64 bit versions - both managed &amp; unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from.</p>\n\n<p>The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like:</p>\n\n<pre><code>static void Main(String[] argv)\n {\n // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit\n // sub-directories.\n\n AppDomainSetup objADS = new AppDomainSetup();\n\n System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n switch (System.IntPtr.Size)\n {\n case (4): assemblyDir += \"\\\\win32\\\\\";\n break;\n case (8): assemblyDir += \"\\\\x64\\\\\";\n break;\n }\n\n objADS.ApplicationBase = assemblyDir;\n\n // We set the PrivateBinPath to the application directory, so that we can still\n // load the platform neutral assemblies from the app directory.\n objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n\n AppDomain objAD = AppDomain.CreateDomain(\"\", null, objADS);\n if (argv.Length &gt; 0)\n objAD.ExecuteAssembly(argv[0]);\n else\n objAD.ExecuteAssembly(\"MyApplication.exe\");\n\n AppDomain.Unload(objAD);\n\n }\n</code></pre>\n\n<p>You end up with 2 exes - your normal app and a second switching app that chooses which bits to load.\nNote - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2102/" ]
I've got a problem similar to,but subtly different from, that described [here](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies) (Loading assemblies and their dependencies). I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time? Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?
I finally have an answer for this that appears to work. Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from. The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like: ``` static void Main(String[] argv) { // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit // sub-directories. AppDomainSetup objADS = new AppDomainSetup(); System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath); switch (System.IntPtr.Size) { case (4): assemblyDir += "\\win32\\"; break; case (8): assemblyDir += "\\x64\\"; break; } objADS.ApplicationBase = assemblyDir; // We set the PrivateBinPath to the application directory, so that we can still // load the platform neutral assemblies from the app directory. objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath); AppDomain objAD = AppDomain.CreateDomain("", null, objADS); if (argv.Length > 0) objAD.ExecuteAssembly(argv[0]); else objAD.ExecuteAssembly("MyApplication.exe"); AppDomain.Unload(objAD); } ``` You end up with 2 exes - your normal app and a second switching app that chooses which bits to load. Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him
22,326
<p>I am trying to <strong>replace the current selection in Word (2003/2007)</strong> by some <strong>RTF string</strong> stored in a variable.</p> <p>Here is the current code:</p> <pre><code>Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) </code></pre> <p>Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?</p>
[ { "answer_id": 22335, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": -1, "selected": false, "text": "<p>You can use a RichTextbox to convert RTF to text or vice versa.</p>\n\n<pre><code>RichTextBox r = new RichTextBox();\nr.Rtf = strRTFString;\nConsole.WriteLine(r.Text);\n</code></pre>\n" }, { "answer_id": 27425, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 5, "selected": true, "text": "<p>Put the RTF in a file instead of the clipboard, then insert from the file, e.g.</p>\n\n<blockquote>\n <p><code>Selection.InsertFile FileName:=\"myfile.rtf\", Range :=\"\", _\n ConfirmConversions:=False, Link:=False, Attachment:=False</code></p>\n</blockquote>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
I am trying to **replace the current selection in Word (2003/2007)** by some **RTF string** stored in a variable. Here is the current code: ``` Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) ``` Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?
Put the RTF in a file instead of the clipboard, then insert from the file, e.g. > > `Selection.InsertFile FileName:="myfile.rtf", Range :="", _ > ConfirmConversions:=False, Link:=False, Attachment:=False` > > >
22,354
<p>I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field.</p> <p>I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error.</p> <p>The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success.</p> <p>Is there a way to tell if another thread has a lock on a document?</p>
[ { "answer_id": 22703, "author": "vitule", "author_id": 1287, "author_profile": "https://Stackoverflow.com/users/1287", "pm_score": 1, "selected": false, "text": "<p>Sometimes I see the <code>ItemAdded</code> or <code>ItemUpdated</code> firing twice for a single operation. \nYou can try to put a breakpoint in the <code>ItemAdded()</code> method to confirm that.</p>\n\n<p>The solution in my case was to single thread the <code>ItemAdded()</code> method:</p>\n\n<pre><code>private static object myLock = new object();\npublic override void ItemAdded(SPItemEventProperties properties) {\n if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30))\n {\n //do your stuff here.\n System.Threading.Monitor.Exit(myLock);\n }\n}\n</code></pre>\n" }, { "answer_id": 22786, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "<p>I'll have to look into that and get back to you. The problem on my end seems to be that there is code running in a different class, in a different feature, being controlled by a different thread, all of which are trying to access the same record.</p>\n\n<p>I am trying to avoid using a fixed delay. With any threading issue, there is the pathological possibility that one thread can delay or block beyond what we expect. With deployments on different server hardware with different loads, this is a very real possibility. On the other end of the spectrum, even if I were to go with a delay, I don't want it to be very high, especially not 30 seconds. My client will be importing tens of thousands of documents, and a delay of any significant length will cause the import to take literally all day.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field. I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error. The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success. Is there a way to tell if another thread has a lock on a document?
Sometimes I see the `ItemAdded` or `ItemUpdated` firing twice for a single operation. You can try to put a breakpoint in the `ItemAdded()` method to confirm that. The solution in my case was to single thread the `ItemAdded()` method: ``` private static object myLock = new object(); public override void ItemAdded(SPItemEventProperties properties) { if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30)) { //do your stuff here. System.Threading.Monitor.Exit(myLock); } } ```
22,356
<p>I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.</p> <p>Based on the community suggestions, I've used this:</p> <pre><code>// earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here } </code></pre>
[ { "answer_id": 22387, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>I shun redundant delegate declarations.</p>\n\n<pre><code>private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n if (InvokeRequired)\n {\n Invoke(new Action&lt;object, CoolObjectEventArgs&gt;(mCoolObject_CoolEvent), sender, args);\n return;\n }\n // do the dirty work of my method here\n}\n</code></pre>\n\n<p>For non-events, you can use the <code>System.Windows.Forms.MethodInvoker</code> delegate or <code>System.Action</code>.</p>\n\n<p>EDIT: Additionally, every event has a corresponding <code>EventHandler</code> delegate so there's no need at all to redeclare one.</p>\n" }, { "answer_id": 22395, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've always wondered how costly it is to <em>always</em> assume that invoke is required...</p>\n\n<pre><code>private void OnCoolEvent(CoolObjectEventArgs e)\n{\n BeginInvoke((o,e) =&gt; /*do work here*/,this, e);\n}\n</code></pre>\n" }, { "answer_id": 22397, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 6, "selected": true, "text": "<p>A couple of observations:</p>\n\n<ul>\n<li>Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: </li>\n</ul>\n\n<pre class=\"lang-cs prettyprint-override\"><code> BeginInvoke(new EventHandler&lt;CoolObjectEventArgs&gt;(mCoolObject_CoolEvent), \n sender, \n args);\n</code></pre>\n\n<ul>\n<li><p>Also you don't need to create and populate the object array because the args parameter is a \"params\" type so you can just pass in the list.</p></li>\n<li><p>I would probably favor <code>Invoke</code> over <code>BeginInvoke</code> as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to <code>EndInvoke</code>. What would happen is that your app will end up getting a <code>TargetInvocationException</code> instead.</p></li>\n</ul>\n" }, { "answer_id": 22415, "author": "On Freund", "author_id": 2150, "author_profile": "https://Stackoverflow.com/users/2150", "pm_score": 0, "selected": false, "text": "<p>You can try to develop some sort of a generic component that accepts a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx\" rel=\"nofollow noreferrer\">SynchronizationContext</a> as input and uses it to invoke the events.</p>\n" }, { "answer_id": 22470, "author": "gbc", "author_id": 1667, "author_profile": "https://Stackoverflow.com/users/1667", "pm_score": 2, "selected": false, "text": "<p>As an interesting side note, WPF's binding handles marshaling automatically so you can bind the UI to object properties that are modified on background threads without having to do anything special. This has proven to be a great timesaver for me.</p>\n\n<p>In XAML:</p>\n\n<pre><code>&lt;TextBox Text=\"{Binding Path=Name}\"/&gt;\n</code></pre>\n" }, { "answer_id": 258385, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 6, "selected": false, "text": "<p>I have <a href=\"https://github.com/domenic/extensions/blob/master/WindowsFormsInvokingExtensions.cs\" rel=\"noreferrer\">some code for this</a> online. It's much nicer than the other suggestions; definitely check it out.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n // You could use \"() =&gt;\" in place of \"delegate\"; it's a style choice.\n this.Invoke(delegate\n {\n // Do the dirty work of my method here.\n });\n}\n</code></pre>\n" }, { "answer_id": 803445, "author": "Dmitri Nesteruk", "author_id": 9476, "author_profile": "https://Stackoverflow.com/users/9476", "pm_score": 2, "selected": false, "text": "<p>I think the cleanest way is <strong>definitely</strong> to go the AOP route. Make a few aspects, add the necessary attributes, and you never have to check thread affinity again.</p>\n" }, { "answer_id": 12743503, "author": "TarPista", "author_id": 1722587, "author_profile": "https://Stackoverflow.com/users/1722587", "pm_score": 3, "selected": false, "text": "<p>I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace CrossThreadCalls\n{\n public static class clsCrossThreadCalls\n {\n private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);\n public static void SetAnyProperty(Control c, string Property, object Value)\n {\n if (c.GetType().GetProperty(Property) != null)\n {\n //The given property exists\n if (c.InvokeRequired)\n {\n SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);\n c.BeginInvoke(d, c, Property, Value);\n }\n else\n {\n c.GetType().GetProperty(Property).SetValue(c, Value, null);\n }\n }\n }\n\n private delegate void SetTextPropertyCallBack(Control c, string Value);\n public static void SetTextProperty(Control c, string Value)\n {\n if (c.InvokeRequired)\n {\n SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);\n c.BeginInvoke(d, c, Value);\n }\n else\n {\n c.Text = Value;\n }\n }\n }\n</code></pre>\n\n<p>And you can simply use SetAnyProperty() from another thread:</p>\n\n<pre><code>CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, \"Text\", KvaserCanReader.GetSpeed.ToString());\n</code></pre>\n\n<p>In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.</p>\n" }, { "answer_id": 31263315, "author": "The Lonely Coder", "author_id": 1201038, "author_profile": "https://Stackoverflow.com/users/1201038", "pm_score": 2, "selected": false, "text": "<p>Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.</p>\n\n<pre><code> #region SyncContextCancel\n\n private SynchronizationContext _syncContextCancel;\n\n /// &lt;summary&gt;\n /// Gets the synchronization context used for UI-related operations.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The synchronization context.&lt;/value&gt;\n protected SynchronizationContext SyncContextCancel\n {\n get { return _syncContextCancel; }\n }\n\n #endregion //SyncContextCancel\n\n public void CancelCurrentDbCommand()\n {\n _syncContextCancel = SynchronizationContext.Current;\n\n //ThreadPool.QueueUserWorkItem(CancelWork, null);\n\n Thread worker = new Thread(new ThreadStart(CancelWork));\n worker.Priority = ThreadPriority.Highest;\n worker.Start();\n }\n\n SQLiteConnection _connection;\n private void CancelWork()//object state\n {\n bool success = false;\n\n try\n {\n if (_connection != null)\n {\n log.Debug(\"call cancel\");\n _connection.Cancel();\n log.Debug(\"cancel complete\");\n _connection.Close();\n log.Debug(\"close complete\");\n success = true;\n log.Debug(\"long running query cancelled\" + DateTime.Now.ToLongTimeString());\n }\n }\n catch (Exception ex)\n {\n log.Error(ex.Message, ex);\n }\n\n SyncContextCancel.Send(CancelCompleted, new object[] { success });\n }\n\n public void CancelCompleted(object state)\n {\n object[] args = (object[])state;\n bool success = (bool)args[0];\n\n if (success)\n {\n log.Debug(\"long running query cancelled\" + DateTime.Now.ToLongTimeString());\n\n }\n }\n</code></pre>\n" }, { "answer_id": 66629283, "author": "mahirgul", "author_id": 2703120, "author_profile": "https://Stackoverflow.com/users/2703120", "pm_score": -1, "selected": false, "text": "<p>I am using something like</p>\n<pre><code>Invoke((Action)(() =&gt;\n {\n //your code\n }));\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: ``` // earlier in the code mCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent); // then private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here } ```
A couple of observations: * Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: ```cs BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args); ``` * Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list. * I would probably favor `Invoke` over `BeginInvoke` as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to `EndInvoke`. What would happen is that your app will end up getting a `TargetInvocationException` instead.
22,379
<p>I'm wondering how you can implement a program similar to <code>tail -f</code> in C/C++, a program that watches for and processes new lines added to a log file?</p>
[ { "answer_id": 22384, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime#18635\">See here</a></p>\n\n<p>You could either call out to tail and retrieve the stream back into your app, or as it's open source, maybe try to pull it into your own code.</p>\n\n<p>Also, it is possible in C++ iostream to open a file for viewing only and just read to the end, while buffering the last 10-20 lines, then output that.</p>\n" }, { "answer_id": 22399, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 4, "selected": true, "text": "<p>You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details.</p>\n\n<p>Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same:</p>\n\n<pre><code>wembley 0 /home/jj33/swap &gt;#&gt; cat p\nmy $f = shift;\nopen(I, \"&lt;$f\") || die \"Couldn't open $f: $!\\n\";\n\nwhile (1) {\n seek(I, 0, 1);\n while (defined(my $l = &lt;I&gt;)) {\n print \"Got: $l\";\n }\n print \"Hit EOF, sleeping\\n\";\n sleep(10);\n}\nwembley 0 /home/jj33/swap &gt;#&gt; cat tfile\nThis is\nsome\ntext\nin\na file\nwembley 0 /home/jj33/swap &gt;#&gt; perl p tfile\nGot: This is\nGot: some\nGot: text\nGot: in\nGot: a file\nHit EOF, sleeping\n</code></pre>\n\n<p>Then, in another session:</p>\n\n<pre><code>wembley 0 /home/jj33/swap &gt; echo \"another line of text\" &gt;&gt; tfile\n</code></pre>\n\n<p>And back to the original program output:</p>\n\n<pre><code>Hit EOF, sleeping\nGot: another line of text\nHit EOF, sleeping\n</code></pre>\n" }, { "answer_id": 22400, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 0, "selected": false, "text": "<p>I think what you're looking for is the select() call in c/c++. I found a copy of the man page here: <a href=\"http://www.opengroup.org/onlinepubs/007908775/xsh/select.html\" rel=\"nofollow noreferrer\">http://www.opengroup.org/onlinepubs/007908775/xsh/select.html</a>. Select takes file descriptors as arguments and tells you when one of them has changed and is ready for reading.</p>\n" }, { "answer_id": 22430, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>The tail program is open source, so you could reference that. I wondered the same thing and looked at the code a while back, thinking it would be pretty simple, but I was surprised at how complex it was. There are lots of gotchas that have to be taken into account.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
I'm wondering how you can implement a program similar to `tail -f` in C/C++, a program that watches for and processes new lines added to a log file?
You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details. Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same: ``` wembley 0 /home/jj33/swap >#> cat p my $f = shift; open(I, "<$f") || die "Couldn't open $f: $!\n"; while (1) { seek(I, 0, 1); while (defined(my $l = <I>)) { print "Got: $l"; } print "Hit EOF, sleeping\n"; sleep(10); } wembley 0 /home/jj33/swap >#> cat tfile This is some text in a file wembley 0 /home/jj33/swap >#> perl p tfile Got: This is Got: some Got: text Got: in Got: a file Hit EOF, sleeping ``` Then, in another session: ``` wembley 0 /home/jj33/swap > echo "another line of text" >> tfile ``` And back to the original program output: ``` Hit EOF, sleeping Got: another line of text Hit EOF, sleeping ```
22,409
<p>I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...</p> <p>With the release of ColdFusion 8, we got the <a href="http://cfquickdocs.com/cf8/?getDoc=cfimage" rel="nofollow noreferrer">CFImage</a> tag, but it doesn't support this conversion; and nor does <a href="http://x.com" rel="nofollow noreferrer">Image.cfc</a>, or <a href="http://x.com" rel="nofollow noreferrer">Alagad's Image Component</a>.</p> <p>However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:</p> <pre><code>&lt;cfset jthread = createObject("java", "java.lang.Thread")/&gt; &lt;cfset jthread.sleep(5000)/&gt; </code></pre> <p>I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?</p>
[ { "answer_id": 23577, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 4, "selected": false, "text": "<p>A very simple formula for converting from CMYK to RGB ignoring all color profiles is:</p>\n\n<pre>\n R = ( (255-C)*(255-K) ) / 255;\n G = ( (255-M)*(255-K) ) / 255;\n B = ( (255-Y)*(255-K) ) / 255;\n</pre>\n\n<p>This code requires CMYK values to be in rage of 0-255. If you have 0 to 100 or 0.0 to 1.0 you'll have to convert the values.</p>\n\n<p>Hope this will get you started.</p>\n\n<p>As for the java and ColdFusion interfacing, I'm sorry, but I have no idea how to do that.</p>\n" }, { "answer_id": 275661, "author": "Jas Panesar", "author_id": 35886, "author_profile": "https://Stackoverflow.com/users/35886", "pm_score": 1, "selected": false, "text": "<p>The tag cfx_image may be of use to you. I haven't used it in a while but I remember it had a ton of features.</p>\n\n<p>Alternatively, you might be able to script a windows app such as Irfanview (via commandline using cfexecute) to process images.</p>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 848533, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 4, "selected": true, "text": "<p>I use the Java ImageIO libraries (<a href=\"https://jai-imageio.dev.java.net\" rel=\"noreferrer\">https://jai-imageio.dev.java.net</a>). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with.</p>\n\n<p>Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong.</p>\n\n<p>The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative.</p>\n\n<p>Below is some code to convert a CMYK image into an RGB image of any supported format.</p>\n\n<p>Thank you,<br>\nRandy Stegbauer</p>\n\n<pre><code>package cmyk;\n\nimport java.awt.color.ColorSpace;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.ColorConvertOp;\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.imageio.ImageIO;\n\nimport org.apache.commons.lang.StringUtils;\n\npublic class Main\n{\n\n /**\n * Creates new RGB images from all the CMYK images passed\n * in on the command line.\n * The new filename generated is, for example \"GIF_original_filename.gif\".\n *\n */\n public static void main(String[] args)\n {\n for (int ii = 0; ii &lt; args.length; ii++)\n {\n String filename = args[ii];\n boolean cmyk = isCMYK(filename);\n System.out.println(cmyk + \": \" + filename);\n if (cmyk)\n {\n try\n {\n String rgbFile = cmyk2rgb(filename);\n System.out.println(isCMYK(rgbFile) + \": \" + rgbFile);\n }\n catch (IOException e)\n {\n System.out.println(e.getMessage());\n }\n }\n }\n }\n\n /**\n * If 'filename' is a CMYK file, then convert the image into RGB,\n * store it into a JPEG file, and return the new filename.\n *\n * @param filename\n */\n private static String cmyk2rgb(String filename) throws IOException\n {\n // Change this format into any ImageIO supported format.\n String format = \"gif\";\n File imageFile = new File(filename);\n String rgbFilename = filename;\n BufferedImage image = ImageIO.read(imageFile);\n if (image != null)\n {\n int colorSpaceType = image.getColorModel().getColorSpace().getType();\n if (colorSpaceType == ColorSpace.TYPE_CMYK)\n {\n BufferedImage rgbImage =\n new BufferedImage(\n image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);\n ColorConvertOp op = new ColorConvertOp(null);\n op.filter(image, rgbImage);\n\n rgbFilename = changeExtension(imageFile.getName(), format);\n rgbFilename = new File(imageFile.getParent(), format + \"_\" + rgbFilename).getPath();\n ImageIO.write(rgbImage, format, new File(rgbFilename));\n }\n }\n return rgbFilename;\n }\n\n /**\n * Change the extension of 'filename' to 'newExtension'.\n *\n * @param filename\n * @param newExtension\n * @return filename with new extension\n */\n private static String changeExtension(String filename, String newExtension)\n {\n String result = filename;\n if (filename != null &amp;&amp; newExtension != null &amp;&amp; newExtension.length() != 0);\n {\n int dot = filename.lastIndexOf('.');\n if (dot != -1)\n {\n result = filename.substring(0, dot) + '.' + newExtension;\n }\n }\n return result;\n }\n\n private static boolean isCMYK(String filename)\n {\n boolean result = false;\n BufferedImage img = null;\n try\n {\n img = ImageIO.read(new File(filename));\n }\n catch (IOException e)\n {\n System.out.println(e.getMessage() + \": \" + filename);\n }\n if (img != null)\n {\n int colorSpaceType = img.getColorModel().getColorSpace().getType();\n result = colorSpaceType == ColorSpace.TYPE_CMYK;\n }\n\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 17498325, "author": "James Moberg", "author_id": 693068, "author_profile": "https://Stackoverflow.com/users/693068", "pm_score": 0, "selected": false, "text": "<p>I know that this question is old, but I still encounter problems with CMYK images &amp; ColdFusion. However, I just read a CMYK JPEG image using ColdFusion 10 and resaved it. The saved image was able to to be read using ColdFusion 9 (which is only capable of reading RGB JPEGs.) I'm not sure if this conversion is intentional or not and I don't currently have any way of identifying whether the source image's color profile is CMYK or not as the saved color profile still appears to be the same.</p>\n\n<pre><code>&lt;cfset imgData = ImageRead(expandPath(\"./CMYK_image.jpg\"))&gt;\n&lt;cfset ImageWrite(imgData, expandPath(\"./Saved_image.jpg\"))&gt;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751/" ]
I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done... With the release of ColdFusion 8, we got the [CFImage](http://cfquickdocs.com/cf8/?getDoc=cfimage) tag, but it doesn't support this conversion; and nor does [Image.cfc](http://x.com), or [Alagad's Image Component](http://x.com). However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process: ``` <cfset jthread = createObject("java", "java.lang.Thread")/> <cfset jthread.sleep(5000)/> ``` I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?
I use the Java ImageIO libraries (<https://jai-imageio.dev.java.net>). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with. Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong. The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative. Below is some code to convert a CMYK image into an RGB image of any supported format. Thank you, Randy Stegbauer ``` package cmyk; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.commons.lang.StringUtils; public class Main { /** * Creates new RGB images from all the CMYK images passed * in on the command line. * The new filename generated is, for example "GIF_original_filename.gif". * */ public static void main(String[] args) { for (int ii = 0; ii < args.length; ii++) { String filename = args[ii]; boolean cmyk = isCMYK(filename); System.out.println(cmyk + ": " + filename); if (cmyk) { try { String rgbFile = cmyk2rgb(filename); System.out.println(isCMYK(rgbFile) + ": " + rgbFile); } catch (IOException e) { System.out.println(e.getMessage()); } } } } /** * If 'filename' is a CMYK file, then convert the image into RGB, * store it into a JPEG file, and return the new filename. * * @param filename */ private static String cmyk2rgb(String filename) throws IOException { // Change this format into any ImageIO supported format. String format = "gif"; File imageFile = new File(filename); String rgbFilename = filename; BufferedImage image = ImageIO.read(imageFile); if (image != null) { int colorSpaceType = image.getColorModel().getColorSpace().getType(); if (colorSpaceType == ColorSpace.TYPE_CMYK) { BufferedImage rgbImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(image, rgbImage); rgbFilename = changeExtension(imageFile.getName(), format); rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath(); ImageIO.write(rgbImage, format, new File(rgbFilename)); } } return rgbFilename; } /** * Change the extension of 'filename' to 'newExtension'. * * @param filename * @param newExtension * @return filename with new extension */ private static String changeExtension(String filename, String newExtension) { String result = filename; if (filename != null && newExtension != null && newExtension.length() != 0); { int dot = filename.lastIndexOf('.'); if (dot != -1) { result = filename.substring(0, dot) + '.' + newExtension; } } return result; } private static boolean isCMYK(String filename) { boolean result = false; BufferedImage img = null; try { img = ImageIO.read(new File(filename)); } catch (IOException e) { System.out.println(e.getMessage() + ": " + filename); } if (img != null) { int colorSpaceType = img.getColorModel().getColorSpace().getType(); result = colorSpaceType == ColorSpace.TYPE_CMYK; } return result; } } ```
22,417
<p>Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID</p> <p>I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters.</p> <p>I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring.</p> <p>Anyone ever tackle something like this and have insight? </p>
[ { "answer_id": 22421, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 1, "selected": false, "text": "<p>I would probably leave it up to your application to perform the scoring. Check out <a href=\"http://www.codinghorror.com/blog/archives/001152.html\" rel=\"nofollow noreferrer\">Maybe Normalizing Isn't Normal</a> by Jeff Atwood.</p>\n" }, { "answer_id": 22424, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>The architecture you are talking about could become very cumbersome in the long run, and if you need to change the questions it means more changes to the UDF you are using.</p>\n\n<p>I would think you could probably do your analysis in code without necessarily de-normalizing your database. De-normalization could also lend to inflexibility, or at least added expense to update, down the road.</p>\n" }, { "answer_id": 22426, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<p>No way, you definitely want to keep it normalized. It's not even that hard of a query.</p>\n\n<p>Basically, you want to left join the students correct answers with the total answers for that question, and do a count. This will give you the percent correct. Do that for each student, and put the minimum percent correct in a where clause.</p>\n" }, { "answer_id": 22427, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Denormalization is generally considered a last resort. The problem seems very similar to survey applications, which are very common. Without seeing your data model, it's difficult to propose a solution, but I will say that it is definitely possible. I'm wondering why you need 20 parameters to that function?</p>\n\n<p>A relational set-based solution will be simpler and faster in most cases.</p>\n" }, { "answer_id": 22448, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "<p>If I understand your schema and question correctly, how about something like this:</p>\n\n<pre><code>select student_name, score\nfrom students\n join (select student_answers.student_id, count(*) as score\n from student_answers, answer_key\n group by student_id\n where student_answers.question_id = answer_key.question_id\n and student_answers.answer = answer_key.answer)\n as student_scores on students.student_id = student_scores.student_id\nwhere score &gt;= 7\norder by score, student_name\n</code></pre>\n\n<p>That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.</p>\n" }, { "answer_id": 22494, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>This query should be quite easy... assuming you have the correct answer stored in the question table. You do have the correct answer stored in the question table, right?</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters. I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring. Anyone ever tackle something like this and have insight?
If I understand your schema and question correctly, how about something like this: ``` select student_name, score from students join (select student_answers.student_id, count(*) as score from student_answers, answer_key group by student_id where student_answers.question_id = answer_key.question_id and student_answers.answer = answer_key.answer) as student_scores on students.student_id = student_scores.student_id where score >= 7 order by score, student_name ``` That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.
22,429
<p>Is it possible to embed an inline search box into a web page which provides similar functionality to the <a href="http://www.ie7pro.com/inline-search.html" rel="noreferrer">IE7Pro Inline Search</a> or similar plugins for Firefox/Safari?</p>
[ { "answer_id": 22421, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 1, "selected": false, "text": "<p>I would probably leave it up to your application to perform the scoring. Check out <a href=\"http://www.codinghorror.com/blog/archives/001152.html\" rel=\"nofollow noreferrer\">Maybe Normalizing Isn't Normal</a> by Jeff Atwood.</p>\n" }, { "answer_id": 22424, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>The architecture you are talking about could become very cumbersome in the long run, and if you need to change the questions it means more changes to the UDF you are using.</p>\n\n<p>I would think you could probably do your analysis in code without necessarily de-normalizing your database. De-normalization could also lend to inflexibility, or at least added expense to update, down the road.</p>\n" }, { "answer_id": 22426, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<p>No way, you definitely want to keep it normalized. It's not even that hard of a query.</p>\n\n<p>Basically, you want to left join the students correct answers with the total answers for that question, and do a count. This will give you the percent correct. Do that for each student, and put the minimum percent correct in a where clause.</p>\n" }, { "answer_id": 22427, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Denormalization is generally considered a last resort. The problem seems very similar to survey applications, which are very common. Without seeing your data model, it's difficult to propose a solution, but I will say that it is definitely possible. I'm wondering why you need 20 parameters to that function?</p>\n\n<p>A relational set-based solution will be simpler and faster in most cases.</p>\n" }, { "answer_id": 22448, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "<p>If I understand your schema and question correctly, how about something like this:</p>\n\n<pre><code>select student_name, score\nfrom students\n join (select student_answers.student_id, count(*) as score\n from student_answers, answer_key\n group by student_id\n where student_answers.question_id = answer_key.question_id\n and student_answers.answer = answer_key.answer)\n as student_scores on students.student_id = student_scores.student_id\nwhere score &gt;= 7\norder by score, student_name\n</code></pre>\n\n<p>That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.</p>\n" }, { "answer_id": 22494, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>This query should be quite easy... assuming you have the correct answer stored in the question table. You do have the correct answer stored in the question table, right?</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2418/" ]
Is it possible to embed an inline search box into a web page which provides similar functionality to the [IE7Pro Inline Search](http://www.ie7pro.com/inline-search.html) or similar plugins for Firefox/Safari?
If I understand your schema and question correctly, how about something like this: ``` select student_name, score from students join (select student_answers.student_id, count(*) as score from student_answers, answer_key group by student_id where student_answers.question_id = answer_key.question_id and student_answers.answer = answer_key.answer) as student_scores on students.student_id = student_scores.student_id where score >= 7 order by score, student_name ``` That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.
22,444
<p>I have this gigantic ugly string:</p> <pre class="lang-none prettyprint-override"><code>J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully </code></pre> <p>I'm trying to extract pieces from it using regex. In this case, I want to grab everything after <code>Project Name</code> up to the part where it says <code>J0000011:</code> (the 11 is going to be a different number every time).</p> <p>Here's the regex I've been playing with:</p> <pre class="lang-none prettyprint-override"><code>Project name:\s+(.*)\s+J[0-9]{7}: </code></pre> <p>The problem is that it doesn't stop until it hits the <strong>J0000020:</strong> at the end.</p> <p>How do I make the regex stop at the first occurrence of <code>J[0-9]{7}</code>?</p>
[ { "answer_id": 22449, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 8, "selected": true, "text": "<p>Make <code>.*</code> non-greedy by adding '<code>?</code>' after it:</p>\n\n<pre><code>Project name:\\s+(.*?)\\s+J[0-9]{7}:\n</code></pre>\n" }, { "answer_id": 22457, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>Using non-greedy quantifiers here is probably the best solution, also because it is more efficient than the greedy alternative: Greedy matches generally go as far as they can (here, until the end of the text!) and then trace back character after character to try and match the part coming afterwards.</p>\n\n<p>However, consider using a negative character class instead:</p>\n\n<pre><code>Project name:\\s+(\\S*)\\s+J[0-9]{7}:\n</code></pre>\n\n<p><code>\\S</code> means “everything except a whitespace and this is exactly what you want.</p>\n" }, { "answer_id": 22461, "author": "Hershi", "author_id": 1596, "author_profile": "https://Stackoverflow.com/users/1596", "pm_score": 1, "selected": false, "text": "<p>I would also recommend you experiment with regular expressions using \"Expresso\" - it's a utility a great (and free) utility for regex editing and testing.</p>\n\n<p>One of its upsides is that its UI exposes a lot of regex functionality that people unexprienced with regex might not be familiar with, in a way that it would be easy for them to learn these new concepts.</p>\n\n<p>For example, when building your regex using the UI, and choosing \"*\", you have the ability to check the checkbox \"As few as possible\" and see the resulting regex, as well as test its behavior, even if you were unfamiliar with non-greedy expressions before.</p>\n\n<p>Available for download at their site:\n<a href=\"http://www.ultrapico.com/Expresso.htm\" rel=\"nofollow noreferrer\">http://www.ultrapico.com/Expresso.htm</a></p>\n\n<p>Express download:\n<a href=\"http://www.ultrapico.com/ExpressoDownload.htm\" rel=\"nofollow noreferrer\">http://www.ultrapico.com/ExpressoDownload.htm</a></p>\n" }, { "answer_id": 22480, "author": "Svend", "author_id": 2491, "author_profile": "https://Stackoverflow.com/users/2491", "pm_score": 3, "selected": false, "text": "<p>Well, <code>\".*\"</code> is a greedy selector. You make it non-greedy by using <code>\".*?\"</code> When using the latter construct, the regex engine will, at every step it matches text into the <code>\".\"</code> attempt to match whatever make come after the <code>\".*?\"</code>. This means that if for instance nothing comes after the <code>\".*?\"</code>, then it matches nothing. </p>\n\n<p>Here's what I used. <code>s</code> contains your original string. This code is .NET specific, but most flavors of regex will have something similar.</p>\n\n<pre><code>string m = Regex.Match(s, @\"Project name: (?&lt;name&gt;.*?) J\\d+\").Groups[\"name\"].Value;\n</code></pre>\n" }, { "answer_id": 51357203, "author": "Shailendra", "author_id": 1556909, "author_profile": "https://Stackoverflow.com/users/1556909", "pm_score": 0, "selected": false, "text": "<p>(Project name:\\s+[A-Z]:(?:\\\\w+)+.[a-zA-Z]+\\s+J[0-9]{7})(?=:)</p>\n\n<p>This will work for you.</p>\n\n<p>Adding (?:\\\\w+)+.[a-zA-Z]+ will be more restrictive instead of .*</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I have this gigantic ugly string: ```none J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM J0000010: Project name: E:\foo.pf J0000011: Job name: MBiek Direct Mail Test J0000020: Document 1 - Completed successfully ``` I'm trying to extract pieces from it using regex. In this case, I want to grab everything after `Project Name` up to the part where it says `J0000011:` (the 11 is going to be a different number every time). Here's the regex I've been playing with: ```none Project name:\s+(.*)\s+J[0-9]{7}: ``` The problem is that it doesn't stop until it hits the **J0000020:** at the end. How do I make the regex stop at the first occurrence of `J[0-9]{7}`?
Make `.*` non-greedy by adding '`?`' after it: ``` Project name:\s+(.*?)\s+J[0-9]{7}: ```
22,459
<p>I'm getting some strange, intermittent, data aborts (&lt; 5% of the time) in some of my code, when calling <code>memset()</code>. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.</p> <p>I'm using the following code:</p> <pre><code>char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); </code></pre> <p>As you can see, I'm not trying to use memset with a size larger that what's originally allocated with <code>malloc()</code></p> <p>Anyone see what might be wrong with this?</p>
[ { "answer_id": 22464, "author": "Doug", "author_id": 1618, "author_profile": "https://Stackoverflow.com/users/1618", "pm_score": 0, "selected": false, "text": "<p>Have you tried using Valgrind? That is usually the fastest and easiest way to debug these sorts of errors. If you are reading or writing outside the bounds of allocated memory, it will flag it for you.</p>\n" }, { "answer_id": 22473, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 5, "selected": true, "text": "<p><code>malloc</code> can return <code>NULL</code> if no memory is available. You're not checking for that.</p>\n" }, { "answer_id": 22486, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 2, "selected": false, "text": "<p>There's a couple of things. You're using <code>sprintf</code> which is inherently unsafe; unless you're 100% positive that you're not going to exceed the size of the buffer, you should almost <em>always</em> prefer <code>snprintf</code>. The same applies to <code>strcat</code>; prefer the safer alternative <code>strncat</code>.</p>\n\n<p>Obviously this may not fix anything, but it goes a <em>long</em> way in helping spot what might otherwise be very annoying to spot bugs.</p>\n" }, { "answer_id": 22488, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>malloc can return NULL if no memory is\n available. You're not checking for\n that.</p>\n</blockquote>\n\n<p>Right you are... I didn't think about that as I was monitoring the memory and it there was enough free. Is there any way for there to be available memory on the system but for malloc to fail?</p>\n\n<blockquote>\n <p>Yes, if memory is fragmented. Also, when you say \"monitoring memory,\" there may be something on the system which occasionally consumes a lot of memory and then releases it before you notice. If your call to <code>malloc</code> occurs then, there won't be any memory available. -- <strong>Joel</strong></p>\n</blockquote>\n\n<p>Either way...I will add that check :)</p>\n" }, { "answer_id": 22495, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>You're using sprintf which is\n inherently unsafe; unless you're 100%\n positive that you're not going to\n exceed the size of the buffer, you\n should almost always prefer snprintf.\n The same applies to strcat; prefer the\n safer alternative strncat.</p>\n</blockquote>\n\n<p>Yeah..... I mostly do .NET lately and old habits die hard. I likely pulled that code out of something else that was written before my time...</p>\n\n<p>But I'll try not to use those in the future ;)</p>\n" }, { "answer_id": 22496, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 0, "selected": false, "text": "<p>You know it might not even be your code... Are there any other programs running that could have a memory leak?</p>\n" }, { "answer_id": 22799, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 1, "selected": false, "text": "<p><code>wcstombs</code> doesn't get the size of the destination, so it can, in theory, buffer overflow.</p>\n\n<p>And why are you using <code>sprintf</code> with what I assume are constants? Just use:</p>\n\n<p><code>EZMPPOST\" \" EZMPTAG \"/\" EZMPVER \" \" TYPETXT EOL</code></p>\n\n<p>C and C++ combines string literal declarations into a single string.</p>\n" }, { "answer_id": 107412, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 0, "selected": false, "text": "<p>It could be your processor. Some CPUs can't address single bytes, and require you to work in words or chunk sizes, or have instructions that can only be used on word or chunk aligned data. </p>\n\n<p>Usually the compiler is made aware of these and works around them, but sometimes you can malloc a region as bytes, and then try to address it as a structure or wider-than-a-byte field, and the compiler won't catch it, but the processor will throw a data exception later. </p>\n\n<p>It wouldn't happen unless you're using an unusual CPU. ARM9 will do that, for example, but i686 won't. I see it's tagged windows mobile, so maybe you do have this CPU issue.</p>\n" }, { "answer_id": 107431, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>Instead of doing <code>malloc</code> followed by <code>memset</code>, you should be using <code>calloc</code> which will clear the newly allocated memory for you. Other than that, do what Joel said.</p>\n" }, { "answer_id": 128706, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 0, "selected": false, "text": "<p>NB borrowed some comments from other answers and integrated into a whole. The code is all mine...</p>\n\n<ul>\n<li>Check your error codes. E.g. malloc can return NULL if no memory is available. This could be causing your data abort.</li>\n<li>sizeof(char) is 1 by definition</li>\n<li>Use snprintf not sprintf to avoid buffer overruns \n\n<ul>\n<li>If EZMPPOST etc are constants, then you don't need a format string, you can just combined several string literals as STRING1 \" \" STRING2 \" \" STRING3 and strcat the whole lot. </li>\n</ul></li>\n<li>You are using much more memory than you need to.</li>\n<li>With one minor change, you don't need to call memset in the first place. Nothing\nreally requires zero initialisation here.</li>\n</ul>\n\n<p>This code does the same thing, safely, runs faster, and uses less memory.</p>\n\n<pre><code> // sizeof(char) is 1 by definition. This memory does not require zero\n // initialisation. If it did, I'd use calloc.\n const int max_msg = 2048;\n char *msg = (char*)malloc(max_msg);\n if(!msg)\n {\n // Allocaton failure\n return;\n }\n // Use snprintf instead of sprintf to avoid buffer overruns\n // we write directly to msg, instead of using a temporary buffer and then calling\n // strcat. This saves CPU time, saves the temporary buffer, and removes the need\n // to zero initialise msg.\n snprintf(msg, max_msg, \"%s %s/%s %s%s\", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);\n\n //Add Data\n size_t len = wcslen(gdevID);\n // No need to zero init this\n char* temp = (char*)malloc(len);\n if(!temp)\n {\n free(msg);\n return;\n }\n wcstombs(temp, gdevID, len);\n // No need to use a temporary buffer - just append directly to the msg, protecting \n // against buffer overruns.\n snprintf(msg + strlen(msg), \n max_msg - strlen(msg), \"%s: %s%s\", \"DeviceID\", temp, EOL);\n free(temp);\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling `memset()`. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: ``` char *msg = (char*)malloc(sizeof(char)*2048); char *temp = (char*)malloc(sizeof(char)*1024); memset(msg, 0, 2048); memset(temp, 0, 1024); char *tempstr = (char*)malloc(sizeof(char)*128); sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL); strcat(msg, temp); //Add Data memset(tempstr, '\0', 128); wcstombs(tempstr, gdevID, wcslen(gdevID)); sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL); strcat(msg, temp); ``` As you can see, I'm not trying to use memset with a size larger that what's originally allocated with `malloc()` Anyone see what might be wrong with this?
`malloc` can return `NULL` if no memory is available. You're not checking for that.
22,474
<p>How do I select all records that contain "LCS" within the title column in sql.</p>
[ { "answer_id": 22476, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 3, "selected": true, "text": "<pre><code>SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';\n</code></pre>\n\n<p>% is the wild card matcher.</p>\n" }, { "answer_id": 22478, "author": "rjrapson", "author_id": 1616, "author_profile": "https://Stackoverflow.com/users/1616", "pm_score": 0, "selected": false, "text": "<p>Look into the LIKE clause</p>\n" }, { "answer_id": 22489, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<p>Are you looking for all the tables with a column name which contains the LCS in them? If yes the do this</p>\n\n<pre><code>select table_name \nfrom information_schema.columns \nwhere column_name like '%lcs%'\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453046/" ]
How do I select all records that contain "LCS" within the title column in sql.
``` SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%'; ``` % is the wild card matcher.
22,503
<p>I have a form view, in the edit template I have two drop downs. Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback. Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2)</p> <p>On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error </p> <blockquote> <p>Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.</p> </blockquote> <p>Here is the drop down list #2:</p> <pre><code>&lt;asp:DropDownList ID="ProjectList" runat="server" SelectedValue='&lt;%# Bind("ConnectToProject_ID","{0:D}") %&gt;' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true"&gt; &lt;asp:ListItem Value="0" Text="{No Master Project}" Selected="True" /&gt; &lt;/asp:DropDownList&gt; </code></pre> <p>And here is the MasterProjectDataSource2:</p> <pre><code>&lt;asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server" SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" &gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID" PropertyName="SelectedValue" Type="Int32" /&gt; &lt;/SelectParameters&gt; &lt;/asp:ObjectDataSource&gt; </code></pre> <p>Any help on how to get this to work would be greatly appriciated.</p>
[ { "answer_id": 22797, "author": "Joel Meador", "author_id": 1976, "author_profile": "https://Stackoverflow.com/users/1976", "pm_score": 0, "selected": false, "text": "<p>Sounds like the controls aren't being databound properly after the postback.</p>\n\n<p>Are you databinding the first dropdown in the page or in the codebehind?\nIf codebehind, are you doing it in on_init or on_load every time?</p>\n\n<p>There might be an issue of the SelectedValue of the second drop down being set to a non-existent item after the postback.</p>\n" }, { "answer_id": 25612, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>Unless your 2nd dropdown is in a databound control (say, a Repeater) - I'm not sure what you're trying to bind SelectedValue to. Apparently, neither is .NET - since that's probably where the error is occurring. </p>\n\n<p>Where's Connect_ToProjectId supposed to come from?</p>\n" }, { "answer_id": 183587, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem with bound dropdownlists in a FormView. I worked around it by setting the selected value manually in the formview's \"OnDataBound\". </p>\n\n<p>(don't know where you get ConnectToProject_ID from)</p>\n\n<pre><code>FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\nddl.SelectedValue = String.Format(\"{0:D}\", ConnectToProject_ID);\n</code></pre>\n\n<p>When you ready to save, use the \"OnItemInserting\" event:</p>\n\n<pre><code>FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\ne.Values[\"ConnectToProject_ID\"] = ddl.SelectedValue;\n</code></pre>\n\n<p>or \"OnItemUpdating\"</p>\n\n<p>When you ready to save, use the \"OnItemInserting\" event:</p>\n\n<pre><code>FormView fv = (FormView)sender;\nDropDownList ddl = (DropDownList)fv.FindControl(\"ProjectList\");\ne.NewValues[\"ConnectToProject_ID\"] = ddl.SelectedValue;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2496/" ]
I have a form view, in the edit template I have two drop downs. Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback. Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2) On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error > > Databinding methods such as Eval(), > XPath(), and Bind() can only be used > in the context of a databound control. > > > Here is the drop down list #2: ``` <asp:DropDownList ID="ProjectList" runat="server" SelectedValue='<%# Bind("ConnectToProject_ID","{0:D}") %>' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true"> <asp:ListItem Value="0" Text="{No Master Project}" Selected="True" /> </asp:DropDownList> ``` And here is the MasterProjectDataSource2: ``` <asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server" SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" > <SelectParameters> <asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> ``` Any help on how to get this to work would be greatly appriciated.
I had a similar problem with bound dropdownlists in a FormView. I worked around it by setting the selected value manually in the formview's "OnDataBound". (don't know where you get ConnectToProject\_ID from) ``` FormView fv = (FormView)sender; DropDownList ddl = (DropDownList)fv.FindControl("ProjectList"); ddl.SelectedValue = String.Format("{0:D}", ConnectToProject_ID); ``` When you ready to save, use the "OnItemInserting" event: ``` FormView fv = (FormView)sender; DropDownList ddl = (DropDownList)fv.FindControl("ProjectList"); e.Values["ConnectToProject_ID"] = ddl.SelectedValue; ``` or "OnItemUpdating" When you ready to save, use the "OnItemInserting" event: ``` FormView fv = (FormView)sender; DropDownList ddl = (DropDownList)fv.FindControl("ProjectList"); e.NewValues["ConnectToProject_ID"] = ddl.SelectedValue; ```
22,509
<p>I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using <a href="http://www.stardeveloper.com/articles/display.html?article=2007110401&amp;page=1" rel="nofollow noreferrer">this implementation</a> (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again.</p> <p>Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not.</p> <p>Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.</p>
[ { "answer_id": 22563, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 0, "selected": false, "text": "<p>If you will be deploying on IIS 6 or IIS 7, just use the built-in IIS compression. We're using it on production sites for compressing HTML, CSS, and JavaScript with no errors. It also caches the compressed version on the server, so the compression hit is only taken once.</p>\n" }, { "answer_id": 22585, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": true, "text": "<p>Is it only CSS files that get corrupted? Do JS files (or any other static text files) come through ok?</p>\n\n<p>Also can you duplicate the behavior if you browse directly to the CSS file?</p>\n\n<p>I've only enabled compression on Windows 2003 server's IIS using this approach:</p>\n\n<ol>\n<li>IIS → Web Sites → Properties → Service tab, check both boxes</li>\n<li>IIS → Web Service Extensions → Right click, Add New<pre>\n Name\n Http Compression \n Required Files\n %systemroot%\\system32\\inetsrv\\gzip.dll </pre></li>\n<li>IIS → Right click top node, Internet Information Services, check <em>Enable Direct Metabase Edit</em></li>\n<li>Backup and Edit <code>%systemroot%\\system32\\inetsrv\\MetaBase.xml</code>\n\n<ol>\n<li>Find <code>Location =\"/LM/W3SVC/Filters/Compression/gzip\"</code>\n\n<ul>\n<li>Add <code>png</code>, <code>css</code>, <code>js</code> and any other static file extensions to <code>HcFileExtensions</code></li>\n<li>Add <code>aspx</code> and any other executable extensions to <code>HcScriptFileExtensions</code></li>\n<li>Save </li>\n</ul></li>\n</ol></li>\n<li>Restart IIS (run <code>iisreset</code>) </li>\n</ol>\n\n<p>If you have a Windows 2003/2008 server to play with you could try that approach.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using [this implementation](http://www.stardeveloper.com/articles/display.html?article=2007110401&page=1) (and tried a few others that hook into Application\_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again. Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not. Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.
Is it only CSS files that get corrupted? Do JS files (or any other static text files) come through ok? Also can you duplicate the behavior if you browse directly to the CSS file? I've only enabled compression on Windows 2003 server's IIS using this approach: 1. IIS → Web Sites → Properties → Service tab, check both boxes 2. IIS → Web Service Extensions → Right click, Add New ``` Name Http Compression Required Files %systemroot%\system32\inetsrv\gzip.dll ``` 3. IIS → Right click top node, Internet Information Services, check *Enable Direct Metabase Edit* 4. Backup and Edit `%systemroot%\system32\inetsrv\MetaBase.xml` 1. Find `Location ="/LM/W3SVC/Filters/Compression/gzip"` * Add `png`, `css`, `js` and any other static file extensions to `HcFileExtensions` * Add `aspx` and any other executable extensions to `HcScriptFileExtensions` * Save 5. Restart IIS (run `iisreset`) If you have a Windows 2003/2008 server to play with you could try that approach.
22,552
<p>I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.</p> <p>I tried this but it just barfs.</p> <pre><code>preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this-&gt;getResultVar('FullMessage'), $atmp ); </code></pre> <p>Is there are way to pass a regex in the above form to preg_match?</p>
[ { "answer_id": 22572, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>You can use the extended syntax:</p>\n\n<pre><code>preg_match(\"/\n test\n/x\", $foo, $bar);\n</code></pre>\n" }, { "answer_id": 22574, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "<p>OK, here's a solution:</p>\n\n<pre><code>preg_match(\n '/(?x)^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+/'\n , $this-&gt;getResultVar('FullMessage'), $atmp);\n</code></pre>\n\n<p>The key is <strong>(?x)</strong> at the beginning which makes whitespace insignificant and allows comments.</p>\n\n<p>It's also important that there's no whitespace between the starting and ending quotes and the start &amp; end of the regex.</p>\n\n<p>My first attempt like this gave errors:</p>\n\n<pre><code>preg_match('\n /(?x)^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+/\n ', $this-&gt;getResultVar('FullMessage'), $atmp);\n</code></pre>\n\n<p>What <a href=\"https://stackoverflow.com/questions/22552/passing-a-commented-multi-line-freespace-regex-to-pregmatch#22572\">Konrad said</a> also works and feels a little easier than sticking <strong>(?x)</strong> at the beginning.</p>\n" }, { "answer_id": 22580, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "<p>In PHP the comment syntax looks like this:<pre>(?# Your comment here)</pre></p>\n<pre><code>preg_match('\n ^J[0-9]{7}:\\s+\n (.*?) (?#Extract the Transaction Start Date msg)\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) (?#Extract the Project Name)\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) (?#Extract the Job Name)\n \\s+J[0-9]{7}:\\s+\n ', $this-&gt;getResultVar('FullMessage'), $atmp);\n</code></pre>\n<p>For more information see the <a href=\"http://nl.php.net/manual/en/regexp.reference.php\" rel=\"nofollow noreferrer\">PHP Regular Expression Syntax Reference</a></p>\n<p>You can also use the PCRE_EXTENDED (or 'x') <a href=\"http://nl.php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">Pattern Modifier</a> as Mark shows in his example.</p>\n" }, { "answer_id": 22582, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 1, "selected": false, "text": "<ul>\n<li>You should add delimiters: the first character of the regex will be used to indicate the end of the pattern.</li>\n<li>You should add the 'x' flag. This has the same result as putting (?x) at the beginning, but it is more readable imho.</li>\n</ul>\n" }, { "answer_id": 22589, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "<p>Yes, you can add the <code>/x</code> <a href=\"http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">Pattern Modifier</a>.</p>\n\n<blockquote>\n <p>This modifier turns on additional\n functionality of PCRE that is\n incompatible with Perl. Any backslash\n in a pattern that is followed by a\n letter that has no special meaning\n causes an error, thus reserving these\n combinations for future expansion. By\n default, as in Perl, a backslash\n followed by a letter with no special\n meaning is treated as a literal. There\n are at present no other features\n controlled by this modifier.</p>\n</blockquote>\n\n<p>For your example try this:</p>\n\n<pre><code>preg_match('/\n ^J[0-9]{7}:\\s+\n (.*?) #Extract the Transaction Start Date msg\n \\s+J[0-9]{7}:\\s+Project\\sname:\\s+\n (.*?) #Extract the Project Name\n \\s+J[0-9]{7}:\\s+Job\\sname:\\s+\n (.*?) #Extract the Job Name\n \\s+J[0-9]{7}:\\s+\n /x', $this-&gt;getResultVar('FullMessage'), $atmp);\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines. I tried this but it just barfs. ``` preg_match( '^J[0-9]{7}:\s+ (.*?) #Extract the Transaction Start Date msg \s+J[0-9]{7}:\s+Project\sname:\s+ (.*?) #Extract the Project Name \s+J[0-9]{7}:\s+Job\sname:\s+ (.*?) #Extract the Job Name \s+J[0-9]{7}:\s+', $this->getResultVar('FullMessage'), $atmp ); ``` Is there are way to pass a regex in the above form to preg\_match?
You can use the extended syntax: ``` preg_match("/ test /x", $foo, $bar); ```
22,566
<p>How do I get Perl to read the contents of a given directory into an array?</p> <p><a href="https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming" rel="noreferrer">Backticks</a> can do it, but is there some method using 'scandir' or a similar term?</p>
[ { "answer_id": 22573, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 7, "selected": true, "text": "<pre><code>opendir(D, \"/path/to/directory\") || die \"Can't open directory: $!\\n\";\nwhile (my $f = readdir(D)) {\n print \"\\$f = $f\\n\";\n}\nclosedir(D);\n</code></pre>\n\n<p>EDIT: Oh, sorry, missed the \"into an array\" part:</p>\n\n<pre><code>my $d = shift;\n\nopendir(D, \"$d\") || die \"Can't open directory $d: $!\\n\";\nmy @list = readdir(D);\nclosedir(D);\n\nforeach my $f (@list) {\n print \"\\$f = $f\\n\";\n}\n</code></pre>\n\n<p>EDIT2: Most of the other answers are valid, but I wanted to comment on <a href=\"https://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl#24436\">this answer</a> specifically, in which this solution is offered:</p>\n\n<pre><code>opendir(DIR, $somedir) || die \"Can't open directory $somedir: $!\";\n@dots = grep { (!/^\\./) &amp;&amp; -f \"$somedir/$_\" } readdir(DIR);\nclosedir DIR;\n</code></pre>\n\n<p>First, to document what it's doing since the poster didn't: it's passing the returned list from <a href=\"http://perldoc.perl.org/functions/readdir.html\" rel=\"noreferrer\">readdir()</a> through a <a href=\"http://perldoc.perl.org/functions/grep.html\" rel=\"noreferrer\">grep()</a> that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name <code>@dots</code> misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in <a href=\"http://en.wikipedia.org/wiki/Perl\" rel=\"noreferrer\">Perl</a>, and I thought it would be valuable to document. Another example seen a lot is:</p>\n\n<pre><code>@list = grep !/^\\.\\.?$/, readdir(D);\n</code></pre>\n\n<p>This snippet reads all contents from the directory handle D <strong>except</strong> '.' and '..', since those are very rarely desired to be used in the listing.</p>\n" }, { "answer_id": 22663, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 3, "selected": false, "text": "<p>This will do it, in one line (note the '*' wildcard at the end)</p>\n\n<pre><code>@files = &lt;/path/to/directory/*&gt;;\n# To demonstrate:\nprint join(\", \", @files);\n</code></pre>\n" }, { "answer_id": 22678, "author": "Mickey", "author_id": 1494, "author_profile": "https://Stackoverflow.com/users/1494", "pm_score": 1, "selected": false, "text": "<p>Here's an example of recursing through a directory structure and copying files from a backup script I wrote.</p>\n<pre><code>sub copy_directory {\nmy ($source, $dest) = @_;\nmy $start = time;\n\n# get the contents of the directory.\nopendir(D, $source);\nmy @f = readdir(D);\nclosedir(D);\n\n# recurse through the directory structure and copy files.\nforeach my $file (@f) {\n # Setup the full path to the source and dest files.\n my $filename = $source . &quot;\\\\&quot; . $file;\n my $destfile = $dest . &quot;\\\\&quot; . $file;\n \n # get the file info for the 2 files.\n my $sourceInfo = stat( $filename );\n my $destInfo = stat( $destfile );\n \n # make sure the destinatin directory exists.\n mkdir( $dest, 0777 );\n \n if ($file eq '.' || $file eq '..') {\n } elsif (-d $filename) { # if it's a directory then recurse into it.\n #print &quot;entering $filename\\n&quot;;\n copy_directory($filename, $destfile); \n } else { \n # Only backup the file if it has been created/modified since the last backup \n if( (not -e $destfile) || ($sourceInfo-&gt;mtime &gt; $destInfo-&gt;mtime ) ) {\n #print $filename . &quot; -&gt; &quot; . $destfile . &quot;\\n&quot;;\n copy( $filename, $destfile ) or print &quot;Error copying $filename: $!\\n&quot;;\n } \n } \n}\n\nprint &quot;$source copied in &quot; . (time - $start) . &quot; seconds.\\n&quot;; \n}\n</code></pre>\n" }, { "answer_id": 22762, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://search.cpan.org/~gbarr/IO-1.2301/IO/Dir.pm\" rel=\"nofollow noreferrer\">IO::Dir</a> is nice and provides a tied hash interface as well.</p>\n\n<p>From the perldoc:</p>\n\n<pre><code>use IO::Dir;\n$d = IO::Dir-&gt;new(\".\");\nif (defined $d) {\n while (defined($_ = $d-&gt;read)) { something($_); }\n $d-&gt;rewind;\n while (defined($_ = $d-&gt;read)) { something_else($_); }\n undef $d;\n}\n\ntie %dir, 'IO::Dir', \".\";\nforeach (keys %dir) {\n print $_, \" \" , $dir{$_}-&gt;size,\"\\n\";\n}\n</code></pre>\n\n<p>So you could do something like:</p>\n\n<pre><code>tie %dir, 'IO::Dir', $directory_name;\nmy @dirs = keys %dir;\n</code></pre>\n" }, { "answer_id": 22915, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": false, "text": "<p>A quick and dirty solution is to use <a href=\"http://perldoc.perl.org/functions/glob.html\" rel=\"noreferrer\">glob</a></p>\n\n<pre><code>@files = glob ('/path/to/dir/*');\n</code></pre>\n" }, { "answer_id": 24436, "author": "trjh", "author_id": 2620, "author_profile": "https://Stackoverflow.com/users/2620", "pm_score": 1, "selected": false, "text": "<p>Similar to the above, but I think the best version is (slightly modified) from \"perldoc -f readdir\":</p>\n\n<pre><code>opendir(DIR, $somedir) || die \"can't opendir $somedir: $!\";\n@dots = grep { (!/^\\./) &amp;&amp; -f \"$somedir/$_\" } readdir(DIR);\nclosedir DIR;\n</code></pre>\n" }, { "answer_id": 38016, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>You could use <a href=\"http://search.cpan.org/~rgarcia/perl-5.10.0/lib/DirHandle.pm\" rel=\"nofollow noreferrer\">DirHandle</a>:</p>\n\n<pre><code>use DirHandle;\n$d = new DirHandle \".\";\nif (defined $d)\n{\n while (defined($_ = $d-&gt;read)) { something($_); }\n $d-&gt;rewind;\n while (defined($_ = $d-&gt;read)) { something_else($_); }\n undef $d;\n}\n</code></pre>\n\n<p><code>DirHandle</code> provides an alternative, cleaner interface to the <code>opendir()</code>, <code>closedir()</code>, <code>readdir()</code>, and <code>rewinddir()</code> functions.</p>\n" }, { "answer_id": 42334054, "author": "Luke Fowler", "author_id": 2419597, "author_profile": "https://Stackoverflow.com/users/2419597", "pm_score": 0, "selected": false, "text": "<p>from: <a href=\"http://perlmeme.org/faqs/file_io/directory_listing.html\" rel=\"nofollow noreferrer\">http://perlmeme.org/faqs/file_io/directory_listing.html</a></p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy $directory = '/tmp';\n\nopendir (DIR, $directory) or die $!;\n\nwhile (my $file = readdir(DIR)) {\n next if ($file =~ m/^\\./);\n print \"$file\\n\";\n}\n</code></pre>\n\n<p>The following example (based on a code sample from perldoc -f readdir) gets all the files (not directories) beginning with a period from the open directory. The filenames are found in the array @dots.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $dir = '/tmp';\n\nopendir(DIR, $dir) or die $!;\n\nmy @dots \n = grep { \n /^\\./ # Begins with a period\n &amp;&amp; -f \"$dir/$_\" # and is a file\n} readdir(DIR);\n\n# Loop through the array printing out the filenames\nforeach my $file (@dots) {\n print \"$file\\n\";\n}\n\nclosedir(DIR);\nexit 0;\n\n\nclosedir(DIR);\nexit 0;\n</code></pre>\n" }, { "answer_id": 67091406, "author": "Shawn", "author_id": 9952196, "author_profile": "https://Stackoverflow.com/users/9952196", "pm_score": 1, "selected": false, "text": "<p>You can also use the <code>children</code> method from the popular <a href=\"https://metacpan.org/pod/Path::Tiny\" rel=\"nofollow noreferrer\"><code>Path::Tiny</code></a> module:</p>\n<pre><code>use Path::Tiny;\nmy @files = path(&quot;/path/to/dir&quot;)-&gt;children;\n</code></pre>\n<p>This creates an array of <code>Path::Tiny</code> objects, which are often more useful than just filenames if you want to do things to the files, but if you want just the names:</p>\n<pre><code>my @files = map { $_-&gt;stringify } path(&quot;/path/to/dir&quot;)-&gt;children;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
How do I get Perl to read the contents of a given directory into an array? [Backticks](https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming) can do it, but is there some method using 'scandir' or a similar term?
``` opendir(D, "/path/to/directory") || die "Can't open directory: $!\n"; while (my $f = readdir(D)) { print "\$f = $f\n"; } closedir(D); ``` EDIT: Oh, sorry, missed the "into an array" part: ``` my $d = shift; opendir(D, "$d") || die "Can't open directory $d: $!\n"; my @list = readdir(D); closedir(D); foreach my $f (@list) { print "\$f = $f\n"; } ``` EDIT2: Most of the other answers are valid, but I wanted to comment on [this answer](https://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl#24436) specifically, in which this solution is offered: ``` opendir(DIR, $somedir) || die "Can't open directory $somedir: $!"; @dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR); closedir DIR; ``` First, to document what it's doing since the poster didn't: it's passing the returned list from [readdir()](http://perldoc.perl.org/functions/readdir.html) through a [grep()](http://perldoc.perl.org/functions/grep.html) that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name `@dots` misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in [Perl](http://en.wikipedia.org/wiki/Perl), and I thought it would be valuable to document. Another example seen a lot is: ``` @list = grep !/^\.\.?$/, readdir(D); ``` This snippet reads all contents from the directory handle D **except** '.' and '..', since those are very rarely desired to be used in the listing.
22,570
<p>Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index.</p> <p>In this case, merging the function code back into the query seems impractical.</p> <p>I think I am missing something simple here.</p> <p>Here's the function for reference.</p> <pre><code>if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go </code></pre> <p>To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row:</p> <pre><code>where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight </code></pre> <p>[Edit]</p> <p>I'm incorporating @Todd's suggestion:</p> <pre><code>where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 </code></pre> <p>My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort.</p> <p>But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.</p>
[ { "answer_id": 22579, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 3, "selected": false, "text": "<pre><code>where\nyear(date1) = year(date2)\nand month(date1) = month(date2)\nand day(date1) = day(date2)\n</code></pre>\n" }, { "answer_id": 22592, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>This is much more concise:</p>\n\n<pre><code>where \n datediff(day, date1, date2) = 0\n</code></pre>\n" }, { "answer_id": 22600, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "<p>this will remove time component from a date for you: </p>\n\n<pre><code>select dateadd(d, datediff(d, 0, current_timestamp), 0)\n</code></pre>\n" }, { "answer_id": 22640, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": false, "text": "<p>You pretty much have to keep the left side of your where clause clean. So, normally, you'd do something like:</p>\n\n<pre><code>WHERE MyDateTime &gt;= @activityDateMidnight \n AND MyDateTime &lt; (@activityDateMidnight + 1)\n</code></pre>\n\n<p>(Some folks prefer DATEADD(d, 1, @activityDateMidnight) instead - but it's the same thing).</p>\n\n<p>The TimeZone table complicates matter a bit though. It's a little unclear from your snippet, but it looks like t.TheDateInTable is in GMT with a Time Zone identifier, and that you're then adding the offset to compare against @activityDateMidnight - which is in local time. I'm not sure what ds.LocalTimeZone is, though.</p>\n\n<p>If that's the case, then you need to get @activityDateMidnight into GMT instead.</p>\n" }, { "answer_id": 22655, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<p>Make sure to read <a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr\" rel=\"nofollow noreferrer\">Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code</a> so that you are sure that the optimizer can utilize the index effectively when messing with dates</p>\n" }, { "answer_id": 22656, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 1, "selected": false, "text": "<p>You're spoilt for choice in terms of options here. If you are using Sybase or SQL Server 2008 you can create variables of type date and assign them your datetime values. The database engine gets rid of the time for you. Here's a quick and dirty test to illustrate (Code is in Sybase dialect):</p>\n\n<pre><code>declare @date1 date\ndeclare @date2 date\nset @date1='2008-1-1 10:00'\nset @date2='2008-1-1 22:00'\nif @date1=@date2\n print 'Equal'\nelse\n print 'Not equal'\n</code></pre>\n\n<p>For SQL 2005 and earlier what you can do is convert the date to a varchar in a format that does not have the time component. For instance the following returns 2008.08.22</p>\n\n<pre><code>select convert(varchar,'2008-08-22 18:11:14.133',102)\n</code></pre>\n\n<p>The 102 part specifies the formatting (Books online can list for you all the available formats)</p>\n\n<p>So, what you can do is write a function that takes a datetime and extracts the date element and discards the time. Like so:</p>\n\n<pre><code>create function MakeDate (@InputDate datetime) returns datetime as\nbegin\n return cast(convert(varchar,@InputDate,102) as datetime);\nend\n</code></pre>\n\n<p>You can then use the function for companions</p>\n\n<pre><code>Select * from Orders where dbo.MakeDate(OrderDate) = dbo.MakeDate(DeliveryDate)\n</code></pre>\n" }, { "answer_id": 22662, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 0, "selected": false, "text": "<p>I would use the dayofyear function of datepart:</p>\n\n<pre><code>\nSelect *\nfrom mytable\nwhere datepart(dy,date1) = datepart(dy,date2)\nand\nyear(date1) = year(date2) --assuming you want the same year too\n</code></pre>\n\n<p>See the datepart reference <a href=\"http://www.tizag.com/sqlTutorial/sqldatepart.php\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 22670, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 0, "selected": false, "text": "<p>Regarding timezones, yet one more reason to store all dates in a single timezone (preferably UTC). Anyway, I think the answers using datediff, datepart and the different built-in date functions are your best bet.</p>\n" }, { "answer_id": 22802, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>Eric Z Beard:</p>\n\n<blockquote>\n <p>I do store all dates in GMT. Here's the use case: something happened at 11:00 PM EST on the 1st, which is the 2nd GMT. I want to see activity for the 1st, and I am in EST so I will want to see the 11PM activity. If I just compared raw GMT datetimes, I would miss things. Each row in the report can represent an activity from a different time zone.</p>\n</blockquote>\n\n<p>Right, but when you say you're interested in activity for Jan 1st 2008 EST:</p>\n\n<pre><code>SELECT @activityDateMidnight = '1/1/2008', @activityDateTZ = 'EST'\n</code></pre>\n\n<p>you just need to convert <em>that</em> to GMT (I'm ignoring the complication of querying for the day before EST goes to EDT, or vice versa):</p>\n\n<pre><code>Table: TimeZone\nFields: TimeZone, Offset\nValues: EST, -4\n\n--Multiply by -1, since we're converting EST to GMT.\n--Offsets are to go from GMT to EST.\nSELECT @activityGmtBegin = DATEADD(hh, Offset * -1, @activityDateMidnight)\nFROM TimeZone\nWHERE TimeZone = @activityDateTZ\n</code></pre>\n\n<p>which should give you '1/1/2008 4:00 AM'. Then, you can just search in GMT:</p>\n\n<pre><code>SELECT * FROM EventTable\nWHERE \n EventTime &gt;= @activityGmtBegin --1/1/2008 4:00 AM\n AND EventTime &lt; (@activityGmtBegin + 1) --1/2/2008 4:00 AM\n</code></pre>\n\n<p>The event in question is stored with a GMT EventTime of 1/2/2008 3:00 AM. You don't even need the TimeZone in the EventTable (for this purpose, at least). </p>\n\n<p>Since EventTime is not in a function, this is a straight index scan - which should be pretty efficient. Make EventTime your clustered index, and it'll fly. ;)</p>\n\n<p>Personally, I'd have the app convert the search time into GMT before running the query.</p>\n" }, { "answer_id": 23856, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Eric Z Beard:</p>\n\n<blockquote>\n <p>the activity date is meant to indicate the local time zone, but not a specific one</p>\n</blockquote>\n\n<p>Okay - back to the drawing board. Try this:</p>\n\n<pre><code>where t.TheDateINeedToCheck BETWEEN (\n dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, @ActivityDate)\n AND\n dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, (@ActivityDate + 1))\n)\n</code></pre>\n\n<p>which will translate the @ActivityDate to local time, and compare against that. That's your best chance for using an index, though I'm not sure it'll work - you should try it and check the query plan.</p>\n\n<p>The next option would be an indexed view, with an indexed, computed TimeINeedToCheck <em>in local time</em>. Then you just go back to:</p>\n\n<pre><code>where v.TheLocalDateINeedToCheck BETWEEN @ActivityDate AND (@ActivityDate + 1)\n</code></pre>\n\n<p>which would definitely use the index - though you have a slight overhead on INSERT and UPDATE then.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index. In this case, merging the function code back into the query seems impractical. I think I am missing something simple here. Here's the function for reference. ``` if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end') go alter function dbo.f_MakeDate ( @Day datetime, @Hour int, @Minute int ) returns datetime as /* Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided */ begin declare @retval datetime set @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime) return @retval end go ``` To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row: ``` where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight ``` [Edit] I'm incorporating @Todd's suggestion: ``` where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 ``` My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort. But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.
This is much more concise: ``` where datediff(day, date1, date2) = 0 ```
22,617
<p>I need to find out how to format numbers as strings. My code is here:</p> <pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm </code></pre> <p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p> <p>Bottom line, what library / function do I need to do this for me?</p>
[ { "answer_id": 22624, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "<p>Starting with Python 3.6, formatting in Python can be done using <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"noreferrer\">formatted string literals</a> or <em>f-strings</em>:</p>\n\n<pre><code>hours, minutes, seconds = 6, 56, 33\nf'{hours:02}:{minutes:02}:{seconds:02} {\"pm\" if hours &gt; 12 else \"am\"}'\n</code></pre>\n\n<p>or the <a href=\"https://docs.python.org/library/stdtypes.html#str.format\" rel=\"noreferrer\"><code>str.format</code></a> function starting with 2.7:</p>\n\n<pre><code>\"{:02}:{:02}:{:02} {}\".format(hours, minutes, seconds, \"pm\" if hours &gt; 12 else \"am\")\n</code></pre>\n\n<p>or the <a href=\"https://docs.python.org/library/stdtypes.html#printf-style-string-formatting\" rel=\"noreferrer\">string formatting <code>%</code> operator</a> for even older versions of Python, but see the note in the docs:</p>\n\n<pre><code>\"%02d:%02d:%02d\" % (hours, minutes, seconds)\n</code></pre>\n\n<p>And for your specific case of formatting time, there’s <a href=\"https://docs.python.org/library/time.html#time.strftime\" rel=\"noreferrer\"><code>time.strftime</code></a>:</p>\n\n<pre><code>import time\n\nt = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)\ntime.strftime('%I:%M:%S %p', t)\n</code></pre>\n" }, { "answer_id": 22630, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You can use C style string formatting:</p>\n\n<pre><code>\"%d:%d:d\" % (hours, minutes, seconds)\n</code></pre>\n\n<p>See here, especially: <a href=\"https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html</a></p>\n" }, { "answer_id": 24962, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p><em>str()</em> in python on an integer will <strong>not</strong> print any decimal places.</p>\n\n<p>If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).</p>\n\n<p>Perhaps the following code will demonstrate:</p>\n\n<pre><code>&gt;&gt;&gt; str(5)\n'5'\n&gt;&gt;&gt; int(8.7)\n8\n</code></pre>\n" }, { "answer_id": 2550630, "author": "wescpy", "author_id": 305689, "author_profile": "https://Stackoverflow.com/users/305689", "pm_score": 7, "selected": false, "text": "<p>Here are some examples using the existing string format operator (<code>%</code>) which has been around for as long as Python has been around:</p>\n<pre><code>&gt;&gt;&gt; &quot;Name: %s, age: %d&quot; % ('John', 35) \n'Name: John, age: 35' \n&gt;&gt;&gt; i = 45 \n&gt;&gt;&gt; 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) \n'dec: 45/oct: 055/hex: 0X2D' \n&gt;&gt;&gt; &quot;MM/DD/YY = %02d/%02d/%02d&quot; % (12, 7, 41) \n'MM/DD/YY = 12/07/41' \n&gt;&gt;&gt; 'Total with tax: $%.2f' % (13.00 * 1.0825) \n'Total with tax: $14.07' \n&gt;&gt;&gt; d = {'web': 'user', 'page': 42} \n&gt;&gt;&gt; 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d \n'http://xxx.yyy.zzz/user/42.html' \n</code></pre>\n<p>Starting in Python 2.6, there is an alternative: the <code>str.format()</code> method. Here are the equivalent snippets to the above but using <code>str.format()</code>:</p>\n<pre><code>&gt;&gt;&gt; &quot;Name: {0}, age: {1}&quot;.format('John', 35) \n'Name: John, age: 35' \n&gt;&gt;&gt; i = 45 \n&gt;&gt;&gt; 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) \n'dec: 45/oct: 0o55/hex: 0X2D' \n&gt;&gt;&gt; &quot;MM/DD/YY = {0:02d}/{1:02d}/{2:02d}&quot;.format(12, 7, 41) \n'MM/DD/YY = 12/07/41' \n&gt;&gt;&gt; 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) \n'Total with tax: $14.07' \n&gt;&gt;&gt; d = {'web': 'user', 'page': 42} \n&gt;&gt;&gt; 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) \n'http://xxx.yyy.zzz/user/42.html'\n</code></pre>\n<p>Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132269937\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">my hardcore Python intro book</a> and the slides for the Intro+Intermediate <a href=\"http://cyberwebconsulting.com\" rel=\"nofollow noreferrer\">Python courses I offer</a> from time-to-time. <code>:-)</code></p>\n<p><strong>Aug 2018 UPDATE</strong>: Of course, now that we have <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">the f-string feature introduced in 3.6</a>, we need the equivalent examples of <em>that</em>; yes, another alternative:</p>\n<pre><code>&gt;&gt;&gt; name, age = 'John', 35\n&gt;&gt;&gt; f'Name: {name}, age: {age}'\n'Name: John, age: 35'\n\n&gt;&gt;&gt; i = 45\n&gt;&gt;&gt; f'dec: {i}/oct: {i:#o}/hex: {i:#X}'\n'dec: 45/oct: 0o55/hex: 0X2D'\n\n&gt;&gt;&gt; m, d, y = 12, 7, 41\n&gt;&gt;&gt; f&quot;MM/DD/YY = {m:02d}/{d:02d}/{y:02d}&quot;\n'MM/DD/YY = 12/07/41'\n\n&gt;&gt;&gt; f'Total with tax: ${13.00 * 1.0825:.2f}'\n'Total with tax: $14.07'\n\n&gt;&gt;&gt; d = {'web': 'user', 'page': 42}\n&gt;&gt;&gt; f&quot;http://xxx.yyy.zzz/{d['web']}/{d['page']}.html&quot;\n'http://xxx.yyy.zzz/user/42.html'\n</code></pre>\n" }, { "answer_id": 3336493, "author": "Ruz", "author_id": 231395, "author_profile": "https://Stackoverflow.com/users/231395", "pm_score": 0, "selected": false, "text": "<p>If you have a value that includes a decimal, but the decimal value is negligible (ie: 100.0) and try to int that, you will get an error. It seems silly, but calling float first fixes this.</p>\n\n<p>str(int(float([variable])))</p>\n" }, { "answer_id": 26250207, "author": "Varun Chadha", "author_id": 3408904, "author_profile": "https://Stackoverflow.com/users/3408904", "pm_score": 1, "selected": false, "text": "<p>You can use following to achieve desired functionality</p>\n\n<pre><code>\"%d:%d:d\" % (hours, minutes, seconds)\n</code></pre>\n" }, { "answer_id": 41352627, "author": "lmiguelvargasf", "author_id": 3705840, "author_profile": "https://Stackoverflow.com/users/3705840", "pm_score": 3, "selected": false, "text": "<h2>Python 2.6+</h2>\n\n<p>It is possible to use the <code>format()</code> function, so in your case you can use:</p>\n\n<pre><code>return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)\n</code></pre>\n\n<p>There are multiple ways of using this function, so for further information you can check the <a href=\"https://docs.python.org/2/library/string.html\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n\n<h2>Python 3.6+</h2>\n\n<p>f-strings is a new feature that has been added to the language in Python 3.6. This facilitates formatting strings notoriously:</p>\n\n<pre><code>return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'\n</code></pre>\n" }, { "answer_id": 57165617, "author": "HamTheBurger", "author_id": 11771597, "author_profile": "https://Stackoverflow.com/users/11771597", "pm_score": 1, "selected": false, "text": "<p>You can use the str.format() to make Python recognize any objects to strings.</p>\n" }, { "answer_id": 65057124, "author": "Ranjeet R Patil", "author_id": 12415637, "author_profile": "https://Stackoverflow.com/users/12415637", "pm_score": 1, "selected": false, "text": "<p><strong><strong>I've tried this in Python 3.6.9</strong></strong></p>\n<pre><code>&gt;&gt;&gt; hours, minutes, seconds = 9, 33, 35\n&gt;&gt;&gt; time = f'{hours:02}:{minutes:02}:{seconds:02} {&quot;pm&quot; if hours &gt; 12 else &quot;am&quot;}'\n&gt;&gt;&gt; print (time)\n09:33:35 am\n&gt;&gt;&gt; type(time)\n\n&lt;class 'str'&gt;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504/" ]
I need to find out how to format numbers as strings. My code is here: ``` return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ``` Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
Starting with Python 3.6, formatting in Python can be done using [formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) or *f-strings*: ``` hours, minutes, seconds = 6, 56, 33 f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}' ``` or the [`str.format`](https://docs.python.org/library/stdtypes.html#str.format) function starting with 2.7: ``` "{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am") ``` or the [string formatting `%` operator](https://docs.python.org/library/stdtypes.html#printf-style-string-formatting) for even older versions of Python, but see the note in the docs: ``` "%02d:%02d:%02d" % (hours, minutes, seconds) ``` And for your specific case of formatting time, there’s [`time.strftime`](https://docs.python.org/library/time.html#time.strftime): ``` import time t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0) time.strftime('%I:%M:%S %p', t) ```
22,623
<p>What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the <code>Exception</code> object's <code>InnerException</code> and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?</p> <pre><code>try { //some code } catch (Exception ex) { throw ex; } </code></pre> <p>Vs:</p> <pre><code>try { //some code } catch { throw; } </code></pre>
[ { "answer_id": 22628, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 9, "selected": true, "text": "<p>The way to preserve the stack trace is through the use of the <code>throw;</code> This is valid as well</p>\n\n<pre><code>try {\n // something that bombs here\n} catch (Exception ex)\n{\n throw;\n}\n</code></pre>\n\n<p><code>throw ex;</code> is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the <code>throw ex;</code> statement.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649\">Mike</a> is also correct, assuming the exception allows you to pass an exception (which is recommended).</p>\n\n<p><a href=\"http://openmymind.net\" rel=\"noreferrer\">Karl Seguin</a> has a <a href=\"http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx\" rel=\"noreferrer\">great write up on exception handling</a> in his <a href=\"http://openmymind.net/FoundationsOfProgramming.pdf\" rel=\"noreferrer\">foundations of programming e-book</a> as well, which is a great read.</p>\n\n<p>Edit: Working link to <a href=\"http://openmymind.net/FoundationsOfProgramming.pdf\" rel=\"noreferrer\">Foundations of Programming</a> pdf. Just search the text for \"exception\".</p>\n" }, { "answer_id": 22639, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 5, "selected": false, "text": "<p>When you <code>throw ex</code>, you're essentially throwing a new exception, and will miss out on the original stack trace information. <code>throw</code> is the preferred method.</p>\n" }, { "answer_id": 22648, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "<p>The rule of thumb is to avoid Catching and Throwing the basic <code>Exception</code> object. This forces you to be a little smarter about exceptions; in other words you should have an explicit catch for a <code>SqlException</code> so that your handling code doesn't do something wrong with a <code>NullReferenceException</code>.</p>\n\n<p>In the real world though, catching <em>and logging</em> the base exception is also a good practice, but don't forget to walk the whole thing to get any <code>InnerExceptions</code> it might have.</p>\n" }, { "answer_id": 22649, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 7, "selected": false, "text": "<p>If you throw a new exception with the initial exception you will preserve the initial stack trace too..</p>\n\n<pre><code>try{\n} \ncatch(Exception ex){\n throw new MoreDescriptiveException(\"here is what was happening\", ex);\n}\n</code></pre>\n" }, { "answer_id": 22650, "author": "Kevin Griffin", "author_id": 1226, "author_profile": "https://Stackoverflow.com/users/1226", "pm_score": 2, "selected": false, "text": "<p>I would definitely use:</p>\n\n<pre><code>try\n{\n //some code\n}\ncatch\n{\n //you should totally do something here, but feel free to rethrow\n //if you need to send the exception up the stack.\n throw;\n}\n</code></pre>\n\n<p>That will preserve your stack.</p>\n" }, { "answer_id": 22673, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 2, "selected": false, "text": "<p>You may also use:</p>\n\n<pre><code>try\n{\n// Dangerous code\n}\nfinally\n{\n// clean up, or do nothing\n}\n</code></pre>\n\n<p>And any exceptions thrown will bubble up to the next level that handles them.</p>\n" }, { "answer_id": 3179808, "author": "Vinod T. Patil", "author_id": 200752, "author_profile": "https://Stackoverflow.com/users/200752", "pm_score": 3, "selected": false, "text": "<p>You should always use \"throw;\" to rethrow the exceptions in .NET,</p>\n\n<p>Refer this,\n<a href=\"http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx</a></p>\n\n<p>Basically MSIL (CIL) has two instructions - \"throw\" and \"rethrow\":</p>\n\n<ul>\n<li>C#'s \"throw ex;\" gets compiled into MSIL's \"throw\" </li>\n<li>C#'s \"throw;\" - into MSIL \"rethrow\"!</li>\n</ul>\n\n<p>Basically I can see the reason why \"throw ex\" overrides the stack trace.</p>\n" }, { "answer_id": 5653239, "author": "redcalx", "author_id": 15703, "author_profile": "https://Stackoverflow.com/users/15703", "pm_score": 0, "selected": false, "text": "<p>FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:</p>\n\n<pre><code> private void foo()\n {\n try\n {\n bar(3);\n bar(2);\n bar(1);\n bar(0);\n }\n catch(DivideByZeroException)\n {\n //log message and rethrow...\n throw;\n }\n }\n\n private void bar(int b)\n {\n int a = 1;\n int c = a/b; // Generate divide by zero exception.\n }\n</code></pre>\n\n<p>The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.</p>\n" }, { "answer_id": 9186501, "author": "notlkk", "author_id": 576300, "author_profile": "https://Stackoverflow.com/users/576300", "pm_score": 3, "selected": false, "text": "<p>A few people actually missed a very important point - 'throw' and 'throw ex' may do the same thing but they don't give you a crucial piece of imformation which is the line where the exception happened.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n try\n {\n TestMe();\n }\n catch (Exception ex)\n {\n string ss = ex.ToString();\n }\n}\n\nstatic void TestMe()\n{\n try\n {\n //here's some code that will generate an exception - line #17\n }\n catch (Exception ex)\n {\n //throw new ApplicationException(ex.ToString());\n throw ex; // line# 22\n }\n}\n</code></pre>\n\n<p>When you do either a 'throw' or 'throw ex' you get the stack trace but the line# is going to be #22 so you can't figure out which line exactly was throwing the exception (unless you have only 1 or few lines of code in the try block). To get the expected line #17 in your exception you'll have to throw a new exception with the original exception stack trace.</p>\n" }, { "answer_id": 11284872, "author": "CARLOS LOTH", "author_id": 139042, "author_profile": "https://Stackoverflow.com/users/139042", "pm_score": 5, "selected": false, "text": "<p>Actually, there are some situations which the <code>throw</code> statment will not preserve the StackTrace information. For example, in the code below:</p>\n\n<pre><code>try\n{\n int i = 0;\n int j = 12 / i; // Line 47\n int k = j + 1;\n}\ncatch\n{\n // do something\n // ...\n throw; // Line 54\n}\n</code></pre>\n\n<p>The StackTrace will indicate that line 54 raised the exception, although it was raised at line 47.</p>\n\n<pre><code>Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.\n at Program.WithThrowIncomplete() in Program.cs:line 54\n at Program.Main(String[] args) in Program.cs:line 106\n</code></pre>\n\n<p>In situations like the one described above, there are two options to preseve the original StackTrace:</p>\n\n<p><strong>Calling the Exception.InternalPreserveStackTrace</strong></p>\n\n<p>As it is a private method, it has to be invoked by using reflection: </p>\n\n<pre><code>private static void PreserveStackTrace(Exception exception)\n{\n MethodInfo preserveStackTrace = typeof(Exception).GetMethod(\"InternalPreserveStackTrace\",\n BindingFlags.Instance | BindingFlags.NonPublic);\n preserveStackTrace.Invoke(exception, null);\n}\n</code></pre>\n\n<p>I has a disadvantage of relying on a private method to preserve the StackTrace information. It can be changed in future versions of .NET Framework. The code example above and proposed solution below was extracted from <a href=\"http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx\" rel=\"noreferrer\">Fabrice MARGUERIE weblog</a>.</p>\n\n<p><strong>Calling Exception.SetObjectData</strong></p>\n\n<p>The technique below was suggested by <a href=\"https://stackoverflow.com/users/77724/anton-tykhyy\">Anton Tykhyy</a> as answer to <a href=\"https://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace\">In C#, how can I rethrow InnerException without losing stack trace</a> question.</p>\n\n<pre><code>static void PreserveStackTrace (Exception e) \n{ \n var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; \n var mgr = new ObjectManager (null, ctx) ; \n var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; \n\n e.GetObjectData (si, ctx) ; \n mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData \n mgr.DoFixups () ; // ObjectManager calls SetObjectData \n\n // voila, e is unmodified save for _remoteStackTraceString \n} \n</code></pre>\n\n<p>Although, it has the advantage of relying in public methods only it also depends on the following exception constructor (which some exceptions developed by 3rd parties do not implement):</p>\n\n<pre><code>protected Exception(\n SerializationInfo info,\n StreamingContext context\n)\n</code></pre>\n\n<p>In my situation, I had to choose the first approach, because the exceptions raised by a 3rd-party library I was using didn't implement this constructor.</p>\n" }, { "answer_id": 40586475, "author": "Mark", "author_id": 6192931, "author_profile": "https://Stackoverflow.com/users/6192931", "pm_score": 4, "selected": false, "text": "<p>Nobody has explained the difference between <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> and a plain <code>throw</code>, so here it is. However, some people have noticed the problem with <code>throw</code>.</p>\n\n<p>The complete way to rethrow a caught exception is to use <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> (only available from .Net 4.5).</p>\n\n<p>Below there are the cases necessary to test this:</p>\n\n<p>1.</p>\n\n<pre><code>void CallingMethod()\n{\n //try\n {\n throw new Exception( \"TEST\" );\n }\n //catch\n {\n // throw;\n }\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n ExceptionDispatchInfo.Capture( ex ).Throw();\n throw; // So the compiler doesn't complain about methods which don't either return or throw.\n }\n}\n</code></pre>\n\n<p>3.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch\n {\n throw;\n }\n}\n</code></pre>\n\n<p>4.</p>\n\n<pre><code>void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n throw new Exception( \"RETHROW\", ex );\n }\n}\n</code></pre>\n\n<p>Case 1 and case 2 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw new Exception( \"TEST\" )</code> line.</p>\n\n<p>However, case 3 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw</code> call. This means that if the <code>throw new Exception( \"TEST\" )</code> line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.</p>\n\n<p>Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the `Exception` object's `InnerException` and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? ``` try { //some code } catch (Exception ex) { throw ex; } ``` Vs: ``` try { //some code } catch { throw; } ```
The way to preserve the stack trace is through the use of the `throw;` This is valid as well ``` try { // something that bombs here } catch (Exception ex) { throw; } ``` `throw ex;` is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the `throw ex;` statement. [Mike](https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649) is also correct, assuming the exception allows you to pass an exception (which is recommended). [Karl Seguin](http://openmymind.net) has a [great write up on exception handling](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) in his [foundations of programming e-book](http://openmymind.net/FoundationsOfProgramming.pdf) as well, which is a great read. Edit: Working link to [Foundations of Programming](http://openmymind.net/FoundationsOfProgramming.pdf) pdf. Just search the text for "exception".
22,676
<p>I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.</p> <p>The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows <code>.bat</code> file to download the actual MP3 file. I would prefer to have the entire utility written in Python.</p> <p>I struggled to find a way to actually download the file in Python, thus why I resorted to using <code>wget</code>.</p> <p>So, how do I download the file using Python?</p>
[ { "answer_id": 22682, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 10, "selected": true, "text": "<p>Use <a href=\"https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen\" rel=\"noreferrer\"><code>urllib.request.urlopen()</code></a>:</p>\n<pre><code>import urllib.request\nwith urllib.request.urlopen('http://www.example.com/') as f:\n html = f.read().decode('utf-8')\n</code></pre>\n<p>This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers.</p>\n<p>On Python 2, the method is in <a href=\"http://docs.python.org/2/library/urllib2.html\" rel=\"noreferrer\"><code>urllib2</code></a>:</p>\n<pre><code>import urllib2\nresponse = urllib2.urlopen('http://www.example.com/')\nhtml = response.read()\n</code></pre>\n" }, { "answer_id": 22721, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 7, "selected": false, "text": "<pre class=\"lang-py prettyprint-override\"><code>import urllib2\nmp3file = urllib2.urlopen(\"http://www.example.com/songs/mp3.mp3\")\nwith open('test.mp3','wb') as output:\n output.write(mp3file.read())\n</code></pre>\n\n<p>The <code>wb</code> in <code>open('test.mp3','wb')</code> opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text.</p>\n" }, { "answer_id": 22723, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 4, "selected": false, "text": "<p>I agree with Corey, urllib2 is more complete than <a href=\"http://docs.python.org/lib/module-urllib.html\" rel=\"noreferrer\">urllib</a> and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:</p>\n\n<pre><code>import urllib\nresponse = urllib.urlopen('http://www.example.com/sound.mp3')\nmp3 = response.read()\n</code></pre>\n\n<p>Will work fine. Or, if you don't want to deal with the \"response\" object you can call <strong>read()</strong> directly:</p>\n\n<pre><code>import urllib\nmp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()\n</code></pre>\n" }, { "answer_id": 22776, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 10, "selected": false, "text": "<p>One more, using <a href=\"http://docs.python.org/2/library/urllib.html#urllib.urlretrieve\" rel=\"noreferrer\"><code>urlretrieve</code></a>:</p>\n<pre><code>import urllib.request\nurllib.request.urlretrieve(&quot;http://www.example.com/songs/mp3.mp3&quot;, &quot;mp3.mp3&quot;)\n</code></pre>\n<p>(for Python 2 use <code>import urllib</code> and <code>urllib.urlretrieve</code>)</p>\n" }, { "answer_id": 10744565, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 9, "selected": false, "text": "<p>In 2012, use the <a href=\"https://requests.readthedocs.io/\" rel=\"noreferrer\">python requests library</a></p>\n\n<pre><code>&gt;&gt;&gt; import requests\n&gt;&gt;&gt; \n&gt;&gt;&gt; url = \"http://download.thinkbroadband.com/10MB.zip\"\n&gt;&gt;&gt; r = requests.get(url)\n&gt;&gt;&gt; print len(r.content)\n10485760\n</code></pre>\n\n<p>You can run <code>pip install requests</code> to get it.</p>\n\n<p>Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.</p>\n\n<hr>\n\n<p>2015-12-30</p>\n\n<p>People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including <code>tqdm</code>:</p>\n\n<pre><code>from tqdm import tqdm\nimport requests\n\nurl = \"http://download.thinkbroadband.com/10MB.zip\"\nresponse = requests.get(url, stream=True)\n\nwith open(\"10MB\", \"wb\") as handle:\n for data in tqdm(response.iter_content()):\n handle.write(data)\n</code></pre>\n\n<p>This is essentially the implementation @kvance described 30 months ago.</p>\n" }, { "answer_id": 16518224, "author": "Stan", "author_id": 2357007, "author_profile": "https://Stackoverflow.com/users/2357007", "pm_score": 5, "selected": false, "text": "<p>An improved version of the PabloG code for Python 2/3:</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import ( division, absolute_import, print_function, unicode_literals )\n\nimport sys, os, tempfile, logging\n\nif sys.version_info &gt;= (3,):\n import urllib.request as urllib2\n import urllib.parse as urlparse\nelse:\n import urllib2\n import urlparse\n\ndef download_file(url, dest=None):\n \"\"\" \n Download and save a file specified by url to dest directory,\n \"\"\"\n u = urllib2.urlopen(url)\n\n scheme, netloc, path, query, fragment = urlparse.urlsplit(url)\n filename = os.path.basename(path)\n if not filename:\n filename = 'downloaded.file'\n if dest:\n filename = os.path.join(dest, filename)\n\n with open(filename, 'wb') as f:\n meta = u.info()\n meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all\n meta_length = meta_func(\"Content-Length\")\n file_size = None\n if meta_length:\n file_size = int(meta_length[0])\n print(\"Downloading: {0} Bytes: {1}\".format(url, file_size))\n\n file_size_dl = 0\n block_sz = 8192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n f.write(buffer)\n\n status = \"{0:16}\".format(file_size_dl)\n if file_size:\n status += \" [{0:6.2f}%]\".format(file_size_dl * 100 / file_size)\n status += chr(13)\n print(status, end=\"\")\n print()\n\n return filename\n\nif __name__ == \"__main__\": # Only run if this file is called directly\n print(\"Testing with 10MB download\")\n url = \"http://download.thinkbroadband.com/10MB.zip\"\n filename = download_file(url)\n print(filename)\n</code></pre>\n" }, { "answer_id": 19011916, "author": "anatoly techtonik", "author_id": 239247, "author_profile": "https://Stackoverflow.com/users/239247", "pm_score": 4, "selected": false, "text": "<p>Wrote <a href=\"https://pypi.python.org/pypi/wget\" rel=\"noreferrer\">wget</a> library in pure Python just for this purpose. It is pumped up <code>urlretrieve</code> with <a href=\"https://bitbucket.org/techtonik/python-wget/src/6859e7b4aba37cef57616111be890fb59631bc4c/wget.py?at=default#cl-330\" rel=\"noreferrer\">these features</a> as of version 2.0.</p>\n" }, { "answer_id": 19352848, "author": "JD3", "author_id": 2019895, "author_profile": "https://Stackoverflow.com/users/2019895", "pm_score": 2, "selected": false, "text": "<p>This may be a little late, But I saw pabloG's code and couldn't help adding a os.system('cls') to make it look AWESOME! Check it out : </p>\n\n<pre><code> import urllib2,os\n\n url = \"http://download.thinkbroadband.com/10MB.zip\"\n\n file_name = url.split('/')[-1]\n u = urllib2.urlopen(url)\n f = open(file_name, 'wb')\n meta = u.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n print \"Downloading: %s Bytes: %s\" % (file_name, file_size)\n os.system('cls')\n file_size_dl = 0\n block_sz = 8192\n while True:\n buffer = u.read(block_sz)\n if not buffer:\n break\n\n file_size_dl += len(buffer)\n f.write(buffer)\n status = r\"%10d [%3.2f%%]\" % (file_size_dl, file_size_dl * 100. / file_size)\n status = status + chr(8)*(len(status)+1)\n print status,\n\n f.close()\n</code></pre>\n\n<p>If running in an environment other than Windows, you will have to use something other then 'cls'. In MAC OS X and Linux it should be 'clear'.</p>\n" }, { "answer_id": 20218209, "author": "Zuko", "author_id": 2114557, "author_profile": "https://Stackoverflow.com/users/2114557", "pm_score": 2, "selected": false, "text": "<p>Source code can be:</p>\n\n<pre><code>import urllib\nsock = urllib.urlopen(\"http://diveintopython.org/\")\nhtmlSource = sock.read() \nsock.close() \nprint htmlSource \n</code></pre>\n" }, { "answer_id": 21363808, "author": "Marcin Cuprjak", "author_id": 2454922, "author_profile": "https://Stackoverflow.com/users/2454922", "pm_score": 3, "selected": false, "text": "<p>You can get the progress feedback with urlretrieve as well:</p>\n\n<pre><code>def report(blocknr, blocksize, size):\n current = blocknr*blocksize\n sys.stdout.write(\"\\r{0:.2f}%\".format(100.0*current/size))\n\ndef downloadFile(url):\n print \"\\n\",url\n fname = url.split('/')[-1]\n print fname\n urllib.urlretrieve(url, fname, report)\n</code></pre>\n" }, { "answer_id": 29256384, "author": "Sara Santana", "author_id": 4579638, "author_profile": "https://Stackoverflow.com/users/4579638", "pm_score": 6, "selected": false, "text": "<p>use <a href=\"https://pypi.org/project/wget/\" rel=\"noreferrer\">wget module</a>:</p>\n<pre><code>import wget\nwget.download('url')\n</code></pre>\n" }, { "answer_id": 31857152, "author": "bmaupin", "author_id": 399105, "author_profile": "https://Stackoverflow.com/users/399105", "pm_score": 7, "selected": false, "text": "<h3>Python 3</h3>\n\n<ul>\n<li><p><a href=\"https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen\" rel=\"noreferrer\"><code>urllib.request.urlopen</code></a></p>\n\n<pre><code>import urllib.request\nresponse = urllib.request.urlopen('http://www.example.com/')\nhtml = response.read()\n</code></pre></li>\n<li><p><a href=\"https://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve\" rel=\"noreferrer\"><code>urllib.request.urlretrieve</code></a></p>\n\n<pre><code>import urllib.request\nurllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')\n</code></pre>\n\n<p><strong>Note:</strong> According to the documentation, <code>urllib.request.urlretrieve</code> is a \"legacy interface\" and \"might become deprecated in the future\" (thanks <a href=\"https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python/31857152?noredirect=1#comment107731047_31857152\">gerrit</a>)</p></li>\n</ul>\n\n<h3>Python 2</h3>\n\n<ul>\n<li><p><a href=\"https://docs.python.org/2/library/urllib2.html#urllib2.urlopen\" rel=\"noreferrer\"><code>urllib2.urlopen</code></a> (thanks <a href=\"https://stackoverflow.com/a/22682/399105\">Corey</a>)</p>\n\n<pre><code>import urllib2\nresponse = urllib2.urlopen('http://www.example.com/')\nhtml = response.read()\n</code></pre></li>\n<li><p><a href=\"https://docs.python.org/2/library/urllib.html#urllib.urlretrieve\" rel=\"noreferrer\"><code>urllib.urlretrieve</code></a> (thanks <a href=\"https://stackoverflow.com/a/22776/399105\">PabloG</a>)</p>\n\n<pre><code>import urllib\nurllib.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')\n</code></pre></li>\n</ul>\n" }, { "answer_id": 33816517, "author": "max", "author_id": 1896222, "author_profile": "https://Stackoverflow.com/users/1896222", "pm_score": 3, "selected": false, "text": "<p>If you have wget installed, you can use parallel_sync.</p>\n\n<p>pip install parallel_sync</p>\n\n<pre><code>from parallel_sync import wget\nurls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']\nwget.download('/tmp', urls)\n# or a single file:\nwget.download('/tmp', urls[0], filenames='x.zip', extract=True)\n</code></pre>\n\n<p>Doc:\n<a href=\"https://pythonhosted.org/parallel_sync/pages/examples.html\" rel=\"noreferrer\">https://pythonhosted.org/parallel_sync/pages/examples.html</a></p>\n\n<p>This is pretty powerful. It can download files in parallel, retry upon failure , and it can even download files on a remote machine.</p>\n" }, { "answer_id": 39573536, "author": "Jaydev", "author_id": 4269615, "author_profile": "https://Stackoverflow.com/users/4269615", "pm_score": 4, "selected": false, "text": "<p>Following are the most commonly used calls for downloading files in python:</p>\n\n<ol>\n<li><p><code>urllib.urlretrieve ('url_to_file', file_name)</code></p></li>\n<li><p><code>urllib2.urlopen('url_to_file')</code></p></li>\n<li><p><code>requests.get(url)</code></p></li>\n<li><p><code>wget.download('url', file_name)</code></p></li>\n</ol>\n\n<p>Note: <code>urlopen</code> and <code>urlretrieve</code> are found to perform relatively bad with downloading large files (size > 500 MB). <code>requests.get</code> stores the file in-memory until download is complete. </p>\n" }, { "answer_id": 42764549, "author": "Sphynx-HenryAY", "author_id": 5421147, "author_profile": "https://Stackoverflow.com/users/5421147", "pm_score": 2, "selected": false, "text": "<p>urlretrieve and requests.get are simple, however the reality not.\nI have fetched data for couple sites, including text and images, the above two probably solve most of the tasks. but for a more universal solution I suggest the use of urlopen. As it is included in Python 3 standard library, your code could run on any machine that run Python 3 without pre-installing site-package</p>\n\n<pre><code>import urllib.request\nurl_request = urllib.request.Request(url, headers=headers)\nurl_connect = urllib.request.urlopen(url_request)\n\n#remember to open file in bytes mode\nwith open(filename, 'wb') as f:\n while True:\n buffer = url_connect.read(buffer_size)\n if not buffer: break\n\n #an integer value of size of written data\n data_wrote = f.write(buffer)\n\n#you could probably use with-open-as manner\nurl_connect.close()\n</code></pre>\n\n<p>This answer provides a solution to HTTP 403 Forbidden when downloading file over http using Python. I have tried only requests and urllib modules, the other module may provide something better, but this is the one I used to solve most of the problems.</p>\n" }, { "answer_id": 43958201, "author": "imallett", "author_id": 688624, "author_profile": "https://Stackoverflow.com/users/688624", "pm_score": 2, "selected": false, "text": "<p>I wrote the following, which works in vanilla Python 2 or Python 3.</p>\n\n<hr>\n\n<pre><code>import sys\ntry:\n import urllib.request\n python3 = True\nexcept ImportError:\n import urllib2\n python3 = False\n\n\ndef progress_callback_simple(downloaded,total):\n sys.stdout.write(\n \"\\r\" +\n (len(str(total))-len(str(downloaded)))*\" \" + str(downloaded) + \"/%d\"%total +\n \" [%3.2f%%]\"%(100.0*float(downloaded)/float(total))\n )\n sys.stdout.flush()\n\ndef download(srcurl, dstfilepath, progress_callback=None, block_size=8192):\n def _download_helper(response, out_file, file_size):\n if progress_callback!=None: progress_callback(0,file_size)\n if block_size == None:\n buffer = response.read()\n out_file.write(buffer)\n\n if progress_callback!=None: progress_callback(file_size,file_size)\n else:\n file_size_dl = 0\n while True:\n buffer = response.read(block_size)\n if not buffer: break\n\n file_size_dl += len(buffer)\n out_file.write(buffer)\n\n if progress_callback!=None: progress_callback(file_size_dl,file_size)\n with open(dstfilepath,\"wb\") as out_file:\n if python3:\n with urllib.request.urlopen(srcurl) as response:\n file_size = int(response.getheader(\"Content-Length\"))\n _download_helper(response,out_file,file_size)\n else:\n response = urllib2.urlopen(srcurl)\n meta = response.info()\n file_size = int(meta.getheaders(\"Content-Length\")[0])\n _download_helper(response,out_file,file_size)\n\nimport traceback\ntry:\n download(\n \"https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip\",\n \"output.zip\",\n progress_callback_simple\n )\nexcept:\n traceback.print_exc()\n input()\n</code></pre>\n\n<hr>\n\n<p>Notes:</p>\n\n<ul>\n<li>Supports a \"progress bar\" callback.</li>\n<li>Download is a 4 MB test .zip from my website.</li>\n</ul>\n" }, { "answer_id": 44693533, "author": "Akif", "author_id": 950762, "author_profile": "https://Stackoverflow.com/users/950762", "pm_score": 5, "selected": false, "text": "<p>Simple yet <code>Python 2 &amp; Python 3</code> compatible way comes with <code>six</code> library:</p>\n\n<pre><code>from six.moves import urllib\nurllib.request.urlretrieve(\"http://www.example.com/songs/mp3.mp3\", \"mp3.mp3\")\n</code></pre>\n" }, { "answer_id": 47098069, "author": "Omer Dagan", "author_id": 1773706, "author_profile": "https://Stackoverflow.com/users/1773706", "pm_score": 3, "selected": false, "text": "<p>If speed matters to you, I made a small performance test for the modules <code>urllib</code> and <code>wget</code>, and regarding <code>wget</code> I tried once with status bar and once without. I took three different 500MB files to test with (different files- to eliminate the chance that there is some caching going on under the hood). Tested on debian machine, with python2.</p>\n\n<p>First, these are the results (they are similar in different runs):</p>\n\n<pre><code>$ python wget_test.py \nurlretrive_test : starting\nurlretrive_test : 6.56\n==============\nwget_no_bar_test : starting\nwget_no_bar_test : 7.20\n==============\nwget_with_bar_test : starting\n100% [......................................................................] 541335552 / 541335552\nwget_with_bar_test : 50.49\n==============\n</code></pre>\n\n<p>The way I performed the test is using \"profile\" decorator. This is the full code:</p>\n\n<pre><code>import wget\nimport urllib\nimport time\nfrom functools import wraps\n\ndef profile(func):\n @wraps(func)\n def inner(*args):\n print func.__name__, \": starting\"\n start = time.time()\n ret = func(*args)\n end = time.time()\n print func.__name__, \": {:.2f}\".format(end - start)\n return ret\n return inner\n\nurl1 = 'http://host.com/500a.iso'\nurl2 = 'http://host.com/500b.iso'\nurl3 = 'http://host.com/500c.iso'\n\ndef do_nothing(*args):\n pass\n\n@profile\ndef urlretrive_test(url):\n return urllib.urlretrieve(url)\n\n@profile\ndef wget_no_bar_test(url):\n return wget.download(url, out='/tmp/', bar=do_nothing)\n\n@profile\ndef wget_with_bar_test(url):\n return wget.download(url, out='/tmp/')\n\nurlretrive_test(url1)\nprint '=============='\ntime.sleep(1)\n\nwget_no_bar_test(url2)\nprint '=============='\ntime.sleep(1)\n\nwget_with_bar_test(url3)\nprint '=============='\ntime.sleep(1)\n</code></pre>\n\n<p><code>urllib</code> seems to be the fastest</p>\n" }, { "answer_id": 48691447, "author": "Apurv Agarwal", "author_id": 6712942, "author_profile": "https://Stackoverflow.com/users/6712942", "pm_score": 4, "selected": false, "text": "<p>In python3 you can use urllib3 and shutil libraires.\nDownload them by using pip or pip3 (Depending whether python3 is default or not)</p>\n\n<pre><code>pip3 install urllib3 shutil\n</code></pre>\n\n<p>Then run this code</p>\n\n<pre><code>import urllib.request\nimport shutil\n\nurl = \"http://www.somewebsite.com/something.pdf\"\noutput_file = \"save_this_name.pdf\"\nwith urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n</code></pre>\n\n<p>Note that you download <code>urllib3</code> but use <code>urllib</code> in code</p>\n" }, { "answer_id": 51738373, "author": "gzerone", "author_id": 1070813, "author_profile": "https://Stackoverflow.com/users/1070813", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"http://pycurl.io/\" rel=\"nofollow noreferrer\">PycURL</a> on Python 2 and 3.</p>\n\n<pre><code>import pycurl\n\nFILE_DEST = 'pycurl.html'\nFILE_SRC = 'http://pycurl.io/'\n\nwith open(FILE_DEST, 'wb') as f:\n c = pycurl.Curl()\n c.setopt(c.URL, FILE_SRC)\n c.setopt(c.WRITEDATA, f)\n c.perform()\n c.close()\n</code></pre>\n" }, { "answer_id": 52077420, "author": "Robin Dinse", "author_id": 5096199, "author_profile": "https://Stackoverflow.com/users/5096199", "pm_score": 3, "selected": false, "text": "<p>Just for the sake of completeness, it is also possible to call any program for retrieving files using the <code>subprocess</code> package. Programs dedicated to retrieving files are more powerful than Python functions like <code>urlretrieve</code>. For example, <a href=\"https://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\"><code>wget</code></a> can download directories recursively (<code>-R</code>), can deal with FTP, redirects, HTTP proxies, can avoid re-downloading existing files (<code>-nc</code>), and <a href=\"https://aria2.github.io/\" rel=\"nofollow noreferrer\"><code>aria2</code></a> can do multi-connection downloads which can potentially speed up your downloads.</p>\n\n<pre><code>import subprocess\nsubprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])\n</code></pre>\n\n<p>In Jupyter Notebook, one can also call programs directly with the <code>!</code> syntax:</p>\n\n<pre><code>!wget -O example_output_file.html https://example.com\n</code></pre>\n" }, { "answer_id": 53153505, "author": "H S Umer farooq", "author_id": 6454850, "author_profile": "https://Stackoverflow.com/users/6454850", "pm_score": 5, "selected": false, "text": "<pre><code>import os,requests\ndef download(url):\n get_response = requests.get(url,stream=True)\n file_name = url.split(\"/\")[-1]\n with open(file_name, 'wb') as f:\n for chunk in get_response.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n\n\ndownload(\"https://example.com/example.jpg\")\n</code></pre>\n" }, { "answer_id": 60371032, "author": "Pedro Lobito", "author_id": 797495, "author_profile": "https://Stackoverflow.com/users/797495", "pm_score": 3, "selected": false, "text": "<p>Late answer, but for <code>python&gt;=3.6</code> you can use:</p>\n\n<pre><code>import dload\ndload.save(url)\n</code></pre>\n\n<hr>\n\n<p>Install <code>dload</code> with:</p>\n\n<pre><code>pip3 install dload\n</code></pre>\n" }, { "answer_id": 60555820, "author": "gibbone", "author_id": 6332373, "author_profile": "https://Stackoverflow.com/users/6332373", "pm_score": 0, "selected": false, "text": "<p>I wanted do download all the files from a webpage. I tried <code>wget</code> but it was failing so I decided for the Python route and I found this thread. </p>\n\n<p>After reading it, I have made a little command line application, <a href=\"https://gist.github.com/gibbbone/acde8ec66ca76f59d70af6ebd8511252\" rel=\"nofollow noreferrer\"><code>soupget</code></a>, expanding on the excellent answers of <a href=\"https://stackoverflow.com/a/22776/6332373\">PabloG</a> and <a href=\"https://stackoverflow.com/a/16518224/6332373\">Stan</a> and adding some useful options. </p>\n\n<p>It uses <a href=\"https://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeatifulSoup</a> to collect all the URLs of the page and then download the ones with the desired extension(s). Finally it can download multiple files in parallel.</p>\n\n<p>Here it is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import (division, absolute_import, print_function, unicode_literals)\nimport sys, os, argparse\nfrom bs4 import BeautifulSoup\n\n# --- insert Stan's script here ---\n# if sys.version_info &gt;= (3,): \n#...\n#...\n# def download_file(url, dest=None): \n#...\n#...\n\n# --- new stuff ---\ndef collect_all_url(page_url, extensions):\n \"\"\"\n Recovers all links in page_url checking for all the desired extensions\n \"\"\"\n conn = urllib2.urlopen(page_url)\n html = conn.read()\n soup = BeautifulSoup(html, 'lxml')\n links = soup.find_all('a')\n\n results = [] \n for tag in links:\n link = tag.get('href', None)\n if link is not None: \n for e in extensions:\n if e in link:\n # Fallback for badly defined links\n # checks for missing scheme or netloc\n if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):\n results.append(link)\n else:\n new_url=urlparse.urljoin(page_url,link) \n results.append(new_url)\n return results\n\nif __name__ == \"__main__\": # Only run if this file is called directly\n # Command line arguments\n parser = argparse.ArgumentParser(\n description='Download all files from a webpage.')\n parser.add_argument(\n '-u', '--url', \n help='Page url to request')\n parser.add_argument(\n '-e', '--ext', \n nargs='+',\n help='Extension(s) to find') \n parser.add_argument(\n '-d', '--dest', \n default=None,\n help='Destination where to save the files')\n parser.add_argument(\n '-p', '--par', \n action='store_true', default=False, \n help=\"Turns on parallel download\")\n args = parser.parse_args()\n\n # Recover files to download\n all_links = collect_all_url(args.url, args.ext)\n\n # Download\n if not args.par:\n for l in all_links:\n try:\n filename = download_file(l, args.dest)\n print(l)\n except Exception as e:\n print(\"Error while downloading: {}\".format(e))\n else:\n from multiprocessing.pool import ThreadPool\n results = ThreadPool(10).imap_unordered(\n lambda x: download_file(x, args.dest), all_links)\n for p in results:\n print(p)\n</code></pre>\n\n<p>An example of its usage is:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>python3 soupget.py -p -e &lt;list of extensions&gt; -d &lt;destination_folder&gt; -u &lt;target_webpage&gt;\n</code></pre>\n\n<p>And an actual example if you want to see it in action:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics\n</code></pre>\n" }, { "answer_id": 63876738, "author": "firebfm", "author_id": 3290793, "author_profile": "https://Stackoverflow.com/users/3290793", "pm_score": -1, "selected": false, "text": "<p>Another way is to call an external process such as curl.exe. Curl by default displays a progress bar, average download speed, time left, and more all formatted neatly in a table.\nPut curl.exe in the same directory as your script</p>\n<pre><code>from subprocess import call\nurl = &quot;&quot;\ncall([&quot;curl&quot;, {url}, '--output', &quot;song.mp3&quot;])\n</code></pre>\n<p>Note: You cannot specify an output path with curl, so do an os.rename afterwards</p>\n" }, { "answer_id": 68224842, "author": "Ninja Master", "author_id": 2693349, "author_profile": "https://Stackoverflow.com/users/2693349", "pm_score": 2, "selected": false, "text": "<p>New Api urllib3 based implementation</p>\n<pre><code>&gt;&gt;&gt; import urllib3\n&gt;&gt;&gt; http = urllib3.PoolManager()\n&gt;&gt;&gt; r = http.request('GET', 'your_url_goes_here')\n&gt;&gt;&gt; r.status\n 200\n&gt;&gt;&gt; r.data\n *****Response Data****\n</code></pre>\n<p>More info: <a href=\"https://pypi.org/project/urllib3/\" rel=\"nofollow noreferrer\">https://pypi.org/project/urllib3/</a></p>\n" }, { "answer_id": 72255053, "author": "uTesla", "author_id": 13962104, "author_profile": "https://Stackoverflow.com/users/13962104", "pm_score": 2, "selected": false, "text": "<p>Use Python Requests in 5 lines</p>\n<pre><code>import requests as req\n\nremote_url = 'http://www.example.com/sound.mp3'\nlocal_file_name = 'sound.mp3'\n\ndata = req.get(remote_url)\n\n# Save file data to local copy\nwith open(local_file_name, 'wb')as file:\n file.write(data.content)\n</code></pre>\n<p>Now do something with the local copy of the remote file</p>\n" }, { "answer_id": 74097971, "author": "thebadgateway", "author_id": 14927325, "author_profile": "https://Stackoverflow.com/users/14927325", "pm_score": 0, "selected": false, "text": "<p>Another possibility is with built-in <a href=\"https://docs.python.org/3/library/http.client.html\" rel=\"nofollow noreferrer\"><code>http.client</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from http import HTTPStatus, client\nfrom shutil import copyfileobj\n\n# using https\nconnection = client.HTTPSConnection(&quot;www.example.com&quot;)\nwith connection.request(&quot;GET&quot;, &quot;/noise.mp3&quot;) as response:\n if response.status == HTTPStatus.OK:\n copyfileobj(response, open(&quot;noise.mp3&quot;)\n else:\n raise Exception(&quot;request needs work&quot;)\n</code></pre>\n<p>The <code>HTTPConnection</code> object is considered “low-level” in that it performs the desired request once and assumes the developer will subclass it or script in a way to handle the nuances of HTTP. Libraries such as <a href=\"https://requests.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">requests</a> tend to handle more special cases such as automatically following redirects and so on.</p>\n" }, { "answer_id": 74445704, "author": "Mushfirat Mohaimin", "author_id": 15760624, "author_profile": "https://Stackoverflow.com/users/15760624", "pm_score": 0, "selected": false, "text": "<p>You can use <code>keras.utils.get_file</code> to do it:</p>\n<pre><code>from tensorflow import keras\n\npath_to_downloaded_file = keras.utils.get_file(\n fname=&quot;file name&quot;,\n origin=&quot;https://www.linktofile.com/link/to/file&quot;,\n extract=True,\n archive_format=&quot;zip&quot;, # downloaded file format\n cache_dir=&quot;/&quot;, # cache and extract in current directory\n)\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109/" ]
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows `.bat` file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using `wget`. So, how do I download the file using Python?
Use [`urllib.request.urlopen()`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen): ``` import urllib.request with urllib.request.urlopen('http://www.example.com/') as f: html = f.read().decode('utf-8') ``` This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. On Python 2, the method is in [`urllib2`](http://docs.python.org/2/library/urllib2.html): ``` import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read() ```
22,697
<p>What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?</p>
[ { "answer_id": 23048, "author": "Brian Laframboise", "author_id": 1557, "author_profile": "https://Stackoverflow.com/users/1557", "pm_score": 9, "selected": true, "text": "<p>I've had good success using <a href=\"https://github.com/mockito/mockito\" rel=\"noreferrer\">Mockito</a>.</p>\n\n<p>When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).</p>\n\n<p>I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.</p>\n\n<p>Here's an (abridged) example from the Mockito homepage:</p>\n\n<pre><code>import static org.mockito.Mockito.*;\n\nList mockedList = mock(List.class);\nmockedList.clear();\nverify(mockedList).clear();\n</code></pre>\n\n<p>It doesn't get much simpler than that.</p>\n\n<p>The only major downside I can think of is that it won't mock static methods.</p>\n" }, { "answer_id": 23295, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 4, "selected": false, "text": "<p>We are heavily using <a href=\"http://easymock.org\" rel=\"noreferrer\">EasyMock</a> and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.</p>\n" }, { "answer_id": 27786, "author": "Mike Furtak", "author_id": 3005, "author_profile": "https://Stackoverflow.com/users/3005", "pm_score": 1, "selected": false, "text": "<p>I started using mocks through JMock, but eventually transitioned to use EasyMock. EasyMock was just that, --easier-- and provided a syntax that felt more natural. I haven't switched since.</p>\n" }, { "answer_id": 28015, "author": "Josh Brown", "author_id": 2030, "author_profile": "https://Stackoverflow.com/users/2030", "pm_score": 2, "selected": false, "text": "<p>Mockito also provides the option of stubbing methods, matching arguments (like anyInt() and anyString()), verifying the number of invocations (times(3), atLeastOnce(), never()), <a href=\"http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html\" rel=\"nofollow noreferrer\">and more</a>.</p>\n\n<p>I've also found that Mockito is <a href=\"https://stackoverflow.com/questions/22697/whats-the-best-mock-framework-for-java#23048\">simple and clean</a>.</p>\n\n<p>One thing I don't like about Mockito is that you <a href=\"http://code.google.com/p/mockito/wiki/FAQ\" rel=\"nofollow noreferrer\">can't stub static methods</a>.</p>\n" }, { "answer_id": 37028, "author": "Bartosz Bierkowski", "author_id": 3666, "author_profile": "https://Stackoverflow.com/users/3666", "pm_score": 3, "selected": false, "text": "<p>Yes, Mockito is a great framework. I use it together with <a href=\"http://code.google.com/p/hamcrest/\" rel=\"noreferrer\">hamcrest</a> and <a href=\"http://code.google.com/p/google-guice/\" rel=\"noreferrer\">Google guice</a> to setup my tests.</p>\n" }, { "answer_id": 92998, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 4, "selected": false, "text": "<p>You could also have a look at testing using Groovy. In Groovy you can easily mock Java interfaces using the 'as' operator:</p>\n\n<pre><code>def request = [isUserInRole: { roleName -&gt; roleName == \"testRole\"}] as HttpServletRequest \n</code></pre>\n\n<p>Apart from this basic functionality Groovy offers a lot more on the mocking front, including the powerful <code>MockFor</code> and <code>StubFor</code> classes.</p>\n\n<p><a href=\"http://docs.codehaus.org/display/GROOVY/Groovy+Mocks\" rel=\"nofollow noreferrer\">http://docs.codehaus.org/display/GROOVY/Groovy+Mocks</a></p>\n" }, { "answer_id": 93675, "author": "Kris Pruden", "author_id": 16977, "author_profile": "https://Stackoverflow.com/users/16977", "pm_score": 4, "selected": false, "text": "<p>I've been having success with <a href=\"http://jmockit.github.io/index.html\" rel=\"noreferrer\">JMockit</a>.</p>\n\n<p>It's pretty new, and so it's a bit raw and under-documented. It uses <a href=\"http://asm.objectweb.org/index.html\" rel=\"noreferrer\">ASM</a> to dynamically redefine the class bytecode, so it can mock out all methods including static, private, constructors, and static initializers. For example:</p>\n\n<pre><code>import mockit.Mockit;\n\n...\nMockit.redefineMethods(MyClassWithStaticInit.class,\n MyReplacementClass.class);\n...\nclass MyReplacementClass {\n public void $init() {...} // replace default constructor\n public static void $clinit{...} // replace static initializer\n public static void myStatic{...} // replace static method\n // etc...\n}\n</code></pre>\n\n<p>It has an Expectations interface allowing record/playback scenarios as well:</p>\n\n<pre><code>import mockit.Expectations;\nimport org.testng.annotations.Test;\n\npublic class ExpecationsTest {\n private MyClass obj;\n\n @Test\n public void testFoo() {\n new Expectations(true) {\n MyClass c;\n {\n obj = c;\n invokeReturning(c.getFoo(\"foo\", false), \"bas\");\n }\n };\n\n assert \"bas\".equals(obj.getFoo(\"foo\", false));\n\n Expectations.assertSatisfied();\n }\n\n public static class MyClass {\n public String getFoo(String str, boolean bool) {\n if (bool) {\n return \"foo\";\n } else {\n return \"bar\";\n }\n }\n }\n}\n</code></pre>\n\n<p>The downside is that it requires Java 5/6.</p>\n" }, { "answer_id": 382692, "author": "Andrea Francia", "author_id": 36131, "author_profile": "https://Stackoverflow.com/users/36131", "pm_score": 3, "selected": false, "text": "<p>I like JMock because you are able to set up expectations. This is totally different from checking if a method was called found in some mock libraries. Using JMock you can write very sophisticated expectations. See the jmock <a href=\"http://www.jmock.org/cheat-sheet.html\" rel=\"nofollow noreferrer\">cheat-sheat</a>.</p>\n" }, { "answer_id": 488978, "author": "Jan Kronquist", "author_id": 43935, "author_profile": "https://Stackoverflow.com/users/43935", "pm_score": 6, "selected": false, "text": "<p>I am the creator of PowerMock so obviously I must recommend that! :-)</p>\n\n<p><a href=\"http://powermock.org\" rel=\"noreferrer\">PowerMock</a> extends both EasyMock and Mockito with the ability to <a href=\"http://code.google.com/p/powermock/wiki/MockStatic\" rel=\"noreferrer\">mock static methods</a>, final and even private methods. The EasyMock support is complete, but the Mockito plugin needs some more work. We are planning to add JMock support as well. </p>\n\n<p>PowerMock is not intended to replace other frameworks, rather it can be used in the tricky situations when other frameworks does't allow mocking. PowerMock also contains other useful features such as <a href=\"http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior\" rel=\"noreferrer\">suppressing static initializers</a> and constructors.</p>\n" }, { "answer_id": 489089, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 2, "selected": false, "text": "<p>The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see <a href=\"http://www.scalacheck.org/\" rel=\"nofollow noreferrer\">ScalaCheck</a> and the <a href=\"http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/test/package-summary.html\" rel=\"nofollow noreferrer\">Reductio</a> framework included in the <a href=\"http://functionaljava.org\" rel=\"nofollow noreferrer\">Functional Java</a> library. With automated specification-based testing frameworks, you supply a specification of the method under test (a property about it that should be true) and the framework generates tests as well as mock objects, automatically.</p>\n\n<p>For example, the following property tests the Math.sqrt method to see if the square root of any positive number n squared is equal to n.</p>\n\n<pre><code>val propSqrt = forAll { (n: Int) =&gt; (n &gt;= 0) ==&gt; scala.Math.sqrt(n*n) == n }\n</code></pre>\n\n<p>When you call <code>propSqrt.check()</code>, ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.</p>\n\n<p>Even though ScalaCheck is written in Scala, and requires the Scala Compiler, it's easy to test Java code with it. The Reductio framework in Functional Java is a pure Java implementation of the same concepts.</p>\n" }, { "answer_id": 508379, "author": "James Mead", "author_id": 2025138, "author_profile": "https://Stackoverflow.com/users/2025138", "pm_score": 2, "selected": false, "text": "<p>For something a little different, you could use <a href=\"http://jruby.codehaus.org/\" rel=\"nofollow noreferrer\">JRuby</a> and <a href=\"http://mocha.rubyforge.org/\" rel=\"nofollow noreferrer\">Mocha</a> which are combined in <a href=\"http://docs.codehaus.org/display/JTESTR/Home\" rel=\"nofollow noreferrer\">JtestR</a> to write tests for your Java code in expressive and succinct Ruby. There are some useful mocking examples with JtestR <a href=\"http://docs.codehaus.org/display/JTESTR/Mocks\" rel=\"nofollow noreferrer\">here</a>. One advantage of this approach is that mocking concrete classes is very straightforward.</p>\n" }, { "answer_id": 1024869, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 6, "selected": false, "text": "<p>The <a href=\"http://jmockit.org\" rel=\"noreferrer\">JMockit project site</a> contains plenty of comparative information for current mocking toolkits.</p>\n\n<p>In particular, check out the <strong><a href=\"http://jmockit.org/MockingToolkitComparisonMatrix.html\" rel=\"noreferrer\">feature comparison matrix</a></strong>, which covers EasyMock, jMock, Mockito, Unitils Mock, PowerMock, and of course JMockit. I try to keep it accurate and up-to-date, as much as possible.</p>\n" }, { "answer_id": 2032739, "author": "Dmitry", "author_id": 246969, "author_profile": "https://Stackoverflow.com/users/246969", "pm_score": 3, "selected": false, "text": "<p>I used JMock early. I've tried Mockito at my last project and liked it. More concise, more cleaner. PowerMock covers all needs which are absent in Mockito, such as mocking a static code, mocking an instance creation, mocking final classes and methods. So I have all I need to perform my work.</p>\n" }, { "answer_id": 6393609, "author": "trafalmadorian", "author_id": 204255, "author_profile": "https://Stackoverflow.com/users/204255", "pm_score": 4, "selected": false, "text": "<p>I started using mocks with <a href=\"http://easymock.org/\" rel=\"noreferrer\">EasyMock</a>. Easy enough to understand, but the replay step was kinda annoying. <a href=\"http://code.google.com/p/mockito/\" rel=\"noreferrer\" title=\"Mockito\">Mockito</a> removes this, also has a cleaner syntax as it looks like readability was one of its primary goals. I cannot stress enough how important this is, since most of developers will spend their time reading and maintaining existing code, not creating it. </p>\n\n<p>Another nice thing is that interfaces and implementation classes are handled in the same way, unlike in EasyMock where still you need to remember (and check) to use an EasyMock Class Extension.</p>\n\n<p>I've taken a quick look at <a href=\"http://jmockit.org/\" rel=\"noreferrer\" title=\"JMockit\">JMockit</a> recently, and while the laundry list of features is pretty comprehensive, I think the price of this is legibility of resulting code, and having to write more. </p>\n\n<p>For me, Mockito hits the sweet spot, being easy to write and read, and dealing with majority of the situations most code will require. Using <a href=\"http://code.google.com/p/mockito/\" rel=\"noreferrer\" title=\"Mockito\">Mockito</a> with <a href=\"http://code.google.com/p/powermock/\" rel=\"noreferrer\">PowerMock</a> would be my choice.</p>\n\n<p>One thing to consider is that the tool you would choose if you were developing by yourself, or in a small tight-knit team, might not be the best to get for a large company with developers of varying skill levels. Readability, ease of use and simplicity would need more consideration in the latter case. No sense in getting the ultimate mocking framework if a lot of people end up not using it or not maintaining the tests. </p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2030/" ]
What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?
I've had good success using [Mockito](https://github.com/mockito/mockito). When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me). I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp. Here's an (abridged) example from the Mockito homepage: ``` import static org.mockito.Mockito.*; List mockedList = mock(List.class); mockedList.clear(); verify(mockedList).clear(); ``` It doesn't get much simpler than that. The only major downside I can think of is that it won't mock static methods.
22,708
<p>How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?</p> <p>Edit: A language-agnostic algorithm to determine this is the main goal here.</p>
[ { "answer_id": 22715, "author": "Joseph Sturtevant", "author_id": 317, "author_profile": "https://Stackoverflow.com/users/317", "pm_score": 6, "selected": true, "text": "<p>I once wrote this function to perform that exact task:</p>\n\n<pre><code>public static string Column(int column)\n{\n column--;\n if (column &gt;= 0 &amp;&amp; column &lt; 26)\n return ((char)('A' + column)).ToString();\n else if (column &gt; 25)\n return Column(column / 26) + Column(column % 26 + 1);\n else\n throw new Exception(\"Invalid Column #\" + (column + 1).ToString());\n}\n</code></pre>\n" }, { "answer_id": 22719, "author": "goric", "author_id": 940, "author_profile": "https://Stackoverflow.com/users/940", "pm_score": -1, "selected": false, "text": "<p>I currently use this, but I have a feeling that it can be optimized.</p>\n\n<pre><code>private String GetNthExcelColName(int n)\n{\n String firstLetter = \"\"; \n //if number is under 26, it has a single letter name\n // otherwise, it is 'A' for 27-52, 'B' for 53-78, etc\n if(n &gt; 26)\n {\n //the Converts to double and back to int are just so Floor() can be used\n Double value = Convert.ToDouble((n-1) / 26);\n int firstLetterVal = Convert.ToInt32(Math.Floor(value))-1;\n firstLetter = Convert.ToChar(firstLetterValue + 65).ToString();\n } \n\n //second letter repeats\n int secondLetterValue = (n-1) % 26;\n String secondLetter = Convert.ToChar(secondLetterValue+65).ToString();\n\n return firstLetter + secondLetter;\n}\n</code></pre>\n" }, { "answer_id": 22738, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 3, "selected": false, "text": "<p>Joseph's code is good but, if you don't want or need to use a VBA function, try this.</p>\n\n<p>Assuming that the value of n is in cell <code>A2</code>\nUse this function:</p>\n\n<pre><code>=MID(ADDRESS(1,A2),2,LEN(ADDRESS(1,A2))-3)\n</code></pre>\n" }, { "answer_id": 22766, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>I suppose you need VBA code:</p>\n\n<pre><code>Public Function GetColumnAddress(nCol As Integer) As String\n\nDim r As Range\n\nSet r = Range(\"A1\").Columns(nCol)\nGetColumnAddress = r.Address\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 22959, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 0, "selected": false, "text": "<p>All these code samples that these good people have posted look fine. </p>\n\n<p>There is one thing to be aware of. Starting with Office 2007, Excel actually has up to 16,384 columns. That translates to XFD (the old max of 256 colums was IV). You will have to modify these methods somewhat to make them work for three characters.</p>\n\n<p>Shouldn't be that hard...</p>\n" }, { "answer_id": 23781, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 4, "selected": false, "text": "<p>A language agnostic algorithm would be as follows:</p>\n\n<pre><code>function getNthColumnName(int n) {\n let curPower = 1\n while curPower &lt; n {\n set curPower = curPower * 26\n }\n let result = \"\"\n while n &gt; 0 {\n let temp = n / curPower\n let result = result + char(temp)\n set n = n - (curPower * temp)\n set curPower = curPower / 26\n }\n return result\n</code></pre>\n\n<p>This algorithm also takes into account if Excel gets upgraded again to handle more than 16k columns. If you really wanted to go overboard, you could pass in an additional value and replace the instances of 26 with another number to accomodate alternate alphabets</p>\n" }, { "answer_id": 37002, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 1, "selected": false, "text": "<p>This does what you want in VBA</p>\n\n<pre><code>Function GetNthExcelColName(n As Integer) As String\n Dim s As String\n s = Cells(1, n).Address\n GetNthExcelColName = Mid(s, 2, InStr(2, s, \"$\") - 2)\nEnd Function\n</code></pre>\n" }, { "answer_id": 39952, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 0, "selected": false, "text": "<p>Here's Gary Waters solution</p>\n\n<pre><code>Function ConvertNumberToColumnLetter2(ByVal colNum As Long) As String\n Dim i As Long, x As Long\n For i = 6 To 0 Step -1\n x = (1 - 26 ^ (i + 1)) / (-25) - 1 ‘ Geometric Series formula\n If colNum &gt; x Then\n ConvertNumberToColumnLetter2 = ConvertNumberToColumnLetter2 &amp; Chr(((colNum - x - 1)\\ 26 ^ i) Mod 26 + 65)\n End If\n Next i\nEnd Function\n</code></pre>\n\n<p>via <a href=\"http://www.dailydoseofexcel.com/archives/2004/05/21/column-numbers-to-letters/\" rel=\"nofollow noreferrer\">http://www.dailydoseofexcel.com/archives/2004/05/21/column-numbers-to-letters/</a></p>\n" }, { "answer_id": 50472, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 0, "selected": false, "text": "<p>Considering the comment of wcm (top value = xfd), you can calculate it like this;</p>\n\n<pre><code>function IntToExcel(n: Integer); string;\nbegin\n Result := '';\n for i := 2 down to 0 do \n begin\n if ((n div 26^i)) &gt; 0) or (i = 0) then\n Result := Result + Char(Ord('A')+(n div (26^i)) - IIF(i&gt;0;1;0));\n n := n mod (26^i);\n end;\nend;\n</code></pre>\n\n<p>There are 26 characters in the alphabet and we have a number system just like hex or binary, just with an unusual character set (A..Z), representing positionally the powers of 26: (26^2)(26^1)(26^0).</p>\n" }, { "answer_id": 515791, "author": "Maslow", "author_id": 57883, "author_profile": "https://Stackoverflow.com/users/57883", "pm_score": 1, "selected": false, "text": "<p>This seems to work in vb.net</p>\n\n<pre><code>Public Function Column(ByVal pColumn As Integer) As String\n pColumn -= 1\n If pColumn &gt;= 0 AndAlso pColumn &lt; 26 Then\n Return ChrW(Asc(\"A\"c) + pColumn).ToString\n ElseIf (pColumn &gt; 25) Then\n Return Column(CInt(math.Floor(pColumn / 26))) + Column((pColumn Mod 26) + 1)\n Else\n stop\n Throw New ArgumentException(\"Invalid column #\" + (pColumn + 1).ToString)\n End If\nEnd Function\n</code></pre>\n\n<p>I took Joseph's and tested it to BH, then fed it 980-1000 and it looked good.</p>\n" }, { "answer_id": 1258483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>=CHAR(64+COLUMN())</p>\n" }, { "answer_id": 2292997, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 1, "selected": false, "text": "<p>In VBA, assuming lCol is the column number: </p>\n\n<pre><code>function ColNum2Letter(lCol as long) as string\n ColNum2Letter = Split(Cells(1, lCol).Address, \"$\")(0)\nend function\n</code></pre>\n" }, { "answer_id": 3550070, "author": "Matt Lewis", "author_id": 428667, "author_profile": "https://Stackoverflow.com/users/428667", "pm_score": 2, "selected": false, "text": "<pre><code>IF(COLUMN()&gt;=26,CHAR(ROUND(COLUMN()/26,1)+64)&amp;CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))\n</code></pre>\n\n<p>This works 2 letter columns (up until column <code>ZZ</code>). You'd have to nest another if statement for 3 letter columns. </p>\n\n<p>The formula above fails on columns <code>AY</code>, <code>AZ</code> and each of the following <code>nY</code> and <code>nZ</code> columns. The corrected formula is:</p>\n\n<pre><code>=IF(COLUMN()&gt;26,CHAR(ROUNDDOWN((COLUMN()-1)/26,0)+64)&amp;CHAR(MOD((COLUMN()-1),26)+65),CHAR(COLUMN()+64)\n</code></pre>\n" }, { "answer_id": 4532562, "author": "Samuel Audet", "author_id": 523744, "author_profile": "https://Stackoverflow.com/users/523744", "pm_score": 5, "selected": false, "text": "<p>Here is the cleanest <em>correct</em> solution I could come up with (in Java, but feel free to use your favorite language):</p>\n\n<pre><code>String getNthColumnName(int n) {\n String name = \"\";\n while (n &gt; 0) {\n n--;\n name = (char)('A' + n%26) + name;\n n /= 26;\n }\n return name;\n}\n</code></pre>\n\n<p>But please do let me know of if you find a mistake in this code, thank you.</p>\n" }, { "answer_id": 4695873, "author": "Craig0409", "author_id": 318875, "author_profile": "https://Stackoverflow.com/users/318875", "pm_score": 3, "selected": false, "text": "<p>Thanks, Joseph Sturtevant! Your code works perfectly - I needed it in vbscript, so figured I'd share my version:</p>\n\n<pre><code>Function ColumnLetter(ByVal intColumnNumber)\n Dim sResult\n intColumnNumber = intColumnNumber - 1\n If (intColumnNumber &gt;= 0 And intColumnNumber &lt; 26) Then\n sResult = Chr(65 + intColumnNumber)\n ElseIf (intColumnNumber &gt;= 26) Then\n sResult = ColumnLetter(CLng(intColumnNumber \\ 26)) _\n &amp; ColumnLetter(CLng(intColumnNumber Mod 26 + 1))\n Else\n err.Raise 8, \"Column()\", \"Invalid Column #\" &amp; CStr(intColumnNumber + 1)\n End If\n ColumnLetter = sResult\nEnd Function\n</code></pre>\n" }, { "answer_id": 10017783, "author": "James Evason", "author_id": 900506, "author_profile": "https://Stackoverflow.com/users/900506", "pm_score": 2, "selected": false, "text": "<p>And here is a conversion from the VBScript version to SQL Server 2000+.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE FUNCTION [dbo].[GetExcelColRef] \n(\n @col_seq_no int\n)\nRETURNS varchar(5)\nAS\nBEGIN\n\ndeclare @Result varchar(5)\nset @Result = ''\nset @col_seq_no = @col_seq_no - 1\nIf (@col_seq_no &gt;= 0 And @col_seq_no &lt; 26) \nBEGIN\n set @Result = char(65 + @col_seq_no)\nEND\nELSE\nBEGIN\n set @Result = [dbo].[GetExcelColRef] (@col_seq_no / 26) + '' + [dbo].[GetExcelColRef] ((@col_seq_no % 26) + 1)\nEND\nReturn @Result\n\nEND\nGO\n</code></pre>\n" }, { "answer_id": 12614842, "author": "AndrewD", "author_id": 20151, "author_profile": "https://Stackoverflow.com/users/20151", "pm_score": 0, "selected": false, "text": "<p>FYI T-SQL to give the Excel column name given an ordinal (zero-based), as a single statement.</p>\n\n<p>Anything below 0 or above 16,383 (max columns in Excel2010) returns NULL.</p>\n\n<pre><code>; WITH TestData AS ( -- Major change points\n SELECT -1 AS FieldOrdinal\n UNION ALL\n SELECT 0\n UNION ALL\n SELECT 25\n UNION ALL\n SELECT 26\n UNION ALL\n SELECT 701\n UNION ALL\n SELECT 702\n UNION ALL\n SELECT 703\n UNION ALL\n SELECT 16383\n UNION ALL\n SELECT 16384\n)\nSELECT\n FieldOrdinal\n , CASE\n WHEN FieldOrdinal &lt; 0 THEN NULL\n WHEN FieldOrdinal &lt; 26 THEN ''\n WHEN FieldOrdinal &lt; 702 THEN CHAR (65 + FieldOrdinal / 26 - 1)\n WHEN FieldOrdinal &lt; 16384 THEN CHAR (65 + FieldOrdinal / 676 - 1)\n + CHAR (65 + (FieldOrdinal / 26) - (FieldOrdinal / 676) * 26 - 1)\n ELSE NULL\n END\n + CHAR (65 + FieldOrdinal % 26)\n FROM TestData\n ORDER BY FieldOrdinal\n</code></pre>\n" }, { "answer_id": 13413291, "author": "PatrickDaemen", "author_id": 1829086, "author_profile": "https://Stackoverflow.com/users/1829086", "pm_score": 2, "selected": false, "text": "<p>FROM wcm: </p>\n\n<p>If you don't want to use VBA, you can use this\nreplace colnr with the number you want</p>\n\n<pre><code>=MID(ADDRESS(1,colnr),2,LEN(ADDRESS(1,colnr))-3)\n</code></pre>\n\n<p>Please be aware of the fact that this formula is volatile because of the usage of the ADDRESS function. Volatile functions are functions that are recalculated by excel after EVERY change.\nNormally excel recalculates formula's only when their dependent references changes.</p>\n\n<p>It could be a performance killer, to use this formula.</p>\n" }, { "answer_id": 13882315, "author": "Jim Drannbauer", "author_id": 1904556, "author_profile": "https://Stackoverflow.com/users/1904556", "pm_score": 2, "selected": false, "text": "<p>Ruby one-liner:</p>\n\n<pre><code>def column_name_for(some_int)\n some_int.to_s(26).split('').map {|c| (c.to_i(26) + 64).chr }.join # 703 =&gt; \"AAA\"\nend\n</code></pre>\n\n<p>It converts the integer to base26 then splits it and does some math to convert each character from ascii. Finally joins 'em all back together. No division, modulus, or recursion.</p>\n\n<p>Fun.</p>\n" }, { "answer_id": 16959692, "author": "Kent Pawar", "author_id": 985766, "author_profile": "https://Stackoverflow.com/users/985766", "pm_score": 2, "selected": false, "text": "<p>This works fine in MS Excel 2003-2010. Should work for previous versions supporting the <em>Cells(...).<a href=\"http://msdn.microsoft.com/en-us/library/office/aa174749%28v=office.11%29.aspx\" rel=\"nofollow\">Address</a></em> function:</p>\n\n<ol>\n<li>For the 28th column - taking <code>columnNumber=28</code>; <code>Cells(1, columnNumber).Address</code> returns <code>\"$AB$1\"</code>.</li>\n<li>Doing a split on the <code>$</code> sign returns the array: <code>[\"\",\"AB\",\"1\"]</code></li>\n<li>So <code>Split(Cells(1, columnNumber).Address, \"$\")(1)</code> gives you the column name <code>\"AB\"</code>.</li>\n</ol>\n\n<hr>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Taken from <a href=\"http://support.microsoft.com/kb/833402\" rel=\"nofollow\">How to convert Excel column numbers into alphabetical characters</a></p>\n\n<pre><code>' The following VBA function is just one way to convert column number \n' values into their equivalent alphabetical characters:\n\nFunction ConvertToLetter(iCol As Integer) As String\n Dim iAlpha As Integer\n Dim iRemainder As Integer\n iAlpha = Int(iCol / 27)\n iRemainder = iCol - (iAlpha * 26)\n If iAlpha &gt; 0 Then\n ConvertToLetter = Chr(iAlpha + 64)\n End If\n If iRemainder &gt; 0 Then\n ConvertToLetter = ConvertToLetter &amp; Chr(iRemainder + 64)\n End If\nEnd Function\n</code></pre>\n\n<p>APPLIES TO: Microsoft Office Excel 2007 SE / 2002 SE / 2000 SE / 97 SE</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940/" ]
How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel? Edit: A language-agnostic algorithm to determine this is the main goal here.
I once wrote this function to perform that exact task: ``` public static string Column(int column) { column--; if (column >= 0 && column < 26) return ((char)('A' + column)).ToString(); else if (column > 25) return Column(column / 26) + Column(column % 26 + 1); else throw new Exception("Invalid Column #" + (column + 1).ToString()); } ```
22,720
<p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p> <pre><code>Socket mySocket = new Socket(host,port); </code></pre> <p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p> <pre><code>tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT </code></pre> <p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p> <p>I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.</p> <p>Any advice please?</p> <p>Thanks all</p>
[ { "answer_id": 22803, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": true, "text": "<p>Set a short timeout?</p>\n\n<p>Does <code>isOutputShutdown()</code> not get you what you want?</p>\n\n<p>You could always build a <code>SocketWatcher</code> class that spins up in its own <code>Thread</code> and repeatedly tries to write empty strings to the <code>Socket</code> until that raises a <code>SocketClosedException</code>.</p>\n" }, { "answer_id": 147160, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": -1, "selected": false, "text": "<p>Set a different thread to reading from the socket. It will block until the socket is closed, and then an exception will be thrown. Catch that exception to detect the close immediately.</p>\n" }, { "answer_id": 21961672, "author": "user207421", "author_id": 207421, "author_profile": "https://Stackoverflow.com/users/207421", "pm_score": 0, "selected": false, "text": "<p>The only reliable way to detect a broken connection in TCP is to write to it, which will eventually cause a 'connection reset' IOException. However due to buffering it won't happen on the first write after the disconnection,p but on a subsequent write. You can't do anything about this.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2362/" ]
I have a listening port on my server that I'm connecting to using a Java class and the `Socket` interface, i.e. ``` Socket mySocket = new Socket(host,port); ``` I then grab an `OutputStream`, decorate with a `PrintWriter` in autoflush mode and I'm laughing - except if the listening port closes. Then I get ``` tcp4 0 0 *.9999 *.* LISTEN tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT ``` and I can't seem to detect the problem in the program - I've tried using the `isConnected()` method on the socket but it doesn't seem to know that the connection is closed. I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue. Any advice please? Thanks all
Set a short timeout? Does `isOutputShutdown()` not get you what you want? You could always build a `SocketWatcher` class that spins up in its own `Thread` and repeatedly tries to write empty strings to the `Socket` until that raises a `SocketClosedException`.
22,732
<p>I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.</p> <p><strong>Code</strong></p> <pre><code>function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s </code></pre> <p><strong>Output</strong></p> <pre class="lang-none prettyprint-override"><code>cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 </code></pre>
[ { "answer_id": 22770, "author": "Paul Roub", "author_id": 1324, "author_profile": "https://Stackoverflow.com/users/1324", "pm_score": 7, "selected": true, "text": "<p>Lose the parentheses and commas. </p>\n\n<p>Calling your function as:</p>\n\n<pre><code>$s = CreateAppPoolScript \"name\" \"user\" \"pass\"\n</code></pre>\n\n<p>gives:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>cscript adsutil.vbs CREATE \"w3svc/AppPools/name\" IIsApplicationPool\ncscript adsutil.vbs SET \"w3svc/AppPools/name/WamUserName\" \"user\"\ncscript adsutil.vbs SET \"w3svc/AppPools/name/WamUserPass\" \"pass\"\ncscript adsutil.vbs SET \"w3svc/AppPools/name/AppPoolIdentityType\" 3\n</code></pre>\n" }, { "answer_id": 22946, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>Paul's right.<br>\nIn PowerShell, function parameters are not enclosed in parenthesis. (Method parameters still are.)<br>\nYour initial call was just passing one big array to the function, rather than the three separate parameters you wanted.</p>\n" }, { "answer_id": 40890, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 3, "selected": false, "text": "<p>By the way, using a PowerShell <a href=\"http://blogs.msdn.com/powershell/archive/2006/07/15/Variable-expansion-in-strings-and-herestrings.aspx\" rel=\"noreferrer\">here-string</a> might make your function a little easier to read as well, since you won't need to double up all the <code>\"</code>-marks:</p>\n\n<pre><code>function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)\n{\n # Command to create an IIS application pool\n return @\"\ncscript adsutil.vbs CREATE \"w3svc/AppPools/$AppPoolName\" IIsApplicationPool\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/WamUserName\" \"$AppPoolUser\"\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/WamUserPass\" \"$AppPoolPass\"\ncscript adsutil.vbs SET \"w3svc/AppPools/$AppPoolName/AppPoolIdentityType\" 3\n\"@\n}\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder. **Code** ``` function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s ``` **Output** ```none cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 ```
Lose the parentheses and commas. Calling your function as: ``` $s = CreateAppPoolScript "name" "user" "pass" ``` gives: ```none cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user" cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass" cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3 ```
22,764
<p>In Ruby 1.8 and earlier,</p> <pre><code>Foo </code></pre> <p>is a constant (a Class, a Module, or another constant). Whereas</p> <pre><code>foo </code></pre> <p>is a variable. The key difference is as follows:</p> <pre><code>module Foo bar = 7 BAZ = 8 end Foo::BAZ # =&gt; 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module </code></pre> <p>That's all well and good, but Ruby 1.9 <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html" rel="nofollow noreferrer">allows UTF-8 source code</a>. So is <code>℃</code> "uppercase" or "lowecase" as far as this is concerned? What about <code>⊂</code> (strict subset) or <code>Ɖfoo</code>?</p> <p>Is there a general rule?</p> <p><em>Later:</em></p> <p>Ruby-core is already considering some of the mathematical operators. For example</p> <pre><code>module Kernel def √(num) ... end def ∑(*args) ... end end </code></pre> <p>would allow</p> <pre><code>x = √2 y = ∑(1, 45, ...) </code></pre> <p>I would love to see</p> <pre><code>my_proc = λ { |...| ... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 </code></pre>
[ { "answer_id": 23945, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>I don't know what ruby would do if you used extended UTF8 characters as identifiers in your source code, but I know what I would do, which would be to slap you upside the back of the head and tell you DON'T DO THAT</p>\n" }, { "answer_id": 25592, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>OK, my joking answer didn't go down so well.</p>\n\n<p><a href=\"http://www.nabble.com/String-upcase-downcase-with-UTF-8-strings-in-Ruby-1.9-td18372062.html\" rel=\"nofollow noreferrer\">This mailing list question, with answer from Matz</a> indicates that Ruby 1.9's built in <code>String#upcase</code> and <code>String#downcase</code> methods will only handle ASCII characters.</p>\n\n<p>Without testing it myself, I would see this as strong evidence that all non-ascii characters in source code will likely be considered lowercase.</p>\n\n<p>Can someone download and compile the latest 1.9 and see?</p>\n" }, { "answer_id": 25610, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I would love to see</p>\n</blockquote>\n\n<pre><code>my_proc = λ { |...| ... }\n\nx ∈ my_enumerable # same as my_enumerable.include?(x)\n\nmy_infinite_range = (1..∞)\n\nreturn 'foo' if x ≠ y\n\n2.21 ≈ 2.2\n</code></pre>\n\n<p>I would love to see someone trying to type that program on an English keyboard :P</p>\n" }, { "answer_id": 1434830, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": true, "text": "<p>I can't get IRB to accept UTF-8 characters, so I used a test script (<code>/tmp/utf_test.rb</code>).</p>\n\n<p>\"λ\" works fine as a variable name:</p>\n\n<pre><code># encoding: UTF-8\nλ = 'foo'\nputs λ\n\n# from the command line:\n&gt; ruby -KU /tmp/utf_test.rb\nfoo\n</code></pre>\n\n<p>\"λ\" also works fine as a method name:</p>\n\n<pre><code># encoding: UTF-8\nKernel.class_eval do\n alias_method :λ, :lambda\nend\n\n(λ { puts 'hi' }).call\n\n# from the command line:\n&gt; ruby -KU /tmp/utf_test.rb:\nhi\n</code></pre>\n\n<p>It doesn't work as a constant, though:</p>\n\n<pre><code># encoding: UTF-8\nObject.const_set :λ, 'bar'\n\n# from the command line:\n&gt; ruby -KU /tmp/utf_test.rb:\nutf_test.rb:2:in `const_set': wrong constant name λ (NameError)\n</code></pre>\n\n<p>Nor does the capitalized version:</p>\n\n<pre><code># encoding: UTF-8\nObject.const_set :Λ, 'bar'\n\n# from the command line:\n&gt; ruby -KU /tmp/utf_test.rb:\nutf_test.rb:2:in `const_set': wrong constant name Λ (NameError)\n</code></pre>\n\n<p>My suspicion is that constant names must start with a capital ASCII letter (must match <code>/^[A-Z]/</code>).</p>\n" }, { "answer_id": 4452015, "author": "Adriano Mitre", "author_id": 525555, "author_profile": "https://Stackoverflow.com/users/525555", "pm_score": 1, "selected": false, "text": "<p>In <strong>Ruby 1.9.2-p0 (YARV)</strong> the result is the same as in the original post (i.e., Foo::bar #=> # NoMethodError: undefined method 'bar' for Foo:Module). Also, letters with accent are unfortunately not considered as being upper nor lower and related methods produce no result.</p>\n\n<p>Examples:</p>\n\n<pre><code>\"á\".upcase\n=&gt; \"á\"\n\"á\" == \"Á\".downcase\n=&gt; false\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
In Ruby 1.8 and earlier, ``` Foo ``` is a constant (a Class, a Module, or another constant). Whereas ``` foo ``` is a variable. The key difference is as follows: ``` module Foo bar = 7 BAZ = 8 end Foo::BAZ # => 8 Foo::bar # NoMethodError: undefined method 'bar' for Foo:Module ``` That's all well and good, but Ruby 1.9 [allows UTF-8 source code](http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html). So is `℃` "uppercase" or "lowecase" as far as this is concerned? What about `⊂` (strict subset) or `Ɖfoo`? Is there a general rule? *Later:* Ruby-core is already considering some of the mathematical operators. For example ``` module Kernel def √(num) ... end def ∑(*args) ... end end ``` would allow ``` x = √2 y = ∑(1, 45, ...) ``` I would love to see ``` my_proc = λ { |...| ... } x ∈ my_enumerable # same as my_enumerable.include?(x) my_infinite_range = (1..∞) return 'foo' if x ≠ y 2.21 ≈ 2.2 ```
I can't get IRB to accept UTF-8 characters, so I used a test script (`/tmp/utf_test.rb`). "λ" works fine as a variable name: ``` # encoding: UTF-8 λ = 'foo' puts λ # from the command line: > ruby -KU /tmp/utf_test.rb foo ``` "λ" also works fine as a method name: ``` # encoding: UTF-8 Kernel.class_eval do alias_method :λ, :lambda end (λ { puts 'hi' }).call # from the command line: > ruby -KU /tmp/utf_test.rb: hi ``` It doesn't work as a constant, though: ``` # encoding: UTF-8 Object.const_set :λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name λ (NameError) ``` Nor does the capitalized version: ``` # encoding: UTF-8 Object.const_set :Λ, 'bar' # from the command line: > ruby -KU /tmp/utf_test.rb: utf_test.rb:2:in `const_set': wrong constant name Λ (NameError) ``` My suspicion is that constant names must start with a capital ASCII letter (must match `/^[A-Z]/`).
22,801
<p>It's about PHP but I've no doubt many of the same comments will apply to other languages.</p> <p>Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?</p> <pre><code>for ($i = 0; $i &lt; 10; $i++) { # code... } foreach ($array as $index =&gt; $value) { # code... } do { # code... } while ($flag == false); </code></pre>
[ { "answer_id": 22806, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 0, "selected": false, "text": "<p>I use the first loop when iterating over a conventional (indexed?) array and the foreach loop when dealing with an associative array. It just seems natural and helps the code flow and be more readable, in my opinion. As for do...while loops, I use those when I have to do more than just flip through an array.</p>\n\n<p>I'm not sure of any performance benefits, though.</p>\n" }, { "answer_id": 22810, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 0, "selected": false, "text": "<p>Performance is not significantly better in either case. While is useful for more complex tasks than iterating, but <code>for</code> and <code>while</code> are functionally equivalent.</p>\n\n<p><code>Foreach</code> is nice, but has one important caveat: you <strong>can't modify</strong> the enumerable you're iterating. So no removing, adding or replacing entries to/in it. Modifying entries (like changing their properties) is OK, of course.</p>\n" }, { "answer_id": 22811, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 0, "selected": false, "text": "<p>With a foreach loop, a copy of the original array is made in memory to use inside. You shouldn't use them on large structures; a simple for loop is a better choice. You can use a while loop more efficiently on a large non-numerically indexed structure like this:</p>\n\n<pre><code>while(list($key, $value) = each($array)) {\n</code></pre>\n\n<p>But that approach is particularly ugly for a simple small structure.</p>\n\n<p>while loops are better suited for looping through streams, or as in the following example that you see very frequently in PHP:</p>\n\n<pre><code>while ($row = mysql_fetch_array($result)) {\n</code></pre>\n\n<p>Almost all of the time the different loops are interchangeable, and it will come down to either a) efficiency, or b) clarity.</p>\n\n<p>If you know the efficiency trade-offs of the different types of loops, then yes, to answer your original question: use the one that looks the most clean.</p>\n" }, { "answer_id": 22813, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 0, "selected": false, "text": "<p>In regards to performance, a foreach is more consuming than a for</p>\n\n<p><a href=\"http://forums.asp.net/p/1041090/1457897.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1041090/1457897.aspx</a></p>\n" }, { "answer_id": 22832, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 1, "selected": false, "text": "<p>This is CS101, but since no one else has mentioned it, while loops evaluate their condition before the code block, and do-while evaluates after the code block, so do-while loops are always guaranteed to run their code block at least once, regardless of the condition.</p>\n" }, { "answer_id": 22838, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.php.lt/benchmark/phpbench.php\" rel=\"nofollow noreferrer\">PHP Benchmarks</a></p>\n" }, { "answer_id": 22844, "author": "JeremiahClark", "author_id": 581, "author_profile": "https://Stackoverflow.com/users/581", "pm_score": 0, "selected": false, "text": "<p>Each looping construct serves a different purpose.</p>\n\n<p>for - This is used to loop for a specific number of iterations. </p>\n\n<p>foreach - This is used to loop through all of the values in a collection.</p>\n\n<p>while - This is used to loop until you meet a condition.</p>\n\n<p>Of the three, \"while\" will most likely provide the best performance in most situations. Of course, if you do something like the following, you are basically rewriting the \"for\" loop (which in c# is slightly more performant).</p>\n\n<pre><code>$count = 0;\ndo\n{\n ...\n $count++;\n}\nwhile ($count &lt; 10); \n</code></pre>\n\n<p>They all have different basic purposes, but they can also be used in somewhat the same way. It completely depends on the specific problem that you are trying to solve. </p>\n" }, { "answer_id": 23024, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>@brendan:</p>\n\n<p>The article you cited is seriously outdated and the information is just plain wrong. Especially the last point (use <code>for</code> instead of <code>foreach</code>) is misleading and the justification offered in the article no longer applies to modern versions of .NET.</p>\n\n<p>While it's true that the <code>IEnumerator</code> uses virtual calls, these <em>can</em> actually be inlined by a modern compiler. Furthermore, .NET now knows generics and strongly typed enumerators.</p>\n\n<p>There are a lot of performance tests out there that prove conclusively that <code>for</code> is generally no faster than <code>foreach</code>. <a href=\"http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx\" rel=\"nofollow noreferrer\">Here's an example</a>.</p>\n" }, { "answer_id": 23739, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>With a foreach loop, a copy of the original array is made in memory to use inside.</p>\n<p>Foreach is nice, but has one important caveat: you can't modify the enumerable you're iterating.</p>\n</blockquote>\n<p>Both of those won't be a problem if you pass by reference instead of value:</p>\n<pre><code> foreach ($array as &amp;$value) {\n</code></pre>\n<p>I think this has been allowed since PHP 5.</p>\n" }, { "answer_id": 23750, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 0, "selected": false, "text": "<p>When accessing the elements of an array, for clarity I would use a foreach whenever possible, and only use a for if you need the actual index values (for example, the same index in multiple arrays). This also minimizes the chance for typo mistakes since for loops make this all too easy. In general, PHP might not be the place be worrying too much about performance. And last but not least, for and foreach have (or should have; I'm not a PHP-er) the same Big-O time (O(n)) so you are looking possibly at a small amount more of memory usage or a slight constant or linear hit in time.</p>\n" }, { "answer_id": 23835, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 4, "selected": true, "text": "<p>For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet </p>\n\n<p>The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;</p>\n\n<pre><code>for ($i = 0; $i &lt; 10; $i++)\n{\n # code...\n}\n</code></pre>\n\n<p>Same thing done with while loop:</p>\n\n<pre><code>$i = 0;\nwhile ($i &lt; 10)\n{\n # code...\n $i++\n}\n</code></pre>\n\n<p>Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block</p>\n\n<pre><code>do\n{\n # code...\n}\nwhile ($flag == false);\n</code></pre>\n\n<p>foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.</p>\n\n<pre><code>foreach ($array as $index =&gt; $value)\n{\n # code...\n}\n</code></pre>\n\n<p>You could do the same thing with while loop, like this </p>\n\n<pre><code>while (current($array))\n{\n $index = key($array); // to get key of the current element\n $value = $array[$index]; // to get value of current element\n\n # code ... \n\n next($array); // advance the internal array pointer of $array\n}\n</code></pre>\n\n<p>And lastly: <a href=\"http://www.php.net/download-docs.php\" rel=\"noreferrer\">The PHP Manual</a> is your friend :)</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
It's about PHP but I've no doubt many of the same comments will apply to other languages. Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop? ``` for ($i = 0; $i < 10; $i++) { # code... } foreach ($array as $index => $value) { # code... } do { # code... } while ($flag == false); ```
For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9; ``` for ($i = 0; $i < 10; $i++) { # code... } ``` Same thing done with while loop: ``` $i = 0; while ($i < 10) { # code... $i++ } ``` Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block ``` do { # code... } while ($flag == false); ``` foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index. ``` foreach ($array as $index => $value) { # code... } ``` You could do the same thing with while loop, like this ``` while (current($array)) { $index = key($array); // to get key of the current element $value = $array[$index]; // to get value of current element # code ... next($array); // advance the internal array pointer of $array } ``` And lastly: [The PHP Manual](http://www.php.net/download-docs.php) is your friend :)
22,807
<p>Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates?</p> <p>Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.</p> <pre><code>AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101)) &lt;= Convert(datetime, Convert(char(10), GetDate(), 101)) AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101)) &gt;= Convert(datetime, Convert(char(10), GetDate(), 101)) </code></pre>
[ { "answer_id": 22809, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": -1, "selected": false, "text": "<p>try</p>\n\n<pre><code>ep.EffectiveStartDate BETWEEN @date1 AND @date2\n</code></pre>\n\n<p>where you would do something like</p>\n\n<pre><code>declare @date1 datetime, @date2 datetime; \nset @date1 = cast('10/1/2000' as datetime) \nset @date2 = cast('10/1/2020' as datetime)\n</code></pre>\n" }, { "answer_id": 22817, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 1, "selected": false, "text": "<p>That is terrible, take a look at <a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr\" rel=\"nofollow noreferrer\">Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code</a> to see how you can optimize this since that is not sargable</p>\n\n<p>Also check out <a href=\"http://wiki.lessthandot.com/index.php/Get_Datetime_Without_Time\" rel=\"nofollow noreferrer\">Get Datetime Without Time</a> and <a href=\"http://wiki.lessthandot.com/index.php/Query_Optimizations_With_Dates\" rel=\"nofollow noreferrer\">Query Optimizations With Dates</a></p>\n" }, { "answer_id": 22820, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<p>@Darren Kopp</p>\n\n<p>Be carefull with BETWEEN, check out <a href=\"http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-does-between-work-with-dates-in-sql-\" rel=\"nofollow noreferrer\">How Does Between Work With Dates In SQL Server?</a></p>\n" }, { "answer_id": 22824, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 1, "selected": false, "text": "<p>@Darren Kopp - you can use </p>\n\n<pre><code>set @date2 = '20201001'\n</code></pre>\n\n<p>this will let you lose the cast.</p>\n\n<p>footndale - you can use date arithmetic to remove the time as well. Something like </p>\n\n<pre><code>select dateadd(d, datediff(d, 0, CURRENT_TIMESTAMP), 0)\n</code></pre>\n\n<p>to get today's date (without the time). I believe this is more efficient than casting back and forth.</p>\n" }, { "answer_id": 4799464, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 0, "selected": false, "text": "<pre><code>AND DateDiff(Day, 0, GetDate()) + 1 &gt; ep.EffectiveStartDate\nAND DateDiff(Day, 0, GetDate()) &lt; ep.EffectiveEndDate\n</code></pre>\n\n<p>I think you will find that these conditions offer the best performance possible. This will happily utilize indexes.</p>\n\n<p>I am also very sure that this is right and will give the right data. No further calculation of dates without time portions is needed.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2526/" ]
Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates? Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005. ``` AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101)) <= Convert(datetime, Convert(char(10), GetDate(), 101)) AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101)) >= Convert(datetime, Convert(char(10), GetDate(), 101)) ```
That is terrible, take a look at [Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr) to see how you can optimize this since that is not sargable Also check out [Get Datetime Without Time](http://wiki.lessthandot.com/index.php/Get_Datetime_Without_Time) and [Query Optimizations With Dates](http://wiki.lessthandot.com/index.php/Query_Optimizations_With_Dates)
22,816
<p>I know the following libraries for drawing charts in an SWT/Eclipse RCP application:</p> <ul> <li><a href="http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html" rel="noreferrer">Eclipse BIRT Chart Engine</a> (Links to an article on how to use it)</li> <li><a href="http://www.jfree.org/jfreechart/" rel="noreferrer">JFreeChart</a></li> </ul> <p>Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...</p>
[ { "answer_id": 22830, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 0, "selected": false, "text": "<p>There's also JGraph, but I'm not sure if that's only for graphs (i.e. nodes and edges), or if it does charts also.</p>\n" }, { "answer_id": 25920, "author": "zvikico", "author_id": 2823, "author_profile": "https://Stackoverflow.com/users/2823", "pm_score": 0, "selected": false, "text": "<p>Here's something different: it's very to embed web pages in SWT views. I recently tried it and it works very well. You can see where this is going: there are plenty of beautiful charting components for HTML, it could be an option. Just make sure the component is client-side only (unless you want to start a server).</p>\n\n<p>I haven't tested Flash, but I'm pretty sure you can get it to work (naturally, this means your software will require Flash plug-in installed).</p>\n" }, { "answer_id": 43112, "author": "Ryan P", "author_id": 1539, "author_profile": "https://Stackoverflow.com/users/1539", "pm_score": 5, "selected": true, "text": "<p>I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite </p>\n\n<pre><code>Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);\nFrame frame = SWT_AWT.new_Frame(comp);\nJFreeChart chart = createChart();\nChartPanel chartPanel = new ChartPanel(chart);\nframe.add(chartPanel);\n</code></pre>\n\n<p>There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower.</p>\n\n<p>@zvikico</p>\n\n<p>The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.</p>\n" }, { "answer_id": 45872, "author": "Tibi", "author_id": 4717, "author_profile": "https://Stackoverflow.com/users/4717", "pm_score": 1, "selected": false, "text": "<p>There’s also <a href=\"http://www.ilog.com/products/jviews/charts/\" rel=\"nofollow noreferrer\">ILOG JViews Charts</a> which looks pretty feature-complete… if you can afford it.\n<a href=\"http://blogs.ilog.com/jviews/2008/06/17/jviews-shines-through-on-eclipse/\" rel=\"nofollow noreferrer\">Here</a> is some additional infos on using it with eclipse. </p>\n" }, { "answer_id": 48724, "author": "Chris Dail", "author_id": 5077, "author_profile": "https://Stackoverflow.com/users/5077", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://jcharts.sourceforge.net/\" rel=\"nofollow noreferrer\">JCharts</a> is another option. It is similar to JFreeChart but the documentation is free. It does not have direct support for SWT but you can always generate an image and embed it in an SWT frame.</p>\n" }, { "answer_id": 2102436, "author": "Caleb Peterson", "author_id": 225237, "author_profile": "https://Stackoverflow.com/users/225237", "pm_score": 3, "selected": false, "text": "<p>SWTChart gives good results for line, scatter, bar, and area charts. The API is straight forward and there are numerous examples on the website. I went from finding it on google to viewing my data in less than an hour.</p>\n\n<p><a href=\"http://www.swtchart.org/index.html\" rel=\"noreferrer\">SWTChart</a></p>\n" }, { "answer_id": 2102528, "author": "Matti Lyra", "author_id": 100190, "author_profile": "https://Stackoverflow.com/users/100190", "pm_score": 2, "selected": false, "text": "<p>The one I've used are <a href=\"http://jchart2d.sourceforge.net/\" rel=\"nofollow noreferrer\">JChart2D</a> and JFreeChart. I did a live plotter application over the summer and used JFreeChart for that. The guy who had started the project had used JChart2D but I found that it doesn't have enough options for tweaking the chart look and feel.</p>\n\n<p>JChart2D is supposed to be very fast so if you need to do live plotting have a look at it, although JFreeChart didn't have any problems doing a plot a few times per second.</p>\n\n<p>There also quite a list of charting libraries on <a href=\"http://www.java2s.com/Product/Java/GUI-Tools/Chart.htm\" rel=\"nofollow noreferrer\">java2s.com</a></p>\n" }, { "answer_id": 3206363, "author": "Martin Pernollet", "author_id": 229513, "author_profile": "https://Stackoverflow.com/users/229513", "pm_score": 1, "selected": false, "text": "<p>I suggest you try <a href=\"http://jzy3d.org/\" rel=\"nofollow noreferrer\">jzy3d</a>, a simple java library for plotting 3d data. It's for java, on AWT, Swing or SWT.</p>\n" }, { "answer_id": 8771380, "author": "Jonathan Schneider", "author_id": 510017, "author_profile": "https://Stackoverflow.com/users/510017", "pm_score": 3, "selected": false, "text": "<p>You might like <a href=\"http://code.google.com/p/swt-xy-graph/\" rel=\"noreferrer\">this</a> one too</p>\n\n<p>It has the ability to plot real time data with your own data provider.</p>\n\n<p><img src=\"https://i.stack.imgur.com/uYAoL.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 9120988, "author": "vambo", "author_id": 1099376, "author_profile": "https://Stackoverflow.com/users/1099376", "pm_score": 2, "selected": false, "text": "<p>I was also looking for a charting library for an Eclipse RCP app, stumbled on Caleb's post here and can definitely recommend SWTChart now myself. It is a lot faster than JFreeChart for me, plus easily extensible. If I would really have to complain about something, I'd say the javadoc could be a bit more verbose, but this is just to say everything else is great.</p>\n" }, { "answer_id": 32049679, "author": "Stefan", "author_id": 2876079, "author_profile": "https://Stackoverflow.com/users/2876079", "pm_score": 1, "selected": false, "text": "<p>After evaluationg several options I decided to use a JavaScript library for showing plots in my Eclipse Plugin. As zvikico already suggested it is possible to show a html page in a browser. In the html page you can utilize one of the JavaScript libraries to do the actual plotting. If you use Chartist you can save the image as SVG file from the context menu. </p>\n\n<p>Some JavaScript charting libraries:</p>\n\n<ul>\n<li><p>Chartist: <a href=\"http://gionkunz.github.io/chartist-js\" rel=\"nofollow noreferrer\">http://gionkunz.github.io/chartist-js</a></p></li>\n<li><p>D3js: <a href=\"http://d3js.org\" rel=\"nofollow noreferrer\">http://d3js.org</a></p></li>\n<li><p>Flot: <a href=\"http://www.flotcharts.org/\" rel=\"nofollow noreferrer\">http://www.flotcharts.org/</a></p></li>\n<li><p>Further JavaScript charting frameworks: <a href=\"https://en.wikipedia.org/wiki/Comparison_of_JavaScript_charting_frameworks\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Comparison_of_JavaScript_charting_frameworks</a></p></li>\n</ul>\n\n<p><strong>Chartist Example image</strong>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oG9mD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oG9mD.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Example java code</strong>:</p>\n\n<pre><code>package org.treez.results.chartist;\n\nimport java.net.URL;\n\nimport javafx.application.Application;\nimport javafx.concurrent.Worker;\nimport javafx.geometry.HPos;\nimport javafx.geometry.VPos;\nimport javafx.scene.Scene;\nimport javafx.scene.layout.Region;\nimport javafx.scene.paint.Color;\nimport javafx.scene.web.WebEngine;\nimport javafx.scene.web.WebView;\nimport javafx.stage.Stage;\nimport netscape.javascript.JSObject;\n\npublic class WebViewSample extends Application {\n\n private Scene scene;\n\n @Override\n public void start(Stage stage) {\n // create the scene\n stage.setTitle(\"Web View\");\n Browser browser = new Browser();\n scene = new Scene(browser, 750, 500, Color.web(\"#666970\"));\n stage.setScene(scene);\n stage.show();\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n}\n\nclass Browser extends Region {\n\n final WebView browser = new WebView();\n\n final WebEngine webEngine = browser.getEngine();\n\n public Browser() {\n\n //add the web view to the scene\n getChildren().add(browser);\n\n //add finished listener\n webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -&gt; {\n if (newState == Worker.State.SUCCEEDED) {\n executeJavaScript();\n }\n });\n\n // load the web page\n URL url = WebViewSample.class.getResource(\"chartist.html\");\n String urlPath = url.toExternalForm();\n webEngine.load(urlPath);\n\n }\n\n private void executeJavaScript() {\n\n String script = \"var chartist = new Chartist.Line(\" + \"'#chart',\" + \" \" + \"{\"\n + \" labels: [1, 2, 3, 4, 5, 6, 7, 8],\" + \"series: [\" + \" [5, 9, 7, 8, 5, 3, 5, 44]\" + \"]\" + \"}, \" + \"\"\n + \"{\" + \" low: 0,\" + \" showArea: true\" + \"}\" + \"\" + \");\" + \" var get = function(){return chartist};\";\n\n webEngine.executeScript(script);\n\n Object resultJs = webEngine.executeScript(\"get()\");\n\n //get line\n JSObject line = (JSObject) resultJs;\n String getKeys = \"{var keys = [];for (var key in this) {keys.push(key);} keys;}\";\n JSObject linekeys = (JSObject) line.eval(getKeys);\n\n JSObject options = (JSObject) line.eval(\"this.options\");\n JSObject optionkeys = (JSObject) options.eval(getKeys);\n\n options.eval(\"this.showLine=false\");\n\n }\n\n @Override\n protected void layoutChildren() {\n double w = getWidth();\n double h = getHeight();\n layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);\n }\n\n @Override\n protected double computePrefWidth(double height) {\n return 750;\n }\n\n @Override\n protected double computePrefHeight(double width) {\n return 500;\n }\n}\n</code></pre>\n\n<p><strong>Example html page</strong>:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"chartist.min.css\"&gt; \n&lt;/head&gt;\n&lt;body&gt;\n &lt;div class=\"ct-chart\" id=\"chart\"&gt;&lt;/div&gt;\n &lt;script type=\"text/javascript\" src=\"chartist.js\"&gt;&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In order to get this working, chartist.js and chartist.min.css need to be downloaded and put at the same location as the html file. You could also include them from the web. See here for another example:\n<a href=\"https://www.snip2code.com/Snippet/233633/Chartist-js-example\" rel=\"nofollow noreferrer\">https://www.snip2code.com/Snippet/233633/Chartist-js-example</a></p>\n\n<p><strong>Edit</strong></p>\n\n<p>I created a java wrapper for D3.js, see</p>\n\n<p><a href=\"https://github.com/stefaneidelloth/javafx-d3\" rel=\"nofollow noreferrer\">https://github.com/stefaneidelloth/javafx-d3</a></p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1793/" ]
I know the following libraries for drawing charts in an SWT/Eclipse RCP application: * [Eclipse BIRT Chart Engine](http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html) (Links to an article on how to use it) * [JFreeChart](http://www.jfree.org/jfreechart/) Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...
I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite ``` Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED); Frame frame = SWT_AWT.new_Frame(comp); JFreeChart chart = createChart(); ChartPanel chartPanel = new ChartPanel(chart); frame.add(chartPanel); ``` There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower. @zvikico The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing.
22,836
<p>In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?</p> <p>I usually just copy the string to a new variable then bind it to the <code>s///</code> regex that does the replacement on the new string, but I was wondering if there is a better way to do this?</p> <pre><code>$newstring = $oldstring; $newstring =~ s/foo/bar/g; </code></pre>
[ { "answer_id": 22896, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 9, "selected": true, "text": "<p>This is the idiom I've always used to get a modified copy of a string without changing the original:</p>\n<pre><code>(my $newstring = $oldstring) =~ s/foo/bar/g;\n</code></pre>\n<p>In perl 5.14.0 or later, you can use the new <code>/r</code> <a href=\"https://metacpan.org/pod/release/FLORA/perl-5.14.2/pod/perl5140delta.pod#Non-destructive-substitution\" rel=\"noreferrer\">non-destructive substitution modifier</a>:</p>\n<pre><code>my $newstring = $oldstring =~ s/foo/bar/gr; \n</code></pre>\n<hr />\n<p><strong>NOTE:</strong><br />\nThe above solutions work without <code>g</code> too. They also work with any other modifiers.</p>\n<p><strong>SEE ALSO:</strong><br />\n<a href=\"https://perldoc.perl.org/perlrequick\" rel=\"noreferrer\"><code>perldoc perlrequick</code>: Perl regular expressions quick start</a></p>\n" }, { "answer_id": 24090, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": false, "text": "<p>The statement:</p>\n\n<pre><code>(my $newstring = $oldstring) =~ s/foo/bar/g;\n</code></pre>\n\n<p>Which is equivalent to:</p>\n\n<pre><code>my $newstring = $oldstring;\n$newstring =~ s/foo/bar/g;\n</code></pre>\n\n<p>Alternatively, as of Perl 5.13.2 you can use <code>/r</code> to do a non destructive substitution:</p>\n\n<pre><code>use 5.013;\n#...\nmy $newstring = $oldstring =~ s/foo/bar/gr;\n</code></pre>\n" }, { "answer_id": 55786, "author": "Tim Kennedy", "author_id": 5699, "author_profile": "https://Stackoverflow.com/users/5699", "pm_score": 0, "selected": false, "text": "<p>If you write Perl with <code>use strict;</code>, then you'll find that the one line syntax isn't valid, even when declared.</p>\n\n<p>With:</p>\n\n<pre><code>my ($newstring = $oldstring) =~ s/foo/bar/;\n</code></pre>\n\n<p>You get:</p>\n\n<pre><code>Can't declare scalar assignment in \"my\" at script.pl line 7, near \") =~\"\nExecution of script.pl aborted due to compilation errors.\n</code></pre>\n\n<p>Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with <code>use strict;</code>. For me, using <code>use strict;</code> is just a habit now. I do it automatically. Everyone should.</p>\n\n<pre><code>#!/usr/bin/env perl -wT\n\nuse strict;\n\nmy $oldstring = \"foo one foo two foo three\";\nmy $newstring = $oldstring;\n$newstring =~ s/foo/bar/g;\n\nprint \"$oldstring\",\"\\n\";\nprint \"$newstring\",\"\\n\";\n</code></pre>\n" }, { "answer_id": 62500, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 5, "selected": false, "text": "<p>Under <code>use strict</code>, say:</p>\n\n<pre><code>(my $new = $original) =~ s/foo/bar/;\n</code></pre>\n\n<p>instead.</p>\n" }, { "answer_id": 94557, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 4, "selected": false, "text": "<p>The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.</p>\n\n<p>In other words, a good way to do this is the way you're <i>already</i> doing it. Unnecessary concision at the cost of readability isn't a win.</p>\n" }, { "answer_id": 35829163, "author": "JoGotta", "author_id": 3037683, "author_profile": "https://Stackoverflow.com/users/3037683", "pm_score": 0, "selected": false, "text": "<p>I hate foo and bar .. who dreamed up these non descriptive terms in programming anyway?</p>\n\n<pre><code>my $oldstring = \"replace donotreplace replace donotreplace replace donotreplace\";\n\nmy $newstring = $oldstring;\n$newstring =~ s/replace/newword/g; # inplace replacement\n\nprint $newstring;\n%: newword donotreplace newword donotreplace newword donotreplace\n</code></pre>\n" }, { "answer_id": 44172761, "author": "textral", "author_id": 1206102, "author_profile": "https://Stackoverflow.com/users/1206102", "pm_score": 2, "selected": false, "text": "<p>Another pre-5.14 solution: <a href=\"http://www.perlmonks.org/?node_id=346719\" rel=\"nofollow noreferrer\">http://www.perlmonks.org/?node_id=346719</a> (see japhy's post)</p>\n\n<p>As his approach uses <code>map</code>, it also works well for arrays, but requires cascading <code>map</code> to produce a temporary array (otherwise the original would be modified):</p>\n\n<pre><code>my @orig = ('this', 'this sucks', 'what is this?');\nmy @list = map { s/this/that/; $_ } map { $_ } @orig;\n# @orig unmodified\n</code></pre>\n" }, { "answer_id": 67513243, "author": "ngn999", "author_id": 461293, "author_profile": "https://Stackoverflow.com/users/461293", "pm_score": 0, "selected": false, "text": "<p>if I just use this in oneliner, how about, <code>sprintf(&quot;%s&quot;, $oldstring)</code></p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original? I usually just copy the string to a new variable then bind it to the `s///` regex that does the replacement on the new string, but I was wondering if there is a better way to do this? ``` $newstring = $oldstring; $newstring =~ s/foo/bar/g; ```
This is the idiom I've always used to get a modified copy of a string without changing the original: ``` (my $newstring = $oldstring) =~ s/foo/bar/g; ``` In perl 5.14.0 or later, you can use the new `/r` [non-destructive substitution modifier](https://metacpan.org/pod/release/FLORA/perl-5.14.2/pod/perl5140delta.pod#Non-destructive-substitution): ``` my $newstring = $oldstring =~ s/foo/bar/gr; ``` --- **NOTE:** The above solutions work without `g` too. They also work with any other modifiers. **SEE ALSO:** [`perldoc perlrequick`: Perl regular expressions quick start](https://perldoc.perl.org/perlrequick)
22,879
<p>I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?</p>
[ { "answer_id": 22891, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 1, "selected": false, "text": "<p>Prefix with '</p>\n" }, { "answer_id": 22897, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 1, "selected": false, "text": "<p>Prefixing the contents of the cell with ' forces Excel to see it as text instead of a number. The ' won't be displayed in Excel.</p>\n" }, { "answer_id": 22900, "author": "Krantz", "author_id": 2528, "author_profile": "https://Stackoverflow.com/users/2528", "pm_score": 0, "selected": false, "text": "<p>I think the way to do this would be to format the source excel file such that the column is formatted as Text instead of General. Select the entire column and right click and select format cells, select text from the list of options.</p>\n\n<p>I think that would explicitly define that the column content is text and should be treated as such.</p>\n\n<p>Let me know if that works.</p>\n" }, { "answer_id": 22908, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 4, "selected": true, "text": "<p>I believe you have to set the option in your connect string to force textual import rather than auto-detecting it.</p>\n\n<pre><code>Provider=Microsoft.ACE.OLEDB.12.0;\n Data Source=c:\\path\\to\\myfile.xlsx;\n Extended Properties=\\\"Excel 12.0 Xml;IMEX=1\\\";\n</code></pre>\n\n<p>Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text.</p>\n" }, { "answer_id": 22926, "author": "TheEmirOfGroofunkistan", "author_id": 1874, "author_profile": "https://Stackoverflow.com/users/1874", "pm_score": 0, "selected": false, "text": "<p>Saving the file as a tab delimited text file has also worked well.</p>\n\n<p>---old\nUnfortunately, we can't rely on the columns of the excel doc to stay in a particular format as the users will be pasting data into it regularly. I don't want the app to crash if we're relying on a certain datatype for a column.</p>\n\n<p>prefixing with ' would work, is there a reasonable way to do that programatically once the data already exists in the excel doc?</p>\n" }, { "answer_id": 677697, "author": "cjk", "author_id": 52201, "author_profile": "https://Stackoverflow.com/users/52201", "pm_score": 1, "selected": false, "text": "<p>There is a registry hack that can force Excel to read more than the first 8 rows when reading a column to determine the type:</p>\n\n<p>Change</p>\n\n<pre><code>HKLM\\Software\\Microsoft\\Jet\\4.0\\Engines\\Excel\\TypeGuessRows \n</code></pre>\n\n<p>To be 0 to read all rows, or another number to set it to that number of rows. </p>\n\n<p>Not that this will have a slighht performance hit.</p>\n" }, { "answer_id": 20784334, "author": "Rajans", "author_id": 3136602, "author_profile": "https://Stackoverflow.com/users/3136602", "pm_score": 0, "selected": false, "text": "<p>Sending value <code>00022556</code> as <code>'=\" 00022556\"'</code> from Sql server is excellent way to handle leading zero problem</p>\n" }, { "answer_id": 29393654, "author": "zoobiezoobie", "author_id": 4596997, "author_profile": "https://Stackoverflow.com/users/4596997", "pm_score": 0, "selected": false, "text": "<p>Add \"\\t\" before your string. It'll make the string seem in a new tab.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?
I believe you have to set the option in your connect string to force textual import rather than auto-detecting it. ``` Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\path\to\myfile.xlsx; Extended Properties=\"Excel 12.0 Xml;IMEX=1\"; ``` Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text.
22,935
<p>Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file? </p> <p>I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...</p>
[ { "answer_id": 22948, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": true, "text": "<p>In SQL server it is as easy as</p>\n\n<pre><code>SELECT * INTO NewTablenNmeHere\nFROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', \n'Excel 8.0;Database=C:\\testing.xls','SELECT * FROM [Sheet1$]') \n</code></pre>\n" }, { "answer_id": 22951, "author": "Krantz", "author_id": 2528, "author_profile": "https://Stackoverflow.com/users/2528", "pm_score": 1, "selected": false, "text": "<pre><code>BULK \nINSERT CSVTest\n FROM 'c:\\csvtest.txt'\n WITH\n (\n FIELDTERMINATOR = ',',\n ROWTERMINATOR = '\\n'\n )\n</code></pre>\n" }, { "answer_id": 22962, "author": "Danielb", "author_id": 39040, "author_profile": "https://Stackoverflow.com/users/39040", "pm_score": 0, "selected": false, "text": "<p>Unfortunately I'm using an SQLEngine for embedded systems so it does not support BULK INSERT or OLEDB datasources, which is why I was thinking of taking the sql statement generation approach.</p>\n" }, { "answer_id": 9886375, "author": "wombat", "author_id": 1295055, "author_profile": "https://Stackoverflow.com/users/1295055", "pm_score": 1, "selected": false, "text": "<p>I recommend having a look at <a href=\"https://github.com/onyxfish/csvkit\" rel=\"nofollow\">csvkit</a>. Its <a href=\"http://csvkit.readthedocs.org/en/latest/scripts/csvsql.html\" rel=\"nofollow\">csvsql</a> function can generate table insert statements, or even execute them for you, from most tabular data sources. </p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39040/" ]
Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file? I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...
In SQL server it is as easy as ``` SELECT * INTO NewTablenNmeHere FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]') ```
22,976
<p>I've got a JavaScript "object", built this way:</p> <pre><code>function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; } ... </code></pre> <p>I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? </p> <p>I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. </p> <p>Thanks rp</p>
[ { "answer_id": 22998, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 2, "selected": false, "text": "<p>Shouldn't be much different:</p>\n\n<pre><code>namespace.foo = function foo() {...}\nnamespace.foo.prototype.getLength = function() { ... }\n</code></pre>\n\n<p>or you could use</p>\n\n<pre><code>(function() {\n function foo() { ... }\n foo.prototype...\n namespace.foo = foo;\n})();\n</code></pre>\n\n<p>to save some typing.</p>\n" }, { "answer_id": 23089, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": true, "text": "<p>Simple:</p>\n\n<pre><code>if(!MyNamespace) MyNamespace = {};\n\nMyNamespace.foo = function() {\n this.length = 0;\n};\nMyNamespace.foo.prototype.getLength = function() {\n return this.length;\n};\n</code></pre>\n" }, { "answer_id": 23207, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "<p>Javascript doesn't really have namespace or packages like other languages. Instead it has closures. If you have an application that consists of multiple functions, variables and objects, then you should put them inside a single global object. This will have the same effect as a namespace. </p>\n\n<p>For example:</p>\n\n<pre><code>var namespace = {\n this.foo: function(){\n ...\n },\n this.foo.prototype.getLength: function(){\n ...\n }\n}\n</code></pre>\n\n<p>You could also create a set of nested objects and simulate packages:</p>\n\n<pre><code>loadPackage = function(){\n var path = arguments[0];\n for(var i=1; i&lt;arguments.length; i++){\n if(!path[arguments[i]]){\n path[arguments[i]] = {};\n }\n path = path[arguments[i]];\n }\n return path;\n}\n\nloadPackage(this, \"com\", \"google\", \"mail\") = {\n username: \"gundersen\",\n login: function(password){\n ...\n }\n}\nthis.com.google.mail.login(\"mySecretPassword\");\n</code></pre>\n" }, { "answer_id": 23468, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "<p>Both answers were very helpful! Here's what I ended up with: </p>\n\n<pre><code>if( typeof( rpNameSpace ) == \"undefined\" ) rpNameSpace = {};\n\nrpNameSpace.foo = function() {\n this.length = 613;\n}\nrpNameSpace.foo.prototype.getLength = function() {\n return this.length * 2;\n}\n</code></pre>\n\n<p>Then, to use the resulting \"namespaced\" object:</p>\n\n<pre><code>var x = new rpNameSpace.foo()\n\ndisplay( x.getLength() );\n</code></pre>\n" }, { "answer_id": 15820688, "author": "Tengiz", "author_id": 523949, "author_profile": "https://Stackoverflow.com/users/523949", "pm_score": -1, "selected": false, "text": "<p>Another alternative may be the <a href=\"http://www.bobjs.com\" rel=\"nofollow\">bob.js</a> framework:</p>\n\n<pre><code>bob.ns.setNs('myApp.myFunctions', { \n say: function(msg) { \n console.log(msg); \n } \n}); \n\n//sub-namespace\nbob.ns.setNs('myApp.myFunctions.mySubFunctions', { \n hello: function(name) { \n myApp.myFunctions.say('Hello, ' + name); \n } \n}); \n\n//call:\nmyApp.myFunctions.mySubFunctions.hello('Bob'); \n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/22976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
I've got a JavaScript "object", built this way: ``` function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; } ... ``` I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. Thanks rp
Simple: ``` if(!MyNamespace) MyNamespace = {}; MyNamespace.foo = function() { this.length = 0; }; MyNamespace.foo.prototype.getLength = function() { return this.length; }; ```
23,027
<p>While setting up CruiseControl, I added a buildpublisher block to the publisher tasks:</p> <pre><code>&lt;buildpublisher&gt; &lt;sourceDir&gt;C:\MyBuild\&lt;/sourceDir&gt; &lt;publishDir&gt;C:\MyBuildPublished\&lt;/publishDir&gt; &lt;alwaysPublish&gt;false&lt;/alwaysPublish&gt; &lt;/buildpublisher&gt; </code></pre> <p>This works, but it copies the entire file contents of the build, I only want to copy the DLL's and .aspx pages, I don't need the source code to get published.</p> <p>Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?</p>
[ { "answer_id": 23060, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": true, "text": "<p>I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task.</p>\n" }, { "answer_id": 32667, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>The default build publisher in CC.NET does not provide a way to do this. You have a few options:</p>\n\n<ul>\n<li>Create your own build publisher with the desired functionality</li>\n<li>Create a custom NAnt/MSBuild task</li>\n<li>Use a scripting technology (RoboCopy, batch file, etc.) to create a script file and run an \"Executable\" task for CC.NET, or an \"exec\" task for NAnt/MSBuild</li>\n</ul>\n" }, { "answer_id": 32681, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 1, "selected": false, "text": "<p>I'm not sure with a web project, but for our winforms app, you can grab the TargetOutputs from the MSBuild task like so:</p>\n\n<pre><code>&lt;MSBuild Projects=\"@(VSProjects)\"\n Properties=\"Configuration=$(Configuration)\"&gt;\n &lt;Output TaskParameter=\"TargetOutputs\" ItemName=\"BuildTargetOutputs\"/&gt;\n&lt;/MSBuild&gt;\n</code></pre>\n\n<p>and then do a copy:</p>\n\n<pre><code>&lt;Copy SourceFiles=\"@(BuildTargetOutputs)\" \n DestinationFolder=\"bin\"\n SkipUnchangedFiles=\"true\" /&gt;\n</code></pre>\n\n<p>Not sure what the TargetOutputs are for a web project, but for winforms and class libraries, it's the .dll or .exe.</p>\n" }, { "answer_id": 7028931, "author": "riffrazor", "author_id": 565913, "author_profile": "https://Stackoverflow.com/users/565913", "pm_score": 0, "selected": false, "text": "<p>A CC.Net Powershell task can be used for this as well. </p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
While setting up CruiseControl, I added a buildpublisher block to the publisher tasks: ``` <buildpublisher> <sourceDir>C:\MyBuild\</sourceDir> <publishDir>C:\MyBuildPublished\</publishDir> <alwaysPublish>false</alwaysPublish> </buildpublisher> ``` This works, but it copies the entire file contents of the build, I only want to copy the DLL's and .aspx pages, I don't need the source code to get published. Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?
I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task.
23,064
<p>I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.)</p> <p><strong>Option A</strong></p> <pre><code>&lt;School&gt; &lt;Student Name="Jack" /&gt; &lt;Student Name="Jill" /&gt; &lt;Class Name="English 101" /&gt; &lt;Class Name="Math 101" /&gt; &lt;/School&gt; </code></pre> <p><strong>Option B</strong></p> <pre><code>&lt;School&gt; &lt;Students&gt; &lt;Student Name="Jack" /&gt; &lt;Student Name="Jill" /&gt; &lt;/Students&gt; &lt;Classes&gt; &lt;Class Name="English 101" /&gt; &lt;Class Name="Math 101" /&gt; &lt;/Classes&gt; &lt;/School&gt; </code></pre>
[ { "answer_id": 23067, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": true, "text": "<p>I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself.</p>\n\n<hr>\n\n<p>I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.</p>\n" }, { "answer_id": 23071, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "<p><strong>Definitely - Option B.</strong> </p>\n\n<p>I wouldn't mix students and classes in the XML just the same way that I wouldn't mix students and classes in the same table in a database. </p>\n" }, { "answer_id": 23079, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p><strong>Option B</strong>, absolutely. When there's a logical grouping of similar items, it should have a parent item. That way, my parser won't have to step through all 500 student records checking to see if there are class records mixed in.</p>\n" }, { "answer_id": 23080, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "<p>Another compelling reason to use option B is error checking. If the original file is modified outside an XML application, or if no XSD schema is applied, there could be the case where you have an uneven number of students and classes.</p>\n\n<p>At least if you have the students and classes grouped together, you will easily be able to tell if each record is complete, independently of any other record.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.) **Option A** ``` <School> <Student Name="Jack" /> <Student Name="Jill" /> <Class Name="English 101" /> <Class Name="Math 101" /> </School> ``` **Option B** ``` <School> <Students> <Student Name="Jack" /> <Student Name="Jill" /> </Students> <Classes> <Class Name="English 101" /> <Class Name="Math 101" /> </Classes> </School> ```
I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself. --- I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.
23,083
<p>In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put <code>this</code> in the window's user data area via <code>SetWindowLong(hwnd, GWL_USERDATA, this)</code>, which allows us to have an MFC-like callback or a tightly integrated <code>WndProc</code>, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?</p>
[ { "answer_id": 23101, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx\" rel=\"noreferrer\">SetWindowLongPtr</a> was created to replace <a href=\"http://msdn.microsoft.com/en-us/library/ms633591%28VS.85%29.aspx\" rel=\"noreferrer\">SetWindowLong</a> in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.</p>\n\n<pre><code>LONG_PTR SetWindowLongPtr( \n HWND hWnd,\n int nIndex,\n LONG_PTR dwNewLong\n);\n</code></pre>\n\n<p>Remember that the constants have changed too, so usage now looks like:</p>\n\n<pre><code>SetWindowLongPtr(hWnd, GWLP_USERDATA, this);\n</code></pre>\n\n<p>Also don't forget that now to retrieve the pointer, you must use <a href=\"http://msdn.microsoft.com/en-us/library/ms633585%28VS.85%29.aspx\" rel=\"noreferrer\">GetWindowLongPtr</a>:</p>\n\n<pre><code>LONG_PTR GetWindowLongPtr( \n HWND hWnd,\n int nIndex\n);\n</code></pre>\n\n<p>And usage would look like (again, with changed constants):</p>\n\n<pre><code>LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);\nMyObject* pMyObject = (MyObject*)lpUserData;\n</code></pre>\n" }, { "answer_id": 33342, "author": "Anders", "author_id": 3501, "author_profile": "https://Stackoverflow.com/users/3501", "pm_score": 4, "selected": false, "text": "<p>The other alternative is SetProp/RemoveProp (When you are subclassing a window that already uses GWLP_USERDATA)</p>\n\n<p>Another good alternative is ATL style thunking of the WNDPROC, for more info on that, see</p>\n\n<ul>\n<li><a href=\"http://www.ragestorm.net/blogs/?cat=20\" rel=\"noreferrer\">http://www.ragestorm.net/blogs/?cat=20</a></li>\n<li><a href=\"http://www.hackcraft.net/cpp/windowsThunk/\" rel=\"noreferrer\">http://www.hackcraft.net/cpp/windowsThunk/</a></li>\n</ul>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2354/" ]
In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put `this` in the window's user data area via `SetWindowLong(hwnd, GWL_USERDATA, this)`, which allows us to have an MFC-like callback or a tightly integrated `WndProc`, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?
[SetWindowLongPtr](http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx) was created to replace [SetWindowLong](http://msdn.microsoft.com/en-us/library/ms633591%28VS.85%29.aspx) in these instances. It's LONG\_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations. ``` LONG_PTR SetWindowLongPtr( HWND hWnd, int nIndex, LONG_PTR dwNewLong ); ``` Remember that the constants have changed too, so usage now looks like: ``` SetWindowLongPtr(hWnd, GWLP_USERDATA, this); ``` Also don't forget that now to retrieve the pointer, you must use [GetWindowLongPtr](http://msdn.microsoft.com/en-us/library/ms633585%28VS.85%29.aspx): ``` LONG_PTR GetWindowLongPtr( HWND hWnd, int nIndex ); ``` And usage would look like (again, with changed constants): ``` LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA); MyObject* pMyObject = (MyObject*)lpUserData; ```
23,094
<p>What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?</p>
[ { "answer_id": 23104, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>The best way to deal with it is to probably put a no-cache directive in your ASP.NET pages (or a master page if you're using one). I don't think there's a way to deal with this directly in your ASP.NET code (since the cache decision is happening on the client).</p>\n\n<p>As for MVC, don't know how you would accomplish that (assuming it's different from Web Forms-based ASP.NET); I haven't used it.</p>\n" }, { "answer_id": 23108, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": false, "text": "<p>As far as I know (or at least have read) is its best to try not to work in response to user events, but rather think \"in the page\"..</p>\n\n<p>Architect your application so it doesn't care if the back button is pushed.. It will just deal with it.. This may mean a little extra work from a development point of view, but overall will make the application a lot more robust..</p>\n\n<p>I.e if step 3 performs some data chages, then the user clicks back (to step 2) and clicks next again, then the application checks to see if the changes have been made.. Or ideally, it doesnt make any <em>hard</em> changes until the user clicks \"OK\" at the end.. This way, all the changes are stored and you can repopulate the form based on previously entered values on load, each and every time..</p>\n\n<p>I hope that makes sense :)</p>\n" }, { "answer_id": 24334, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": true, "text": "<p>You can try using the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache.aspx\" rel=\"noreferrer\">HttpResponse.Cache property</a> if that would help:</p>\n\n<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));\nResponse.Cache.SetCacheability(HttpCacheability.Public);\nResponse.Cache.SetValidUntilExpires(false);\nResponse.Cache.VaryByParams[\"Category\"] = true;\n\nif (Response.Cache.VaryByParams[\"Category\"])\n{\n //...\n}\n</code></pre>\n\n<p>Or could could block caching of the page altogether with <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cachecontrol.aspx\" rel=\"noreferrer\">HttpResponse.CacheControl</a>, but its been deprecated in favor of the Cache property above:</p>\n\n<pre><code>Response.CacheControl = \"No-Cache\";\n</code></pre>\n\n<p>Edit: OR you could really <a href=\"http://forums.asp.net/t/1013531.aspx\" rel=\"noreferrer\">go nuts</a> and do it all by hand:</p>\n\n<pre><code>Response.ClearHeaders();\nResponse.AppendHeader(\"Cache-Control\", \"no-cache\"); //HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"private\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"no-store\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"must-revalidate\"); // HTTP 1.1\nResponse.AppendHeader(\"Cache-Control\", \"max-stale=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Cache-Control\", \"post-check=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Cache-Control\", \"pre-check=0\"); // HTTP 1.1 \nResponse.AppendHeader(\"Pragma\", \"no-cache\"); // HTTP 1.1 \nResponse.AppendHeader(\"Keep-Alive\", \"timeout=3, max=993\"); // HTTP 1.1 \nResponse.AppendHeader(\"Expires\", \"Mon, 26 Jul 1997 05:00:00 GMT\"); // HTTP 1.1 \n</code></pre>\n" }, { "answer_id": 217096, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.13\" rel=\"nofollow noreferrer\">RFC 2616 §13.13</a> says that <strong>History and Cache are different things</strong>. There should be absolutely no way for cache to affect Back button.</p>\n\n<p>If any combination of HTTP headers affects Back button, it's a bug in the browser …with one exception.</p>\n\n<p>In HTTP<b>S</b> browsers interpret <code>Cache-control: must-revalidate</code> as request to refresh pages when Back button is used (Mozilla calls it \"silly bank mode\"). This isn't supported in plain HTTP.</p>\n" }, { "answer_id": 28466691, "author": "Steven de Salas", "author_id": 448568, "author_profile": "https://Stackoverflow.com/users/448568", "pm_score": 0, "selected": false, "text": "<p>The following code worked for me in IE9+, FF21 and Latest Chrome:</p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache | HttpCacheability.Private);\nResponse.Cache.AppendCacheExtension(\"must-revalidate\");\nResponse.Cache.AppendCacheExtension(\"max-age=0\");\nResponse.Cache.SetNoStore();\n</code></pre>\n\n<p>You can place this in <code>Page_Load()</code> event handler in the MasterPage so that every page in your app requires a round-trip to the server when pressing the back button.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?
You can try using the [HttpResponse.Cache property](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache.aspx) if that would help: ``` Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(false); Response.Cache.VaryByParams["Category"] = true; if (Response.Cache.VaryByParams["Category"]) { //... } ``` Or could could block caching of the page altogether with [HttpResponse.CacheControl](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cachecontrol.aspx), but its been deprecated in favor of the Cache property above: ``` Response.CacheControl = "No-Cache"; ``` Edit: OR you could really [go nuts](http://forums.asp.net/t/1013531.aspx) and do it all by hand: ``` Response.ClearHeaders(); Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1 ```
23,124
<p>As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?</p>
[ { "answer_id": 23131, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 2, "selected": false, "text": "<p>You could always run a server-side script that keeps running for a period of time. \nFor example:</p>\n\n<pre><code>&lt;?php\n sleep(10); //sleep for 10 seconds.\n print \"This script has finished.\";\n&gt;\n</code></pre>\n" }, { "answer_id": 23199, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://developer.yahoo.com/yui/connection/\" rel=\"nofollow noreferrer\">YUI Connection Manager</a> allows you to introduce slowdown in your Javascript to test AJAX against latency.</p>\n" }, { "answer_id": 23227, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<p>First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side?</p>\n\n<p>If you want to have the server-side code take a long time and you are using .NET, place this line in the method you call server-side:</p>\n\n<pre><code>System.Threading.Thread.Sleep(timeoutMilliseconds);\n</code></pre>\n\n<p>As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272/" ]
As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?
First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side? If you want to have the server-side code take a long time and you are using .NET, place this line in the method you call server-side: ``` System.Threading.Thread.Sleep(timeoutMilliseconds); ``` As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good.
23,169
<p>When using Groovy <code>MarkupBuilder</code>, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag <em>"text"</em> to do the output. Is there a better way to write this code?</p> <pre><code>li { text("${type.getAlias()} blah blah ") function1(type.getXYZ()) if (type instanceof Class1) { text(" implements ") ft.getList().each { if (it == '') return text(it) if (!function2(type, it)) text(", ") } } } </code></pre>
[ { "answer_id": 23734, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Include a method:</p>\n\n<pre><code>void text(n){\n builder.yield n\n}\n</code></pre>\n\n<p>Most likely you (I) copied this code from somewhere that had a text method, but you didn't also copy the text method. Since MarkupBuilder accepts any name for the name of a tag and browsers ignore unknown markup, it just happened to work.</p>\n" }, { "answer_id": 81815, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "<p>Actually, the recommended way now is to use <code>mkp.yield</code>, e.g.,</p>\n\n<pre><code>src.p {\n mkp.yield 'Some element that has a '\n strong 'child element'\n mkp.yield ' which seems pretty basic.'\n}\n</code></pre>\n\n<p>to produce</p>\n\n<pre><code>&lt;p&gt;Some element that has a &lt;strong&gt;child element&lt;/strong&gt; which seems pretty basic.&lt;/p&gt;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using Groovy `MarkupBuilder`, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag *"text"* to do the output. Is there a better way to write this code? ``` li { text("${type.getAlias()} blah blah ") function1(type.getXYZ()) if (type instanceof Class1) { text(" implements ") ft.getList().each { if (it == '') return text(it) if (!function2(type, it)) text(", ") } } } ```
Actually, the recommended way now is to use `mkp.yield`, e.g., ``` src.p { mkp.yield 'Some element that has a ' strong 'child element' mkp.yield ' which seems pretty basic.' } ``` to produce ``` <p>Some element that has a <strong>child element</strong> which seems pretty basic.</p> ```
23,175
<p>This is mostly geared toward desktop application developers. <br />How do I design a caching block which plays nicely with the GC? <br />How do I tell the GC that I have just done a cache sweep and it is time to do a GC? <br />How do I get an accurate measure of when it is time to do a cache sweep?</p> <p>Are there any prebuilt caching schemes which I could borrow some ideas from?</p>
[ { "answer_id": 23734, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Include a method:</p>\n\n<pre><code>void text(n){\n builder.yield n\n}\n</code></pre>\n\n<p>Most likely you (I) copied this code from somewhere that had a text method, but you didn't also copy the text method. Since MarkupBuilder accepts any name for the name of a tag and browsers ignore unknown markup, it just happened to work.</p>\n" }, { "answer_id": 81815, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "<p>Actually, the recommended way now is to use <code>mkp.yield</code>, e.g.,</p>\n\n<pre><code>src.p {\n mkp.yield 'Some element that has a '\n strong 'child element'\n mkp.yield ' which seems pretty basic.'\n}\n</code></pre>\n\n<p>to produce</p>\n\n<pre><code>&lt;p&gt;Some element that has a &lt;strong&gt;child element&lt;/strong&gt; which seems pretty basic.&lt;/p&gt;\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
This is mostly geared toward desktop application developers. How do I design a caching block which plays nicely with the GC? How do I tell the GC that I have just done a cache sweep and it is time to do a GC? How do I get an accurate measure of when it is time to do a cache sweep? Are there any prebuilt caching schemes which I could borrow some ideas from?
Actually, the recommended way now is to use `mkp.yield`, e.g., ``` src.p { mkp.yield 'Some element that has a ' strong 'child element' mkp.yield ' which seems pretty basic.' } ``` to produce ``` <p>Some element that has a <strong>child element</strong> which seems pretty basic.</p> ```
23,178
<p>Is there a .NET variable that returns the "All Users" directory?</p>
[ { "answer_id": 23194, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 4, "selected": true, "text": "<p>You'll want to use the <code>system.environment</code> variables.<br>\nMost of the predefined ones are <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx\" rel=\"nofollow noreferrer\">shown here</a>. </p>\n\n<p>For the \"<strong>All Users</strong>\" you would use:</p>\n\n<pre><code>System.Environment.GetEnvironmentVariable(\"ALLUSERSPROFILE\")\n</code></pre>\n\n<p>I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other <a href=\"http://msdn.microsoft.com/en-us/library/ms933062.aspx\" rel=\"nofollow noreferrer\">environment variables</a> \nI linked to previously don't seem to work with that function call.</p>\n" }, { "answer_id": 23202, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 1, "selected": false, "text": "<p>Or, </p>\n\n<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n</code></pre>\n\n<p>You can then pass this result to System.IO.Directory.GetParent() to get the root \"All Users\" folder.</p>\n" }, { "answer_id": 23224, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>Is this any use?</p>\n\n<p>Oops:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb774096(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb774096(VS.85).aspx</a></p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
Is there a .NET variable that returns the "All Users" directory?
You'll want to use the `system.environment` variables. Most of the predefined ones are [shown here](http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx). For the "**All Users**" you would use: ``` System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE") ``` I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other [environment variables](http://msdn.microsoft.com/en-us/library/ms933062.aspx) I linked to previously don't seem to work with that function call.
23,190
<p>I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are &quot;cared about.&quot;</p> <p>Example: Consider the following example...</p> <pre> Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. </pre> <p>I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful.</p> <h3>Update:</h3> <p>Just got home. Here is some info to answer your questions:</p> <ol> <li>Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out.</li> <li>@jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).</li> <li>I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a &quot;driver&quot; function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array.</li> <li>The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).</li> </ol> <p>Thanks everyone for your imput.</p>
[ { "answer_id": 23196, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Actually, by colllapsing the colums you already summed them, so the dimension doesn't matter at all for your example. Did I miss something or did you?</p>\n" }, { "answer_id": 23210, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>I think the best thing to do here would be one/both of two things:</p>\n\n<ol>\n<li>Rethink the design, if its too complex, find a less-complex way.</li>\n<li>Stop trying to visualise it.. :P Just store the dimensions in question that you need to sum, then do them one at a time. Once you have the base code, then look at improving the efficiency of your algorithm.</li>\n</ol>\n" }, { "answer_id": 23225, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>I beg to differ, there is ALWAYS another way..</p>\n\n<p>And if you really <em>cannot</em> refactor, then you need to break the problem down into smaller parts.. Like I said, establish which dimensions you need to sum, then hit them one at a time..</p>\n\n<p>Also, stop changing the edits, they are correcting your spelling errors, they are trying to help you ;)</p>\n" }, { "answer_id": 23226, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 0, "selected": false, "text": "<p>When you say you don't know how many dimensions there are, how exactly are you defining the data structures?</p>\n\n<p>At some point, someone needs to create this array, and to do that, they need to know the dimensions of the array. You can force the creator to pass in this data along with the array.</p>\n\n<p>Unless the question is to define such a data structure...</p>\n" }, { "answer_id": 23275, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 0, "selected": false, "text": "<p>You're doing this in c/c++... so you have an array of array of array... you don't have to visualize 20 dimensions since that isn't how the data is laid out in memory, for a 2 dimensional:</p>\n\n<pre><code>[1] --&gt; [1,2,3,4,5,6,...]\n[2] --&gt; [1,2,3,4,5,6,...]\n[3] --&gt; [1,2,3,4,5,6,...]\n[4] --&gt; [1,2,3,4,5,6,...]\n[5] --&gt; [1,2,3,4,5,6,...]\n . .\n . .\n . .\n</code></pre>\n\n<p>so, why can't you iterate across the first one summing it's contents? If you are trying to find the size, then <code>sizeof(array)/sizeof(int)</code> is a risky approach. You must know the dimension to be able to process this data, and set the memory up, so you know the depth of recursion to sum. Here is some pseudo code of what it seems you should do, </p>\n\n<pre><code>sum( n_matrix, depth )\n running_total = 0\n if depth = 0 then\n foreach element in the array\n running_total += elm\n else \n foreach element in the array\n running_total += sum( elm , depth-1 )\n return running_total\n</code></pre>\n" }, { "answer_id": 23282, "author": "Marc Reside", "author_id": 1429, "author_profile": "https://Stackoverflow.com/users/1429", "pm_score": 2, "selected": false, "text": "<p>@Jeff</p>\n\n<p>I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question.</p>\n\n<p>@Ed</p>\n\n<p>Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well?</p>\n\n<p>EDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ...</p>\n\n<p>Let's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, <code>array_care[4][4][4]</code> for 1,2, and 6. The <code>array_care[4][4][4]</code> will hold the end result.</p>\n\n<p>Next, we want to iterate in a very specific way. We have the array <code>input[4][4][4][4][4][4][4][4]</code> to parse through, and we care about dimensions 1, 2, and 6.</p>\n\n<p>We need to define some temporary indexes:</p>\n\n<pre><code>int dim[8] = {0,0,0,0,0,0,0,0};\n</code></pre>\n\n<p>We also need to store the order in which we want to increase the indexes:</p>\n\n<pre><code>int increase_index_order[8] = {7,5,4,3,0,6,2,1};\nint i = 0;\n</code></pre>\n\n<p>This order is important for doing what you requested.</p>\n\n<p>Define a termination flag:</p>\n\n<pre><code>bool terminate=false;\n</code></pre>\n\n<p>Now we can create our loop:</p>\n\n<pre><code>while (terminate)\n{\narray_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]];\n\nwhile ((dim[increase_index_order[i]] = 3) &amp;&amp; (i &lt; 8))\n{\ndim[increase_index_order[i]]=0;\ni++;\n}\n\nif (i &lt; 8) {\ndim[increase_index_order[i]]++; i=0;\n} else {\nterminate=true;\n}\n}\n</code></pre>\n\n<p>That should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :(</p>\n" }, { "answer_id": 23307, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 0, "selected": false, "text": "<pre><code>x = number_of_dimensions;\nwhile (x &gt; 1)\n{\n switch (x)\n {\n case 20:\n reduce20DimensionArray();\n x--;\n break;\n case 19:\n .....\n }\n}\n</code></pre>\n\n<p>(Sorry, couldn't resist.)</p>\n" }, { "answer_id": 23371, "author": "dmo", "author_id": 1807, "author_profile": "https://Stackoverflow.com/users/1807", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you want to sum all values in the cross section defined at each \"bin\" along 1 dimension. I suggest making a 1D array for your destination, then looping through each element in your array adding the value to the destination with the index of the dimension of interest.</p>\n\n<p>If you are using arbitrary number of dimensions, you must have a way of addressing elements (I would be curious how you are implementing this). Your implementation of this will affect how you set the destination index. But an obvious way would be with if statements checked in the iteration loops.</p>\n" }, { "answer_id": 23442, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "<p>This kind of thing is much easier if you use STL containers, or maybe <a href=\"http://www.boost.org/libs/multi_array/doc/index.html\" rel=\"nofollow noreferrer\">Boost.MultiArray</a>. But if you must use an array:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;boost/foreach.hpp&gt;\n#include &lt;vector&gt;\n\nint sum(int x) {\n return x;\n}\n\ntemplate &lt;class T, unsigned N&gt;\nint sum(const T (&amp;x)[N]) {\n int r = 0;\n for(int i = 0; i &lt; N; ++i) {\n r += sum(x[i]);\n }\n return r;\n}\n\ntemplate &lt;class T, unsigned N&gt;\nstd::vector&lt;int&gt; reduce(const T (&amp;x)[N]) {\n std::vector&lt;int&gt; result;\n for(int i = 0; i &lt; N; ++i) {\n result.push_back(sum(x[i]));\n }\n return result;\n}\n\nint main() {\n int x[][2][2] = {\n { { 1, 2 }, { 3, 4 } },\n { { 5, 6 }, { 7, 8 } }\n };\n\n BOOST_FOREACH(int v, reduce(x)) {\n std::cout&lt;&lt;v&lt;&lt;\"\\n\";\n }\n}\n</code></pre>\n" }, { "answer_id": 25002, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 3, "selected": true, "text": "<p>This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid.</p>\n\n<p>I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python,</p>\n\n<pre><code>\ndef iter_arr(array):\n sum = 0\n for i in array:\n if type(i) == type(list()):\n sum = sum + iter_arr(i)\n else:\n sum = sum + i\n return sum \n</code></pre>\n\n<ol>\n<li>Iterate over each element in array</li>\n<li>If element is another array, call the function again</li>\n<li>If element is not array, add it to the sum</li>\n<li>Return sum</li>\n</ol>\n\n<p>You would then apply this to each element in the 'cared about' dimension.</p>\n\n<p>This is easier in python due to duck-typing though ...</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... ``` Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. ``` I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. ### Update: Just got home. Here is some info to answer your questions: 1. Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. 2. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). 3. I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. 4. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput.
This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid. I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python, ``` def iter_arr(array): sum = 0 for i in array: if type(i) == type(list()): sum = sum + iter_arr(i) else: sum = sum + i return sum ``` 1. Iterate over each element in array 2. If element is another array, call the function again 3. If element is not array, add it to the sum 4. Return sum You would then apply this to each element in the 'cared about' dimension. This is easier in python due to duck-typing though ...
23,197
<p>I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.</p> <p>Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative. </p> <p>Anyway, the device file path is of the form: </p> <pre> 1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". </pre> <p>And I'm trying to open it using code, like:</p> <pre><code>// First, open it with minimum permissions, this device may not be ours. // we'll re-open it later in read/write hid_device_ref = CreateFile( device_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); </code></pre> <p>I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.</p>
[ { "answer_id": 23219, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>This is what I use to read from a Magtek card reader:</p>\n\n<pre><code>//Open file on the device\ndeviceHandle = \n CreateFile (deviceDetail-&gt;DevicePath, \n GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, \n NULL, OPEN_EXISTING, 0, NULL);\n</code></pre>\n\n<p>Try those options and see if you can at least read from the device.</p>\n\n<p>I understand your pain here... I found the USB HID documentation to be basically wrong in several places.</p>\n\n<p>[Edit] There's not much out there on this problem. Here's a <a href=\"http://www.codeproject.com/KB/cs/USB_HID.aspx?fid=398968&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2657157&amp;fr=26\" rel=\"nofollow noreferrer\">codeproject link</a> that lightly touches on the subject in a thread at the bottom. Sounds like maybe if it's a keyboard or mouse windows grabs it exclusively.</p>\n" }, { "answer_id": 23246, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 0, "selected": false, "text": "<p>Cool - I'll try those options, as they're probably better defaults given my intentions. Unfortunately, I know my device is there and I'll eventually need read/write access later on (once I inspect the descriptors and have verifed it is infact my device).</p>\n<p>Which means that my real goal IS to know what's using it, so I can inform the customer/user: &quot;Hey man, 'iexplore.exe' is currently using your SuperWidget device. You'll have to close that down in order to use SuperWidget application.&quot; (if not at the application-level, then at least at the phone support level.)</p>\n<p>I forgot to mention that the windows error reported by GetLastError() is:</p>\n<blockquote>\n<p>0x20. The process cannot access the file because it is being used by another process.</p>\n</blockquote>\n<p>(So your sharing alternatives will probably get the file open, assuming no FILE_SHARE_NONE on behalf of the other process).</p>\n<p>[edit]</p>\n<blockquote>\n<p>Yeah, it's painful alright. I have seen mice and keyboards get locked by whatever Windows uses to read from them. I've also seen a lot of people have trouble inside a VM like Paralells on OS X, where the HID class driver has the device open exclusively preventing the VM from using standard USB requests.</p>\n<p>I've seen some code that recreates what <em>ProcessMonitor</em> does. Maybe SysInternals is just electing to ignore device handles, but the same method (or a slight variation) can be employed here to determine the PID.</p>\n<p><strong>Mike</strong></p>\n</blockquote>\n" }, { "answer_id": 45884, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 2, "selected": false, "text": "<p>Have you tried the tool called <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx\" rel=\"nofollow noreferrer\">handle</a> from sysinternals?</p>\n\n<p>Anyway, neither windows does this (display the name of the application that locked the device): when you try to eject an USB device, Windows just says that the device is currently in use and cannot be remove right now.</p>\n" }, { "answer_id": 735453, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 1, "selected": false, "text": "<p>There's a trick you can do where you open the device handle requesting neither read nor write permission and interact with it using only feature reports. <a href=\"http://www.lvr.com/hidpage.htm\" rel=\"nofollow noreferrer\">Jan Axelson</a> mentions this trick in her books about USB HID devices. I believe this gets around the problem with the exclusive lock, which you would encounter (for example) when trying to open a handle to a device that Windows considers a system keyboard or mouse. Even though you can't read or write the handle, you can still send a feature report to the device using <a href=\"http://msdn.microsoft.com/en-us/library/ms790955.aspx\" rel=\"nofollow noreferrer\"><code>HidD_SetFeature</code></a> and read a report from the device using <a href=\"http://msdn.microsoft.com/en-us/library/ms790913.aspx\" rel=\"nofollow noreferrer\"><code>HidD_GetFeature</code></a>. I don't know offhand of a way to read input reports or send output reports under these circumstances, and perhaps it's impossible to do so, but you might not need either of those, especially if the device is \"your\" device in the sense that you control the firmware. Strictly speaking this does nothing to answer your question as asked, but it seemed potentially relevant so I figured I'd throw it out there.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2146/" ]
I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver. Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative. Anyway, the device file path is of the form: ``` 1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". 3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}". ``` And I'm trying to open it using code, like: ``` // First, open it with minimum permissions, this device may not be ours. // we'll re-open it later in read/write hid_device_ref = CreateFile( device_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); ``` I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.
Have you tried the tool called [handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx) from sysinternals? Anyway, neither windows does this (display the name of the application that locked the device): when you try to eject an USB device, Windows just says that the device is currently in use and cannot be remove right now.
23,209
<p>I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:</p> <pre><code>cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl -DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio 9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c </code></pre> <p>The code compiles cleanly. The link command is:</p> <pre><code>link -debug -nologo -machine:IX86 -verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib msvcrt.lib oldnames.lib kernel32.lib winmm.lib [snip large list of dependencies] D:\src\lib\app_main.obj -out:mymain.exe </code></pre> <p>The errors that I'm getting are:</p> <pre><code>app_main.obj : error LNK2019: unresolved external symbol "_\_declspec(dllimport) public: void __thiscall std::locale::facet::_Register(void)" (__imp_?_Register@facet@locale@std@@QAEXXZ) referenced in function "class std::ctype&lt;char&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;char&gt; (class std::locale const &amp;)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype&lt;char&gt;::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype&lt;char&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;char&gt; (class std::locale const &amp;)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype&lt;unsigned short&gt;::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype&lt;unsigned short&gt; const &amp; __cdecl std::use_facet&lt;class std::ctype&lt;unsigned short&gt; &gt;(class std::locale const &amp;)" (??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z) mymain.exe : fatal error LNK1120: 3 unresolved externals </code></pre> <p>Notice that these errors are coming from the legacy code, not my code - app_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?</p>
[ { "answer_id": 23212, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>These are standard library references. Make sure that all libraries (including the standard library) are using the <em>same</em> linkage. E.g. you can't link statically while linking the standard lib dynamically. The same goes for the threading model used. Take special care that you and the 3rd party library use the same linkage options.</p>\n\n<p>This can be a real pain in the *ss.</p>\n" }, { "answer_id": 26180, "author": "Matt McMinn", "author_id": 1322, "author_profile": "https://Stackoverflow.com/users/1322", "pm_score": -1, "selected": true, "text": "<p>After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem. </p>\n\n<p>So to reiterate, downgrading to VS 2003 fixed it.</p>\n" }, { "answer_id": 26217, "author": "jan", "author_id": 1163, "author_profile": "https://Stackoverflow.com/users/1163", "pm_score": 2, "selected": false, "text": "<p>Check this on <a href=\"http://msdn.microsoft.com/en-us/library/2kzt1wy3(VS.80).aspx\" rel=\"nofollow noreferrer\" title=\"MSDN\">MSDN</a>:</p>\n\n<ul>\n<li>/MD Causes your application to use the multithread- and DLL-specific version of the run-time library.</li>\n<li>/MT Causes your application to use the multithread, static version of the run-time library.</li>\n</ul>\n\n<p>Note: \"... so that the linker will use LIBCMT.lib to resolve external symbols\"</p>\n\n<p>So you'll need a different set of libraries.</p>\n\n<p>How I went about finding out which libraries to link:</p>\n\n<ol>\n<li>Find a configuration that <em>does</em> link, and add /verbose option.</li>\n<li>Pipe the output to a text file.</li>\n<li>Try the configuration that <em>doesn't</em> link.</li>\n<li>Look in the verbose output from step 2 for the symbols that are unresolved (\"_declspec(dllimport) public: void thiscall std::locale::facet::Register(void)\" in your case) and find the used libraries.</li>\n<li>Add those libraries to the list of libraries you're linking to.</li>\n</ol>\n\n<p>Old skool but it <a href=\"https://stackoverflow.com/questions/9570/what-libraries-do-i-need-to-link-my-mixed-mode-application-to\">worked</a> for me.</p>\n\n<p>Jan</p>\n" }, { "answer_id": 44886, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 2, "selected": false, "text": "<p>If you still wish to get the project to compile using VS2008 (or in the future) I can suggest using a binary editor to view the object file in question <em>mainapp.obj</em>.</p>\n\n<p>Here is an example from a small project of mine.</p>\n\n<p>The zdbException.obj contains the following excerpt</p>\n\n<pre><code>DEFAULTLIB:\"libc\npmtd\" /DEFAULTLI\nB:\"uuid.lib\" /DE\nFAULTLIB:\"uuid.l\nib\" /include:?id\n@?$num_put@DV?$o\nstreambuf_iterat\nor@DU?$char_trai\nts@D@std@@@std@@\n@std@@2V0locale@\n2@A /include:?id\n@?$numpunct@D@st\nd@@2V0locale@2@A\n /DEFAULTLIB:\"LI\nBCMTD\" /DEFAULTL\nIB:\"OLDNAMES\" /E\nDITANDCONTINUE \n</code></pre>\n\n<p>Note the entry <strong>/DEFAULTLIB:\"LIBCMTD\"</strong>. This indicates the object file was compiled with the static c run-time multi-threaded debug.</p>\n\n<p>There is also the possibility that the functions referenced in the obj are deprecated in the standard run-time lib shipped with VS2008.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322/" ]
I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is: ``` cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl -DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio 9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c ``` The code compiles cleanly. The link command is: ``` link -debug -nologo -machine:IX86 -verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib msvcrt.lib oldnames.lib kernel32.lib winmm.lib [snip large list of dependencies] D:\src\lib\app_main.obj -out:mymain.exe ``` The errors that I'm getting are: ``` app_main.obj : error LNK2019: unresolved external symbol "_\_declspec(dllimport) public: void __thiscall std::locale::facet::_Register(void)" (__imp_?_Register@facet@locale@std@@QAEXXZ) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> (class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<char>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<char> const & __cdecl std::use_facet<class std::ctype<char> (class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z) app_main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static unsigned int __cdecl std::ctype<unsigned short>::_Getcat(class std::locale::facet const * *)" (__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z) referenced in function "class std::ctype<unsigned short> const & __cdecl std::use_facet<class std::ctype<unsigned short> >(class std::locale const &)" (??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z) mymain.exe : fatal error LNK1120: 3 unresolved externals ``` Notice that these errors are coming from the legacy code, not my code - app\_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?
After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem. So to reiterate, downgrading to VS 2003 fixed it.
23,217
<p>I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the <code>javascript:</code> prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:</p> <pre><code>onchange="javascript: myFunction(this)" </code></pre> <p>and</p> <pre><code>onchange="myFunction(this)" </code></pre> <p>?</p>
[ { "answer_id": 23222, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 5, "selected": true, "text": "<p>Probably nothing in your example. My understanding is that <code>javascript:</code> is for anchor tags (in place of an actual <code>href</code>). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank <code>href</code> coupled with an <code>onclick</code> will do).</p>\n\n<p>For example:</p>\n\n<pre><code>&lt;a href=\"javascript:someFunction();\"&gt;Blah&lt;/a&gt;\n</code></pre>\n\n<p>Rather than:</p>\n\n<pre><code>&lt;a href=\"\" onclick=\"someFunction();\"&gt;Blah&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 23237, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": false, "text": "<p>I am no authority in JavaScript, and perhaps more of a dunce than the asker, but AFAIK, the difference is that the <code>javascript:</code> prefix is preferred/required in URI-contexts, where the argument may be as well a traditional HTTP URL as a JavaScript trigger.</p>\n\n<p>So, my intuitive answer would be that, since <code>onChange</code> expects JavaScript, the <code>javascript:</code> prefix is redundant (if not downright erroneous). You can, however, write <code>javascript:myFunction(this)</code> in your address bar, and that function is run. Without the <code>javascript:</code>, your browser would try to interpret <code>myFunction(this)</code> as a URL and tries to fetch the DNS info, browse to that server, etc...</p>\n" }, { "answer_id": 23239, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 0, "selected": false, "text": "<p>I don't know if the <code>javascript:</code> prefix means anything within the <code>onevent</code> attributes but I know they are annoying in anchor tags when trying to open the link in a new tab. The <code>href</code> should be used as a fall back and <strong>never</strong> to attach javascript to links.</p>\n" }, { "answer_id": 23242, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>It should only be used in the href tag.</p>\n</blockquote>\n\n<p>That's ridiculous.</p>\n\n<p>The accepted way is this:</p>\n\n<pre><code>&lt;a href=\"/non-js-version/\" onclick=\"someFunction(); return false\"&gt;Blah&lt;/a&gt;\n</code></pre>\n\n<p>But to answer the OP, there is generally no reason to use <code>javascript:</code> anymore. In fact, you should attach the javascript event from your script, and not inline in the markup. But, that's a purist thing I think :-D</p>\n" }, { "answer_id": 23244, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "<p>It should not be used in event handlers (though most browsers work defensively, and will not punish you). I would also argue that it should not be used in the href attribute of an anchor. If a browser supports javascript, it will use the properly defined event handler. If a browser does not, a javascript: link will appear broken. IMO, it is better to point them to a page explaining that they need to enable javascript to use that functionality, or better yet a non-javascript required version of the functionality. So, something like:</p>\n\n<pre><code>&lt;a href=\"non-ajax.html\" onclick=\"niftyAjax(); return false;\"&gt;Ajax me&lt;/a&gt;\n</code></pre>\n\n<p>Edit: Thought of a good reason to use javascript:. Bookmarklets. For instance, this one sends you to google reader to view the rss feeds for a page:</p>\n\n<pre><code>var b=document.body;\nif(b&amp;&amp;!document.xmlVersion){\n void(z=document.createElement('script'));\n void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');\n void(b.appendChild(z));\n}else{\n location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)\n}\n</code></pre>\n\n<p>To have a user easily add this Bookmarklet, you would format it like so:</p>\n\n<pre><code>&lt;a href=\"javascript:var%20b=document.body;if(b&amp;&amp;!document.xmlVersion){void(z=document.createElement('script'));void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');void(b.appendChild(z));}else{location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)}\"&gt;Drag this to your bookmarks, or right click and bookmark it!&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 23342, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<p>javascript: in JS code (like in an onclick attribute) is just a label for use with continue/goto label statements that may or may not be supported by the browser (probably not anywhere). It could be zipzambam: instead. Even if the label can't be used, browsers still accept it so it doesn't cause an error.</p>\n\n<p>This means that if someone's throwing a useless label in an onclick attribute, they probably don't know what they're doing and are just copying and pasting or doing it out of habit from doing the below.</p>\n\n<p>javascript: in the href attribute signifies a Javascript URI.</p>\n\n<p><a href=\"http://shadow2531.com/js/jsuri.html\" rel=\"nofollow noreferrer\">Example</a>:</p>\n\n<pre><code>javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B\n</code></pre>\n" }, { "answer_id": 23365, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/23217/whats-the-purpose-if-any-of-javascript-in-event-handler-tags#23242\">@mercutio</a></p>\n\n<blockquote>\n <blockquote>\n <p>That's ridiculous.</p>\n </blockquote>\n</blockquote>\n\n<p>No, it's not ridiculous, javascript: is a pseudo protocol that can indeed only be used as the subject of a link, so he's quite right. Your suggestion is indeed better, but the best way of all is to use unobtrusive javascript techniques to iterate over HTML elements and add behaviour programmatically, as used in libraries like jQuery.</p>\n" }, { "answer_id": 23466, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>Basically, is there any appreciable difference between: <code>onchange=\"javascript: myFunction(this)\"</code> and <code>onchange=\"myFunction(this)\"</code> ?</p>\n </blockquote>\n</blockquote>\n\n<p>Assuming you meant <code>href=\"javascript: myFunction(this)\"</code>, yes there is, especially when loading content using the javascript. Using the javascript: pseudo protocol makes the content inaccessible to some humans and all search engines, whereas using a real href and then changing the behaviour of the link using javascript makes the content accessible if javascript is turned off or not available in the particular client.</p>\n" }, { "answer_id": 32193, "author": "Russell Leggett", "author_id": 2828, "author_profile": "https://Stackoverflow.com/users/2828", "pm_score": 2, "selected": false, "text": "<p>The origins of <code>javascript:</code> in an event handler is actually just an IE specific thing so that you can specify the language in addition to the handler. This is because <code>vbscript</code> is also a supported client side scripting language in IE. Here's an example of <a href=\"http://www.visualbasicscript.com/m_50201/tm.htm\" rel=\"nofollow noreferrer\">\"vbscript:\"</a>.</p>\n\n<p>In other browsers (as has been said by Shadow2531) <code>javascript:</code> is just a label and is basically ignored.</p>\n\n<p><code>href=\"javascript:...\"</code> can be used in links to execute javascript code as DannySmurf points out.</p>\n" }, { "answer_id": 43001, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>Flubba:</p>\n\n<p>Use of <code>javascript:</code> in <code>HREF</code> breaks \"Open in New Window\" and \"Open in New Tab\" in a Firefox and other browsers.</p>\n\n<p>It isn't \"wrong\", but if you want to make your site hard to navigate...</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1680/" ]
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the `javascript:` prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: ``` onchange="javascript: myFunction(this)" ``` and ``` onchange="myFunction(this)" ``` ?
Probably nothing in your example. My understanding is that `javascript:` is for anchor tags (in place of an actual `href`). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank `href` coupled with an `onclick` will do). For example: ``` <a href="javascript:someFunction();">Blah</a> ``` Rather than: ``` <a href="" onclick="someFunction();">Blah</a> ```
23,228
<p>Compare</p> <pre><code>String.Format("Hello {0}", "World"); </code></pre> <p>with</p> <pre><code>"Hello {0}".Format("World"); </code></pre> <p>Why did the .Net designers choose a static method over an instance method? What do you think?</p>
[ { "answer_id": 23234, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": false, "text": "<p>I think it's because it's a creator method (not sure if there's a better name). All it does is take what you give it and return a single string object. It doesn't operate on an existing object. If it was non-static, you would need a string to begin with.</p>\n" }, { "answer_id": 23236, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "<p>Because the Format method has nothing to do with a string's current value. The value of the string isn't used. It takes a string and returns one.</p>\n" }, { "answer_id": 23240, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>I see nothing wrong with it being static..</p>\n\n<p>The semantics of the static method seem to make a lot more sense to me. Perhaps it is because it is a primitive. Where primitives are used to often, you want to make the utility code for working with them as light as possible.. Also, I think the semantics are a lot better with <em>String.Format</em> over <em>\"MyString BLAH BLAH {0}\".Format</em> ...</p>\n" }, { "answer_id": 23243, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>Instance methods are good when you have an object that maintains some state; the process of formatting a string does not affect the string you are operating on (read: does not modify its state), it creates a new string.</p>\n\n<p>With extension methods, you can now have your cake and eat it too (i.e. you can use the latter syntax if it helps you sleep better at night).</p>\n" }, { "answer_id": 23248, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 1, "selected": false, "text": "<p>I haven't tried it yet but you could make an extension method for what you want. I wouldn't do it, but I think it would work.</p>\n\n<p>Also I find <code>String.Format()</code> more in line with other patterned static methods like <code>Int32.Parse()</code>, <code>long.TryParse()</code>, etc.</p>\n\n<p>You cloud also just use a <code>StringBuilder</code> if you want a non static format.\n<a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.appendformat&#40;VS.85&#41;.aspx\" rel=\"nofollow noreferrer\"><code>StringBuilder.AppendFormat()</code></a></p>\n" }, { "answer_id": 23253, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": -1, "selected": false, "text": "<p><code>String.Format</code> takes at least one String and returns a different String. It doesn't need to modify the format string in order to return another string, so it makes little sense to do that (ignoring your formatting of it). On the other hand, it wouldn't be that much of a stretch to make <code>String.Format</code> be a member function, except I don't think C# allows for const member functions like C++ does. [Please correct me and this post if it does.]</p>\n" }, { "answer_id": 23255, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>I think it looks better in general to use String.Format, but I could see a point in wanting to have a non-static function for when you already have a string stored in a variable that you want to \"format\". </p>\n\n<p>As an aside, all functions of the string class don't act on the string, but return a new string object, because strings are immutable.</p>\n" }, { "answer_id": 23256, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>Because the Format method has nothing to do with a string's current value.</p>\n</blockquote>\n\n<p>That's true for <em>all</em> string methods because .NET strings are immutable.</p>\n\n<blockquote>\n <p>If it was non-static, you would need a string to begin with.</p>\n</blockquote>\n\n<p>It does: the format string.</p>\n\n<p>I believe this is just another example of the many design flaws in the .NET platform (and I don't mean this as a flame; I still find the .NET framework superior to most other frameworks).</p>\n" }, { "answer_id": 23348, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p><strong>String.Format has to be a static method because strings are immutable.</strong> Making it an instance method would imply you could use it to \"format\" or modify the value of an existing string. This you can't do, and making it an instance method that returned a new string would make no sense. Hence, it's a static method.</p>\n" }, { "answer_id": 23426, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "<p>Well I guess you have to be rather particular about it, but like people are saying, it makes more sense for String.Format to be static because of the implied semantics. Consider:</p>\n\n<pre><code>\"Hello {0}\".Format(\"World\"); // this makes it sound like Format *modifies* \n // the string, which is not possible as \n // strings are immutable.\n\nstring[] parts = \"Hello World\".Split(' '); // this however sounds right, \n // because it implies that you \n // split an existing string into \n // two *new* strings.\n</code></pre>\n" }, { "answer_id": 23798, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 2, "selected": false, "text": "<p>Maybe the .NET designers did it this way because JAVA did it this way...</p>\n\n<p>Embrace and extend. :)</p>\n\n<p>See: <a href=\"http://discuss.techinterview.org/default.asp?joel.3.349728.40\" rel=\"nofollow noreferrer\">http://discuss.techinterview.org/default.asp?joel.3.349728.40</a></p>\n" }, { "answer_id": 23978, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>The first thing I did when I got to upgrade to VS2008 and C#3, was to do this</p>\n\n<pre><code>public static string F( this string format, params object[] args )\n{\n return String.Format(format, args);\n}\n</code></pre>\n\n<p>So I can now change my code from</p>\n\n<pre><code>String.Format(\"Hello {0}\", Name);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>\"Hello {0}\".F(Name);\n</code></pre>\n\n<p>which I preferred at the time. \nNowadays (2014) I don't bother because it's just another hassle to keep re-adding that to each random project I create, or link in some bag-of-utils library.</p>\n\n<p>As for why the .NET designers chose it? Who knows. It seems entirely subjective.\nMy money is on either</p>\n\n<ul>\n<li>Copying Java</li>\n<li>The guy writing it at the time subjectively liked it more.</li>\n</ul>\n\n<p>There aren't really any other valid reasons that I can find</p>\n" }, { "answer_id": 24018, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p><strong>.NET Strings are Immutable</strong></p>\n\n<p>Therefore having an instance method makes absolutely no sense.</p>\n\n<pre><code>String foo = new String();\n\nfoo.Format(\"test {0}\",1); // Makes it look like foo should be modified by the Format method. \n\nstring newFoo = String.Format(foo, 1); // Indicates that a new string will be returned, and foo will be unaltered.\n</code></pre>\n" }, { "answer_id": 24024, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 1, "selected": false, "text": "<p>Non-overloaded, non-inherited static methods (like Class.b(a,c)) that take an instance as the first variable are semantically equivalent to a method call (like a.b(c)) so the platform team made an arbitrary, aesthetic choice. (Assuming it compiles to the same CIL, which it should.) The only way to know would be to ask them why.</p>\n\n<p>Possibly they did it to keep the two strings close to each other lexigraphically, i.e.</p>\n\n<pre><code>String.Format(\"Foo {0}\", \"Bar\");\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>\"Foo {0}\".Format(\"bar\");\n</code></pre>\n\n<p>You want to know what the indexes are mapped to; perhaps they thought that the \".Format\" part just adds noise in the middle.</p>\n\n<p>Interestingly, the ToString method (at least for numbers) is the opposite: number.ToString(\"000\") with the format string on the right hand side.</p>\n" }, { "answer_id": 24048, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>.NET Strings are Immutable<br>\n Therefore having an instance method makes absolutely no sense.</p>\n</blockquote>\n\n<p>By that logic the string class should have no instance methods which return modified copies of the object, yet it has <em>plenty</em> (Trim, ToUpper, and so on). Furthermore, lots of other objects in the framework do this too.</p>\n\n<p>I agree that if they were to make it an instance method, <code>Format</code> seems like it would be a bad name, but that doesn't mean the functionality shouldn't be an instance method.</p>\n\n<p>Why not this? It's consistent with <a href=\"http://msdn.microsoft.com/en-us/library/8wch342y.aspx\" rel=\"nofollow noreferrer\">the rest of</a> <a href=\"http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx\" rel=\"nofollow noreferrer\">the .NET framework</a></p>\n\n<pre><code>\"Hello {0}\".ToString(\"Orion\");\n</code></pre>\n" }, { "answer_id": 24084, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>@Jared:</p>\n\n<blockquote>\n <p>Non-overloaded, non-inherited static methods (like Class.b(a,c)) that take an instance as the first variable are semantically equivalent to a method call (like a.b(c))</p>\n</blockquote>\n\n<p>No, they aren't.</p>\n\n<blockquote>\n <p>(Assuming it compiles to the same CIL, which it should.)</p>\n</blockquote>\n\n<p>That's your mistake. The CIL produced is different. The distinction is that member methods can't be invoked on <code>null</code> values so the CIL inserts a check against <code>null</code> values. This obviously isn't done in the static variant.</p>\n\n<p>However, <code>String.Format</code> does <em>not</em> allow <code>null</code> values so the developers had to insert a check manually. From this point of view, the member method variant would be technically superior.</p>\n" }, { "answer_id": 24143, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 6, "selected": true, "text": "<p>I don't actually know the answer but I suspect that it has something to do with the aspect of invoking methods on string literals directly.</p>\n\n<p>If I recall correctly (I didn't actually verify this because I don't have an old IDE handy), early versions of the C# IDE had trouble detecting method calls against string literals in IntelliSense, and that has a big impact on the discoverability of the API. If that was the case, typing the following wouldn't give you any help:</p>\n\n<pre><code>\"{0}\".Format(12);\n</code></pre>\n\n<p>If you were forced to type </p>\n\n<pre><code>new String(\"{0}\").Format(12);\n</code></pre>\n\n<p>It would be clear that there was no advantage to making the Format method an instance method rather than a static method. </p>\n\n<p>The .NET libraries were designed by a lot of the same people that gave us MFC, and the String class in particular bears a strong resemblance to the CString class in MFC. MFC does have an instance Format method (that uses printf style formatting codes rather than the curly-brace style of .NET) which is painful because there's no such thing as a CString literal. So in a MFC codebase that I worked on I see a lot of this:</p>\n\n<pre><code>CString csTemp = \"\";\ncsTemp.Format(\"Some string: %s\", szFoo);\n</code></pre>\n\n<p>which is painful. (I'm not saying that the code above is a great way to do things even in MFC, but that does seem to be the way that most of the developers on the project learned how to use CString::Format). Coming from that heritage, I can imagine that the API designers were trying to avoid that sort of situation again.</p>\n" }, { "answer_id": 24147, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>This is to avoid confusion with <code>.ToString()</code> methods.</p>\n\n<p>For instance:</p>\n\n<pre><code>double test = 1.54d;\n\n//string.Format pattern\nstring.Format(\"This is a test: {0:F1}\", test );\n\n//ToString pattern\n\"This is a test: \" + test.ToString(\"F1\");\n</code></pre>\n\n<p>If Format was an instance method on string this could cause confusion, as the patterns are different.</p>\n\n<p>String.Format() is a utility method to turn multiple objects into a formatted string.</p>\n\n<p>An instance method on a string does something to that string.</p>\n\n<p>Of course, you could do:</p>\n\n<pre><code>public static string FormatInsert( this string input, params object[] args) {\n return string.Format( input, args );\n}\n\n\"Hello {0}, I have {1} things.\".FormatInsert( \"world\", 3);\n</code></pre>\n" }, { "answer_id": 27029, "author": "nollidge", "author_id": 2911, "author_profile": "https://Stackoverflow.com/users/2911", "pm_score": 2, "selected": false, "text": "<p>I don't know why they did it, but it doesn't really matter anymore:</p>\n\n<pre><code>public static class StringExtension\n{\n public static string FormatWith(this string format, params object[] args)\n {\n return String.Format(format, args);\n }\n}\n\npublic class SomeClass\n{\n public string SomeMethod(string name)\n {\n return \"Hello, {0}\".FormatWith(name);\n }\n}\n</code></pre>\n\n<p>That flows a lot easier, IMHO.</p>\n" }, { "answer_id": 39385, "author": "Kociub", "author_id": 3632, "author_profile": "https://Stackoverflow.com/users/3632", "pm_score": 2, "selected": false, "text": "<p>Another reason for <code>String.Format</code> is the similarity to function <code>printf</code> from C. It was supposed to let C developers have an easier time switching languages.</p>\n" }, { "answer_id": 68990, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 2, "selected": false, "text": "<p>A big design goal for C# was to make the transition from C/C++ to it as easy as possible. Using dot syntax on a string literal would look <em>very</em> strange to someone with only a C/C++ background, and formatting strings is something a developer will likely do on day one with the language. So I believe they made it static to make it closer to familiar territory.</p>\n" }, { "answer_id": 71027, "author": "Kearns", "author_id": 6500, "author_profile": "https://Stackoverflow.com/users/6500", "pm_score": 3, "selected": false, "text": "<p>I think it is because Format doesn't take a string per se, but a \"format string\". Most strings are equal to things like \"Bob Smith\" or \"1010 Main St\" or what have you and not to \"Hello {0}\", generally you only put those format strings in when you are trying to use a template to create another string, like a factory method, and therefore it lends it self to a static method.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
Compare ``` String.Format("Hello {0}", "World"); ``` with ``` "Hello {0}".Format("World"); ``` Why did the .Net designers choose a static method over an instance method? What do you think?
I don't actually know the answer but I suspect that it has something to do with the aspect of invoking methods on string literals directly. If I recall correctly (I didn't actually verify this because I don't have an old IDE handy), early versions of the C# IDE had trouble detecting method calls against string literals in IntelliSense, and that has a big impact on the discoverability of the API. If that was the case, typing the following wouldn't give you any help: ``` "{0}".Format(12); ``` If you were forced to type ``` new String("{0}").Format(12); ``` It would be clear that there was no advantage to making the Format method an instance method rather than a static method. The .NET libraries were designed by a lot of the same people that gave us MFC, and the String class in particular bears a strong resemblance to the CString class in MFC. MFC does have an instance Format method (that uses printf style formatting codes rather than the curly-brace style of .NET) which is painful because there's no such thing as a CString literal. So in a MFC codebase that I worked on I see a lot of this: ``` CString csTemp = ""; csTemp.Format("Some string: %s", szFoo); ``` which is painful. (I'm not saying that the code above is a great way to do things even in MFC, but that does seem to be the way that most of the developers on the project learned how to use CString::Format). Coming from that heritage, I can imagine that the API designers were trying to avoid that sort of situation again.
23,250
<p>I was curious about how other people use the <strong>this</strong> keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:</p> <p>In a constructor:</p> <pre><code>public Light(Vector v) { this.dir = new Vector(v); } </code></pre> <p>Elsewhere</p> <pre><code>public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } </code></pre>
[ { "answer_id": 23257, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 5, "selected": false, "text": "<p>I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.</p>\n" }, { "answer_id": 23258, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.</p>\n" }, { "answer_id": 23259, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 1, "selected": false, "text": "<p>I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...</p>\n" }, { "answer_id": 23260, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 2, "selected": false, "text": "<p>You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))</p>\n" }, { "answer_id": 23264, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 7, "selected": false, "text": "<p>I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:</p>\n\n<pre><code>class Vector3\n{\n float x;\n float y;\n float z;\n\n public Vector3(float x, float y, float z)\n {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n}\n</code></pre>\n\n<p>Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)</p>\n" }, { "answer_id": 23267, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 4, "selected": false, "text": "<p>Any time you need a reference to the current object.</p>\n\n<p>One particularly handy scenario is when your object is calling a function and wants to pass itself into it.</p>\n\n<p>Example:</p>\n\n<pre><code>void onChange()\n{\n screen.draw(this);\n}\n</code></pre>\n" }, { "answer_id": 23278, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 1, "selected": false, "text": "<p>I pretty much only use <strong>this</strong> when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing <strong>this</strong>.</p>\n" }, { "answer_id": 23279, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 0, "selected": false, "text": "<p>It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then \"this\" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.</p>\n" }, { "answer_id": 23281, "author": "Philippe", "author_id": 920, "author_profile": "https://Stackoverflow.com/users/920", "pm_score": 3, "selected": false, "text": "<p>I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.</p>\n" }, { "answer_id": 23306, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": false, "text": "<p>I can't believe all of the people that say using it always is a \"best practice\" and such.</p>\n\n<p>Use \"this\" when there is ambiguity, as in <a href=\"https://stackoverflow.com/a/23264/282110\">Corey's example</a> or when you need to pass the object as a parameter, as in <a href=\"https://stackoverflow.com/a/23267/282110\">Ryan's example</a>. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.</p>\n\n<p>EDIT: The C# documentation on \"this\" indicates one more use, besides the two I mentioned, for the \"this\" keyword - <a href=\"http://msdn.microsoft.com/en-us/library/dk1507sz(VS.71).aspx\" rel=\"nofollow noreferrer\">for declaring indexers</a></p>\n\n<p>EDIT: @Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the \"this\" keyword (as documented in the C# documentation), and those are times when you actually <em>need</em> it. Sticking \"this\" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.</p>\n" }, { "answer_id": 23323, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": -1, "selected": false, "text": "<p>Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? <em>Facepalm</em></p>\n" }, { "answer_id": 23340, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 5, "selected": false, "text": "<p>I use it whenever <a href=\"http://code.msdn.microsoft.com/sourceanalysis\" rel=\"noreferrer\">StyleCop</a> tells me to. <a href=\"http://code.msdn.microsoft.com/sourceanalysis\" rel=\"noreferrer\">StyleCop</a> must be obeyed. Oh yes.</p>\n" }, { "answer_id": 23435, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 8, "selected": false, "text": "<p>I don't mean this to sound snarky, but it doesn't matter.</p>\n\n<p>Seriously.</p>\n\n<p>Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the \"this\" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office. </p>\n\n<p>It's really just a style issue. If you like \"this\", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the \"most aesthetically pleasing code\" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something. </p>\n\n<p>I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.</p>\n" }, { "answer_id": 23502, "author": "Jakub Šturc", "author_id": 2361, "author_profile": "https://Stackoverflow.com/users/2361", "pm_score": 9, "selected": true, "text": "<p>There are several usages of <a href=\"http://msdn.microsoft.com/en-us/library/dk1507sz.aspx\" rel=\"noreferrer\">this</a> keyword in C#.</p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx\" rel=\"noreferrer\">To qualify members hidden by similar name</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx\" rel=\"noreferrer\">To have an object pass itself as a parameter to other methods</a></li>\n<li>To have an object return itself from a method</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx\" rel=\"noreferrer\">To declare indexers</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"noreferrer\">To declare extension methods</a></li>\n<li><a href=\"http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C%29\" rel=\"noreferrer\">To pass parameters between constructors</a></li>\n<li><a href=\"https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1800162#1800162\">To internally reassign value type (struct) value</a>.</li>\n<li>To invoke an extension method on the current instance</li>\n<li>To cast itself to another type</li>\n<li><a href=\"https://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it\">To chain constructors defined in the same class</a></li>\n</ol>\n\n<p>You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using <a href=\"https://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"noreferrer\">auto-implemented properties</a>.</p>\n" }, { "answer_id": 23520, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "<p>Here's when I use it:</p>\n\n<ul>\n<li>Accessing Private Methods from within the class (to differentiate)</li>\n<li>Passing the current object to another method (or as a sender object, in case of an event)</li>\n<li>When creating extension methods :D</li>\n</ul>\n\n<p>I don't use this for Private fields because I prefix private field variable names with an underscore (_). </p>\n" }, { "answer_id": 24003, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": 6, "selected": false, "text": "<p>Personally, I try to always use <em>this</em> when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see <em>this</em> used consistently, they will know if they are looking at a member variable or not.</p>\n" }, { "answer_id": 27246, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "<p>I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)</p>\n\n<p>But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.</p>\n" }, { "answer_id": 28679, "author": "Nick", "author_id": 1236, "author_profile": "https://Stackoverflow.com/users/1236", "pm_score": 2, "selected": false, "text": "<p>[C++]</p>\n\n<p>I agree with the \"use it when you have to\" brigade. Decorating code unnecessarily with <em>this</em> isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting <em>this</em> to always be there, i.e. they'll have to <em>think</em> about it.</p>\n\n<p>So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are <em>good</em> things to do or otherwise):</p>\n\n<ul>\n<li>Passing \"yourself\" to a function.</li>\n<li>Assigning \"yourself\" to a pointer or something like that.</li>\n<li>Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.</li>\n<li>Compiler enforced disambiguation.</li>\n</ul>\n" }, { "answer_id": 39993, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": -1, "selected": false, "text": "<p>You should not use \"this\" unless you absolutely must.</p>\n\n<p>There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.</p>\n" }, { "answer_id": 47397, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 1, "selected": false, "text": "<p>I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:</p>\n\n<pre><code>boolean sameValue (SomeNum other) {\n return this.importantValue == other.importantValue;\n} \n</code></pre>\n" }, { "answer_id": 70058, "author": "Stacker", "author_id": 6574, "author_profile": "https://Stackoverflow.com/users/6574", "pm_score": 1, "selected": false, "text": "<p><strong>[C++]</strong></p>\n\n<p><em>this</em> is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:</p>\n\n<pre><code>A a;\na = a;\n</code></pre>\n\n<p>Your assignment operator will be written:</p>\n\n<pre><code>A&amp; A::operator=(const A&amp; a) {\n if (this == &amp;a) return *this;\n\n // we know both sides of the = operator are different, do something...\n\n return *this;\n}\n</code></pre>\n" }, { "answer_id": 104938, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 1, "selected": false, "text": "<h2><code>this</code> on a C++ compiler</h2>\n\n<p>The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:</p>\n\n<ul>\n<li>using the mother class' method if you did not overloaded it in the child class.</li>\n<li>promoting a value of a type into another type</li>\n</ul>\n\n<p>But sometimes, <strong>You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.</strong></p>\n\n<p><strong>For me</strong>, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote <code>printf</code> instead of <code>print</code>. <code>this->printf</code> would not have compiled.</p>\n\n<p>The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.</p>\n\n<p>These are the reasons I use <code>this</code>.</p>\n\n<p>(§) it's still a kind of mystery to me, but I now wonder if the fact you include the &lt;windows.h&gt; header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace</p>\n\n<p>(§§) realizing that \"you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name\" is one of those <a href=\"http://en.wikipedia.org/wiki/Russian_roulette\" rel=\"nofollow noreferrer\">russian roulette</a> moments of a coder's life</p>\n" }, { "answer_id": 105015, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 3, "selected": false, "text": "<p>Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:</p>\n\n<pre><code>class Example : ICloneable\n{\n private void CallClone()\n {\n object clone = ((ICloneable)this).Clone();\n }\n\n object ICloneable.Clone()\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n" }, { "answer_id": 105016, "author": "Cyberherbalist", "author_id": 16964, "author_profile": "https://Stackoverflow.com/users/16964", "pm_score": 2, "selected": false, "text": "<p>In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of <code>this</code> is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.</p>\n\n<pre><code>class MyClass {\n private int _x\n public MyClass() : this(5) {}\n public MyClass(int v) { _x = v;}\n}\n</code></pre>\n\n<p>I've found this to be a particularly useful feature on occasion.</p>\n" }, { "answer_id": 105112, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>I use it to invoke <strong>Intellisense</strong> just like <a href=\"https://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword#27246\">JohnMcG</a>, but I'll go back and erase \"this->\" when I'm done. I follow the Microsoft convention of prefixing member variables with \"m_\", so leaving it as documentation would just be redundant.</p>\n" }, { "answer_id": 107010, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 0, "selected": false, "text": "<p>1 - Common Java setter idiom:</p>\n\n<pre><code> public void setFoo(int foo) {\n this.foo = foo;\n }\n</code></pre>\n\n<p>2 - When calling a function with this object as a parameter</p>\n\n<pre><code>notifier.addListener(this);\n</code></pre>\n" }, { "answer_id": 650055, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 1, "selected": false, "text": "<p>'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).</p>\n\n<p>Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.</p>\n\n<p>I usually delete it once I have what I was after: but this is just my style breaking through.</p>\n\n<p>In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.</p>\n" }, { "answer_id": 783056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.</p>\n" }, { "answer_id": 783345, "author": "Paw Baltzersen", "author_id": 94923, "author_profile": "https://Stackoverflow.com/users/94923", "pm_score": 1, "selected": false, "text": "<p>When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.</p>\n\n<p>To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.</p>\n" }, { "answer_id": 2182664, "author": "David Rodríguez - dribeas", "author_id": 36565, "author_profile": "https://Stackoverflow.com/users/36565", "pm_score": 0, "selected": false, "text": "<p>There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.</p>\n\n<p>You can use <code>this</code> to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct base {\n void f() {}\n};\n\ntemplate &lt;typename T&gt;\nstruct derived : public base&lt;T&gt;\n{\n void test() {\n //f(); // [1] error\n base&lt;T&gt;::f(); // quite verbose if there is more than one argument, but valid\n this-&gt;f(); // f is now an argument dependent symbol\n }\n}\n</code></pre>\n\n<p>Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments. </p>\n\n<p>At that step, without actually substituting the type, the compiler has almost no information of what <code>base&lt;T&gt;</code> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call <code>f</code> that seems just natural to the programmer is a symbol that the compiler must find as a member of <code>derived</code> or in enclosing namespaces --which does not happen in the example-- and it will complain.</p>\n\n<p>The solution is turning the non-dependent name <code>f</code> into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (<code>base&lt;T&gt;::f</code> --adding the <code>base&lt;T&gt;</code> makes the symbol dependent on <code>T</code> and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.</p>\n\n<p>The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a <code>this-&gt;</code> before the symbol. As the template class you are implementing does depend on an argument (it inherits from <code>base&lt;T&gt;</code>) <code>this-&gt;</code> is argument dependent, and we get the same result: <code>this-&gt;f</code> is checked in the second round, after template parameter substitution.</p>\n" }, { "answer_id": 2789224, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 2, "selected": false, "text": "<p>I use it when, in a function that accepts a reference to an object of the same type, I want to make it <strong>perfectly clear</strong> which object I'm referring to, where.</p>\n\n<p>For example</p>\n\n<pre><code>class AABB\n{\n // ... members\n bool intersects( AABB other )\n {\n return other.left() &lt; this-&gt;right() &amp;&amp;\n this-&gt;left() &lt; other.right() &amp;&amp;\n\n // +y increases going down\n other.top() &lt; this-&gt;bottom() &amp;&amp;\n this-&gt;top() &lt; other.bottom() ;\n }\n} ;\n</code></pre>\n\n<p>(vs)</p>\n\n<pre><code>class AABB\n{\n bool intersects( AABB other )\n {\n return other.left() &lt; right() &amp;&amp;\n left() &lt; other.right() &amp;&amp;\n\n // +y increases going down\n other.top() &lt; bottom() &amp;&amp;\n top() &lt; other.bottom() ;\n }\n} ;\n</code></pre>\n\n<p>At a glance which AABB does <code>right()</code> refer to? The <code>this</code> adds a bit of a clarifier.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016/" ]
I was curious about how other people use the **this** keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: ``` public Light(Vector v) { this.dir = new Vector(v); } ``` Elsewhere ``` public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } ```
There are several usages of [this](http://msdn.microsoft.com/en-us/library/dk1507sz.aspx) keyword in C#. 1. [To qualify members hidden by similar name](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx) 2. [To have an object pass itself as a parameter to other methods](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx) 3. To have an object return itself from a method 4. [To declare indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx) 5. [To declare extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx) 6. [To pass parameters between constructors](http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C%29) 7. [To internally reassign value type (struct) value](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1800162#1800162). 8. To invoke an extension method on the current instance 9. To cast itself to another type 10. [To chain constructors defined in the same class](https://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it) You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using [auto-implemented properties](https://msdn.microsoft.com/en-us/library/bb384054.aspx).
23,372
<p>What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?</p> <p>The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component). </p> <p>Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?</p> <p><strong>Edit:</strong></p> <p><strong><em>John:</em></strong> your solution looks like a lot of engineering :P What I ended up using is following wrapper:</p> <pre><code>package com.sun.lwuit; public class ImageWrapper { private final Image image; public ImageWrapper(final Image lwuitBuffer) { this.image = lwuitBuffer; } public javax.microedition.lcdui.Graphics getGraphics() { return image.getGraphics().getGraphics(); } } </code></pre> <p>Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.</p> <p>And it still looks like a hack :)</p> <p>But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)</p> <p>/JaanusSiim</p>
[ { "answer_id": 48945, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 0, "selected": false, "text": "<p>Based on the javadoc for LWUIT and J2ME and guessing that the custom J2ME class is a <a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Canvas.html\" rel=\"nofollow noreferrer\">Canvas</a> it looks like you would have to:</p>\n\n<ul>\n<li>Subclass <a href=\"https://lwuit.dev.java.net/javadocs/com/sun/lwuit/Component.html\" rel=\"nofollow noreferrer\">LWUIT's Component class</a> wrapping the custom J2ME component</li>\n<li>Override the paint() method of the LWUIT Component</li>\n<li>Subclass the <a href=\"http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Graphics.html\" rel=\"nofollow noreferrer\">J2ME Graphics class</a> wrapping the LWUIT Graphics class and pass all the method calls through</li>\n<li>Pass in the wrapped J2ME Graphics implementation to the custom J2ME component's paint method</li>\n</ul>\n\n<p>That third step is an ugly one. Check on the <a href=\"https://lwuit.dev.java.net/servlets/SummarizeList?listName=users\" rel=\"nofollow noreferrer\">LWUIT mailing list</a> to see if anyone has dome this before. From the published APIs I don't see another way to do it. </p>\n\n<p>Edit: The hack added in the question looks better than my hack for an Image. What I have <em>may</em> be better for a general case, but I don't know either LWUIT or J2ME well enough to really say that. </p>\n" }, { "answer_id": 86279, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 2, "selected": false, "text": "<p>I do not think any hacking is necessary. You can subclass the LWTUI Component class and then you can pain whatever you want on to the graphic context of the component. You do not get the native lcdui.Graphics object but an object with a same interface that is easy to use.</p>\n\n<p>If you really need to pass a lcdui.Graphics to some underlying library to display its output then I would suggest this:</p>\n\n<p>Somewhere in your component code (do only when the component contents really need to be changed):</p>\n\n<pre><code>private Image buffer = null; // keep this\n\nint[] bufferArray = new int[desiredWidth * desiredHeight];\njavax.microedition.lcdui.Image bufferImage = \n Image.createEmptyImage(desiredWidth, desiredHeight);\nthirPartyComponent.paint(bufferImage.getGraphics());\nbufferImage.getRGB(bufferArray,0,1,0,0,desiredWidth, desiredHeight);\nbufferImage = null; //no longer needed\nbuffer = Image.createImage(bufferArray, desiredWidth, desiredHeight);\n</code></pre>\n\n<p>In the component paint(g) method:</p>\n\n<pre><code>g.drawImage(0,0, buffer);\n</code></pre>\n\n<p>By doing the hack you did you are losing portablity and also sice you are exposing implementation private object you might also break other things.</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/706/" ]
What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements? The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component). Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it? **Edit:** ***John:*** your solution looks like a lot of engineering :P What I ended up using is following wrapper: ``` package com.sun.lwuit; public class ImageWrapper { private final Image image; public ImageWrapper(final Image lwuitBuffer) { this.image = lwuitBuffer; } public javax.microedition.lcdui.Graphics getGraphics() { return image.getGraphics().getGraphics(); } } ``` Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component. And it still looks like a hack :) But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :) /JaanusSiim
I do not think any hacking is necessary. You can subclass the LWTUI Component class and then you can pain whatever you want on to the graphic context of the component. You do not get the native lcdui.Graphics object but an object with a same interface that is easy to use. If you really need to pass a lcdui.Graphics to some underlying library to display its output then I would suggest this: Somewhere in your component code (do only when the component contents really need to be changed): ``` private Image buffer = null; // keep this int[] bufferArray = new int[desiredWidth * desiredHeight]; javax.microedition.lcdui.Image bufferImage = Image.createEmptyImage(desiredWidth, desiredHeight); thirPartyComponent.paint(bufferImage.getGraphics()); bufferImage.getRGB(bufferArray,0,1,0,0,desiredWidth, desiredHeight); bufferImage = null; //no longer needed buffer = Image.createImage(bufferArray, desiredWidth, desiredHeight); ``` In the component paint(g) method: ``` g.drawImage(0,0, buffer); ``` By doing the hack you did you are losing portablity and also sice you are exposing implementation private object you might also break other things. Hope this helps.
23,399
<p>I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.</p> <p>I'm using a simple Allow or Deny option for each 'Resource' or screen.</p> <p>We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group.</p> <p>I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance.</p> <p><strong>Option A</strong> The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied.</p> <p>I think this will mean a smaller table, but would queries search the whole table to determine there is no match?</p> <p><strong>Option B</strong> A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table.</p> <p>Thoughts?</p>
[ { "answer_id": 23413, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "<p>I would vote for Option B. If you go with Option A and the assumption that if a user exists, they can get in, then you'll eventually run into the problem that you'll want to deny access to a user, without removing the user record. </p>\n\n<p>There will be lots of cases where you'll want to lock a user out, but won't want to completely destroy their account. One such instance (not necessarily linked to your use case), is when you fail to pay, and they cut off your account until you start paying again. They don't want to delete the record, because they still want to enable it when you pay up again, instead of recreating the account from scratch, and losing all user history.</p>\n" }, { "answer_id": 23416, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>B. It allows for much better checks whether the data is complete (for example, when you add an allowable/deniable feature).</p>\n\n<p>Also, table size should only be a consideration for tables that you know will contain many records (as in, 100,000+). You even taking the time to type the table size consideration into this question already cost more than the extra hard drive space it would take.</p>\n" }, { "answer_id": 23432, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": true, "text": "<p>If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access.</p>\n\n<pre><code>UserResources\n-------------\nUserId FK-&gt;Users\nResourceId FK-&gt;Resources\n</code></pre>\n\n<p>and the sql would be something like </p>\n\n<pre><code>if exists (select 1 from UserResources \nwhere UserId = @uid and ResourceId=@rid)\nset @allow=1;\n</code></pre>\n\n<p>With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.</p>\n" }, { "answer_id": 23480, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "<p>Approach A, but I would also include a explicit deny in addition to you implicit deney. I would make some use cases to be sure your end logic works but here are some examples.</p>\n\n<pre><code>User1 is in group1 and group2. \nUser2 is in group1 \nUser3 is in group2 \n</code></pre>\n\n<hr>\n\n<pre><code>Folder1 allows group1 and deny group2. \nUser1 is denied. \nUser2 is allowed. \nUser3 is denied. \n</code></pre>\n\n<p>I believe your approach users1 would be allowed.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470/" ]
I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers. I'm using a simple Allow or Deny option for each 'Resource' or screen. We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group. I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance. **Option A** The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied. I think this will mean a smaller table, but would queries search the whole table to determine there is no match? **Option B** A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table. Thoughts?
If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access. ``` UserResources ------------- UserId FK->Users ResourceId FK->Resources ``` and the sql would be something like ``` if exists (select 1 from UserResources where UserId = @uid and ResourceId=@rid) set @allow=1; ``` With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.
23,603
<p>I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project).<br> As a result, the project would no longer compile with previous versions of the library.</p> <p>So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in.<br> I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically.</p>
[ { "answer_id": 23624, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 0, "selected": false, "text": "<p>One option is to use a single subversion repository and check-in changes that effect both library and project at the same time. That way you know that whatever revision of the project you are on requires the same revision of the library.</p>\n" }, { "answer_id": 23702, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 2, "selected": false, "text": "<p>I think if I were going to do this, I would use tags. It would be pretty easy to write a script that would tag both repositories with the same ID each time you upgraded the library and used it in the project. Then, if you need to roll back to a previous version, you just see what its most recent tag was, and roll the library back to that version.</p>\n\n<p>UPDATE: Sorry, I've been in Mercurial land for a while, and forgot that subversion doesn't directly support tagging. Assuming you use the usual subversion directory structure</p>\n\n<pre><code>/\n /trunk\n /tags\n /branches\n</code></pre>\n\n<p>you just need to run</p>\n\n<pre><code>svn copy trunk/ tags/TagName\n</code></pre>\n\n<p>on both repos, with the same tag name. Subversion is pretty good about smart copies, so you don't need to worry about disk space.</p>\n" }, { "answer_id": 23811, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 2, "selected": false, "text": "<p>An option that might work for you is to use an svn:external reference to the library. When tagging the project, you can do one of two things:</p>\n\n<ul>\n<li>Update the svn:external to refer to a specific revision of the library; OR</li>\n<li>Update the svn:external to refer to a new tag that you make on the library. </li>\n</ul>\n\n<p>Since the svn:external metadata will be part of the main project's commit history, you can always get the tag on the main project and it will refer to the correct version of the library. We do it and it works very well. It also comes in handy when you want to freeze the version of the library code that you depend on in preparation for a release.</p>\n" }, { "answer_id": 23816, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>You might find <a href=\"http://piston.rubyforge.org/\" rel=\"nofollow noreferrer\">piston</a> provides a solution</p>\n\n<p>It's primarily used for importing ruby on rails plugins, but I don't see why it shouldn't work for any subversion repositories.</p>\n\n<p>Basically what it does is this:</p>\n\n<ul>\n<li>svn export latest revision of the remote path</li>\n<li>commit these files into your local svn as if they were local files</li>\n<li>attach metadata in the form of svn properties about the remote path and revision</li>\n</ul>\n\n<p>This means you can keep a reference to a particular version of a remote repo without having to have it constantly updated like with an svn external.</p>\n\n<p>if you want to update your local copy of the library to the latest remote version, you just do <code>piston update</code></p>\n\n<p>You should also be able to look at the history of updates, by simply looking at the metadata - svn properties are versioned just like files and everything else</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112/" ]
I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project). As a result, the project would no longer compile with previous versions of the library. So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in. I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically.
I think if I were going to do this, I would use tags. It would be pretty easy to write a script that would tag both repositories with the same ID each time you upgraded the library and used it in the project. Then, if you need to roll back to a previous version, you just see what its most recent tag was, and roll the library back to that version. UPDATE: Sorry, I've been in Mercurial land for a while, and forgot that subversion doesn't directly support tagging. Assuming you use the usual subversion directory structure ``` / /trunk /tags /branches ``` you just need to run ``` svn copy trunk/ tags/TagName ``` on both repos, with the same tag name. Subversion is pretty good about smart copies, so you don't need to worry about disk space.
23,610
<p>I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:</p> <pre><code>DOMAIN\USER DOMAIN\GROUP </code></pre> <p>I have a list of users in active directory format that I need to add:</p> <pre><code>ou=group1;ou=group2;ou=group3 </code></pre> <p>I have tried adding DOMAIN\Group1, but I get a 'user not found' error.</p> <p>P.S. should also be noted that I'm not a Lan admin </p>
[ { "answer_id": 23611, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p>OU is an Organizational Unit (sort of like a Subfolder in Explorer), not a Group, Hence group1, 2 and 3 are not actually groups.</p>\n\n<p>You are looking for the DN Attribute, also called \"distinguishedName\". You can simply use DOMAIN\\DN once you have that.</p>\n\n<p>Edit: For groups, the CN (Common Name) could also work. </p>\n\n<p>The full string from Active Directory normally looks like this:</p>\n\n<blockquote>\n <p>cn=Username,cn=Users,dc=DomainName,dc=com</p>\n</blockquote>\n\n<p>(Can be longer or shorter, but the important bit is that the \"ou\" part is worthless for what you're trying to achieve.</p>\n" }, { "answer_id": 23656, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "<p>Programatically or Manually?</p>\n\n<p>Manually, i prefer <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx\" rel=\"noreferrer\">AdExplorer</a>, which is a nice Active directory Browser. You just connect to your domain controller and then you can look for the user and see all the details. Of course, you need permissions on the Domain Controller, not sure which though.</p>\n\n<p>Programatically, it depends on your language of couse. On .net, the <a href=\"http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx\" rel=\"noreferrer\">System.DirectoryServices</a> Namespace is your friend. (I don't have any code examples here unfortunately)</p>\n\n<p>For Active Directory, I'm not really an expert apart from how to query it, but here are two links I found useful:</p>\n\n<p><a href=\"http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm\" rel=\"noreferrer\">http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Active_Directory\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Active_Directory</a> (General stuff about the Structure of AD)</p>\n" }, { "answer_id": 23660, "author": "adeel825", "author_id": 324, "author_profile": "https://Stackoverflow.com/users/324", "pm_score": 2, "selected": false, "text": "<p>You need to go to the Active Directory Users Snap In after logging in as a domain admin on the machine:</p>\n\n<ol>\n<li>Go to start --> run and type in mmc.</li>\n<li>In the MMC console go to File --></li>\n<li>Add/Remove Snap-In Click Add Select</li>\n<li>Active Directory Users and Computers and select Add. </li>\n<li>Hit Close and then hit OK.</li>\n</ol>\n\n<p>From here you can expand the domain tree and search (by right-clicking on the domain name).</p>\n\n<p>You may not need special privileges to view the contents of the Active Directory domain, especially if you are logged in on that domain. It is worth a shot to see how far you can get. </p>\n\n<p>When you search for someone, you can select the columns from View --> Choose Columns. This should help you search for the person or group you are looking for.</p>\n" }, { "answer_id": 23663, "author": "Roy Rico", "author_id": 1580, "author_profile": "https://Stackoverflow.com/users/1580", "pm_score": 0, "selected": false, "text": "<p>Thanks adeel825 &amp; Michael Stum. </p>\n\n<p>My problem is, though, i'm in a big corporation and do not have access to log in as the domain admin nor to view the active directory, so i guess my solution is to try and get that level of access.</p>\n" }, { "answer_id": 23679, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p>Well, AdExplorer runs on your Local Workstation (which is why I prefer it) and I believe that most users have read access to AD anyway because that's actually required for stuff to work, but I'm not sure about that.</p>\n" }, { "answer_id": 23709, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 2, "selected": false, "text": "<p>You do not need domain admin rights to <em>look</em> at the active directory. By default, any (authenticated?) user can read the information that you need from the directory.</p>\n\n<p>If that wasn't the case, for example, a computer (which has an associated account as well) could not verify the account and password of its user.</p>\n\n<p>You only need admin rights to <em>change</em> the contents of the directory.</p>\n\n<p>I think it is possible to set more restricted permissions, but that's not likely the case.</p>\n" }, { "answer_id": 809012, "author": "Doug Seelinger", "author_id": 98167, "author_profile": "https://Stackoverflow.com/users/98167", "pm_score": 0, "selected": false, "text": "<p>Install the \"Windows Support Tools\" that is on the Windows Server CD (CD 1 if it's Windows 2003 R2). If your CD/DVD drive is D: then it will be in D:\\Support\\Tools\\SuppTools.msi</p>\n\n<p>This gives you a couple of additional tools to \"get at\" AD:\nLDP.EXE - good for reading information in AD, but the UI kinda stinks.\nADSI Edit - another snap-in for MMC.EXE that you can both browse AD with and get to all those pesky AD attributes you're looking for.</p>\n\n<p>You can install these tools on your local workstation and access AD from there without domain admin privileges. If you can log on to the domain, you can at least query/read AD for this information.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580/" ]
I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like: ``` DOMAIN\USER DOMAIN\GROUP ``` I have a list of users in active directory format that I need to add: ``` ou=group1;ou=group2;ou=group3 ``` I have tried adding DOMAIN\Group1, but I get a 'user not found' error. P.S. should also be noted that I'm not a Lan admin
Programatically or Manually? Manually, i prefer [AdExplorer](http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx), which is a nice Active directory Browser. You just connect to your domain controller and then you can look for the user and see all the details. Of course, you need permissions on the Domain Controller, not sure which though. Programatically, it depends on your language of couse. On .net, the [System.DirectoryServices](http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx) Namespace is your friend. (I don't have any code examples here unfortunately) For Active Directory, I'm not really an expert apart from how to query it, but here are two links I found useful: <http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm> <http://en.wikipedia.org/wiki/Active_Directory> (General stuff about the Structure of AD)
23,620
<p>I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.</p> <p>As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko_spellcheck option, which is supposed to fix it, but it doesn't.</p> <p>Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?</p>
[ { "answer_id": 23655, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>I know at least <a href=\"http://developer.yahoo.com/yui/editor/\" rel=\"nofollow noreferrer\">yahoo!'s Rich Text Editor</a> will let you use the included spell checker in FireFox.</p>\n\n<p>I also tested FCKeditor, but that requires the users to install additional plugins on their computer.</p>\n" }, { "answer_id": 23733, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "<p>TinyMCE only goes out of its way to disable spell-checking when you don't specify the <code>gecko_spellcheck</code> option (i verified this with their example code). Might want to double-check your <code>tinyMCE.init()</code> call - it should look something like this:</p>\n\n<pre><code>tinyMCE.init({\n mode : \"textareas\",\n theme : \"simple\",\n gecko_spellcheck : true\n});\n</code></pre>\n" }, { "answer_id": 24638, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 1, "selected": false, "text": "<p>Most rich text editors let you specify whether or not to disable the browser's spellchecker (as answered by others), with the exception of those running in Safari.</p>\n\n<p>There is currently no way to programmatically disable the Safari spellchecker (as there is in FF and IE7+), so most rich text editors choose to let Safari do its own thing by leaving the browser in control of the context menu.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2527/" ]
I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that. As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko\_spellcheck option, which is supposed to fix it, but it doesn't. Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?
TinyMCE only goes out of its way to disable spell-checking when you don't specify the `gecko_spellcheck` option (i verified this with their example code). Might want to double-check your `tinyMCE.init()` call - it should look something like this: ``` tinyMCE.init({ mode : "textareas", theme : "simple", gecko_spellcheck : true }); ```
23,715
<p>Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question.</p> <ul> <li>I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the <em>same port</em> (ie, they both run on port 80)?</li> <li>The web servers would <em>not</em> be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com.</li> </ul> <p>I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole. :) </p>
[ { "answer_id": 23718, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 0, "selected": false, "text": "<p>Your best bet would be putting Apache httpd in front of port 80 and relay requests meant for other servers through Apache by using modules. Most popular scenario would be Tomcat behind Apache where you'll be able to run both php and jsp applications.</p>\n\n<p>I'm not familiar with CherryPy, so I can only suggest you look for an Apache module for CherryPy.</p>\n\n<p>Edit: This looks promising: <a href=\"http://tools.cherrypy.org/wiki/BehindApache\" rel=\"nofollow noreferrer\">http://tools.cherrypy.org/wiki/BehindApache</a></p>\n" }, { "answer_id": 23723, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 0, "selected": false, "text": "<p>Alternatively, to Ishmaeel's correct answer, if you have a server with 2 network cards, you could have each server answer requests on different IP addresses.</p>\n" }, { "answer_id": 23732, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 4, "selected": true, "text": "<p>You can't have two processes bound to the same port on the same IP address. You can add another IP address to the box and have each server listen on one.</p>\n\n<p>Another option is to proxy pass one server to the other. With Apache, you could do something like:</p>\n\n<pre><code>NameVirtualHost *\n&lt;virtualhost *&gt;\n ServerName other.site.com\n\n # assumes CherryPy listens on port 8080\n ProxyPass / http://127.0.0.1:8080/\n ProxyPassReverse / http://127.0.0.1:8080/\n&lt;/Virtualhost&gt;\n</code></pre>\n\n<p>That's a pretty quick example, but you can always check the <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_proxy.html\" rel=\"noreferrer\">ProxyPass documentation</a>. Remember though, the application being proxyed to will get 127.0.0.1 in it's logs instead of the requester's IP address. Some web servers (apache does with <a href=\"http://stderr.net/apache/rpaf/\" rel=\"noreferrer\">mod_rpaf</a>) can substitute the X-Forwarded-For header in place of the wrong IP address. Possibly CherryPy has this?</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321/" ]
Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question. * I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the *same port* (ie, they both run on port 80)? * The web servers would *not* be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com. I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole. :)
You can't have two processes bound to the same port on the same IP address. You can add another IP address to the box and have each server listen on one. Another option is to proxy pass one server to the other. With Apache, you could do something like: ``` NameVirtualHost * <virtualhost *> ServerName other.site.com # assumes CherryPy listens on port 8080 ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ </Virtualhost> ``` That's a pretty quick example, but you can always check the [ProxyPass documentation](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html). Remember though, the application being proxyed to will get 127.0.0.1 in it's logs instead of the requester's IP address. Some web servers (apache does with [mod\_rpaf](http://stderr.net/apache/rpaf/)) can substitute the X-Forwarded-For header in place of the wrong IP address. Possibly CherryPy has this?
23,755
<p>When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:</p> <pre><code>1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack)</code></pre> <p>Which do you prefer, and why?</p> <p>I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".</p> <p>In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?</p>
[ { "answer_id": 23756, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>This entirely depends on what varies and what stays the same.</p>\n\n<p>For example, I am working on a (non-OOP) <a href=\"http://www.seqan.de/\" rel=\"noreferrer\">framework</a> where the find algorithm is different depending both on the type of the needle and the haystack. Apart from the fact that this would require double-dispatch in an object-oriented environment, it also means that it isn't meaningful to write either <code>needle.find(haystack)</code> or to write <code>haystack.find(needle)</code>.</p>\n\n<p>On the other hand, your application could happily delegate finding to either of both classes, or stick with one algorithm altogether in which case the decision is arbitrary. In that case, I would prefer the <code>haystack.find(needle)</code> way because it seems more logical to apply the finding to the haystack.</p>\n" }, { "answer_id": 23758, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 1, "selected": false, "text": "<p>Personally, I like the second method. My reasoning is because the major APIs I have worked with use this approach, and I find it makes the most sense.</p>\n\n<p>If you have a list of things (haystack) you would search for (find()) the needle.</p>\n" }, { "answer_id": 23760, "author": "Tilendor", "author_id": 1470, "author_profile": "https://Stackoverflow.com/users/1470", "pm_score": 4, "selected": false, "text": "<p>I would say that option 1 is completely out. The code should read in a way that tells you what it does. Option 1 makes me think that this needle is going to go find me a haystack.</p>\n\n<p>Option 2 looks good if a haystack is meant to contain needles. ListCollections are always going to contain ListItems, so doing collection.find(item) is natural and expressive.</p>\n\n<p>I think the introduction of a helper object is approproiate when:</p>\n\n<ol>\n<li>You don't control the implementation of the objects in question<br>\nIE: search.find(ObsecureOSObject, file)</li>\n<li>There isn't a regular or sensible relationship between the objects<br>\nIE: nameMatcher.find(houses,trees.name)</li>\n</ol>\n" }, { "answer_id": 23769, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 7, "selected": true, "text": "<p>Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate.</p>\n\n<p>You also have a fourth alternative that I think would be better than alternative 3:</p>\n\n<pre><code>haystack.find(needle, searcher)\n</code></pre>\n\n<p>In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on.</p>\n" }, { "answer_id": 23812, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "<p>There is another alternative, which is the approach utilized by the STL of C++:</p>\n\n<pre><code>find(haystack.begin(), haystack.end(), needle)\n</code></pre>\n\n<p>I think it's a great example of C++ shouting \"in your face!\" to OOP. The idea is that OOP is not a silver bullet of any kind; sometimes things are best described in terms of actions, sometimes in terms of objects, sometimes neither and sometimes both.</p>\n\n<p>Bjarne Stroustrup said in TC++PL that when you design a system you should strive to reflect reality under the constraints of effective and efficient code. For me, this means you should never follow anything blindly. Think about the things at hand (haystack, needle) and the context we're in (searching, that's what the expression is about).</p>\n\n<p>If the emphasis is about the searching, then using an algorithm (action) that emphasizes searching (i.e. is flexibly to fit haystacks, oceans, deserts, linked lists). If the emphasis is about the haystack, encapsulate the find method inside the haystack object, and so on.</p>\n\n<p>That said, sometimes you're in doubt and have hard times making a choice. In this case, be object oriented. If you change your mind later, I think it is easier to extract an action from an object then to split an action to objects and classes.</p>\n\n<p>Follow these guidelines, and your code will be clearer and, well, more beautiful.</p>\n" }, { "answer_id": 23814, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 6, "selected": false, "text": "<p>Of the three, I prefer option #3.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> makes me not want to put searching capabilities on my DTOs or models. Their responsibility is to be data, not to find themselves, nor should needles need to know about haystacks, nor haystacks know about needles.</p>\n\n<p>For what it's worth, I think it takes most OO practitioners a LONG time to understand why #3 is the best choice. I did OO for a decade, probably, before I really grokked it.</p>\n\n<p>@wilhelmtell, C++ is one of the very few languages with template specialization that make such a system actually work. For most languages, a general purpose \"find\" method would be a HORRIBLE idea.</p>\n" }, { "answer_id": 23818, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 2, "selected": false, "text": "<p>It depends on your requirements.</p>\n\n<p>For instance, if you don't care about the searcher's properties (e.g. searcher strength, vision, etc.), then I would say haystack.find(needle) would be the cleanest solution.</p>\n\n<p>But, if you do care about the searcher's properties (or any other properties for that matter), I would inject an ISearcher interface into either the haystack constructor or the function to facilitate that. This supports both object oriented design (a haystack has needles) and inversion of control / dependency injection (makes it easier to unit test the \"find\" function).</p>\n" }, { "answer_id": 23840, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 4, "selected": false, "text": "<p>I am with Brad on this one. The more I work on immensely complex systems, the more I see the need to truly decouple objects. He's right. It's obvious that a needle shouldn't know anything about haystack, so 1 is definitely out. But, a haystack should know nothing about a needle. </p>\n\n<p>If I were modeling a haystack, I might implement it as a collection -- but as a collection of <em>hay</em> or <em>straw</em> -- not a collection of needles! However, I would take into consideration that stuff does get lost in a haystack, but I know nothing about what exactly that stuff. I think it's better to not make the haystack look for items in itself (how <em>smart</em> is a haystack anyway). The right approach to me is to have the haystack present a collection of things that are in it, but are not straw or hay or whatever gives a haystack its essence.</p>\n\n<pre><code>class Haystack : ISearchableThingsOnAFarm {\n ICollection&lt;Hay&gt; myHay;\n ICollection&lt;IStuffSmallEnoughToBeLostInAHaystack&gt; stuffLostInMe;\n\n public ICollection&lt;Hay&gt; Hay {\n get {\n return myHay;\n }\n }\n\n public ICollection&lt;IStuffSmallEnoughToBeLostInAHayStack&gt; LostAndFound {\n get {\n return stuffLostInMe;\n }\n }\n}\n\nclass Needle : IStuffSmallEnoughToBeLostInAHaystack {\n}\n\nclass Farmer {\n Search(Haystack haystack, \n IStuffSmallEnoughToBeLostInAHaystack itemToFind)\n}\n</code></pre>\n\n<p>There's actually more I was going to type and abstract into interfaces and then I realized how crazy I was getting. Felt like I was in a CS class in college... :P</p>\n\n<p>You get the idea. I think going as loosely coupled as possible is a good thing, but maybe I was getting a bit carried away! :)</p>\n" }, { "answer_id": 23953, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>To quote the great authors of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0262011530\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">SICP</a>,</p>\n\n<p><em>Programs must be written for people to read, and only incidentally for machines to execute</em></p>\n\n<p>I prefer to have both methods 1 and 2 at hand. Using ruby as an example, it comes with <code>.include?</code> which is used like this</p>\n\n<pre><code>haystack.include? needle\n=&gt; returns true if the haystack includes the needle\n</code></pre>\n\n<p>Sometimes though, purely for readability reasons, I want to flip it round. Ruby doesn't come with an <code>in?</code> method, but it's a one-liner, so I often do this:</p>\n\n<pre><code>needle.in? haystack\n=&gt; exactly the same as above\n</code></pre>\n\n<p>If it's \"more important\" to emphasise the haystack, or the operation of searching, I prefer to write <code>include?</code>.\nOften though, neither the haystack or the search is really what you care about, just that the object is present - in this case I find <code>in?</code> better conveys the meaning of the program.</p>\n" }, { "answer_id": 23957, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>@Peter Meyer</p>\n<p>You get the idea. I think going as loosely coupled as possible is a good thing, but maybe I was getting a bit carried away! :)</p>\n</blockquote>\n<p>Errr... yeah... I think the <code>IStuffSmallEnoughToBeLostInAHaystack</code> kind of is a red flag :-)</p>\n" }, { "answer_id": 25296, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 1, "selected": false, "text": "<blockquote><p>You also have a fourth alternative that I think would be better than alternative 3:</p>\n<pre><code>haystack.find(needle, searcher)</code></pre>\n</blockquote>\n\n<p>I see your point, but what if <code>searcher</code> implements a searching interface that allows for searching other types of objects than haystacks, and finding other things than needles in them? </p>\n\n<p>The interface could also be implemented with different algorithms, for example:</p>\n\n<pre><code>binary_searcher.find(needle, haystack)\nvision_searcher.find(pitchfork, haystack)\nbrute_force_searcher.find(money, wallet)\n</code></pre>\n\n<p>But, as others have already pointed out, I also think this is only helpful if you actually have multiple search algorithms or multiple searchable or findable classes. If not, I agree <code>haystack.find(needle)</code> is better because of its simplicity, so I am willing to sacrifice some \"correctness\" for it.</p>\n" }, { "answer_id": 25337, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>When implementing a needle search of a\n haystack in an object-oriented way,\n you essentially have three\n alternatives:</p>\n \n <ol>\n <li><p>needle.find(haystack)</p></li>\n <li><p>haystack.find(needle)</p></li>\n <li><p>searcher.find(needle, haystack)</p></li>\n </ol>\n \n <p>Which do you prefer, and why?</p>\n</blockquote>\n\n<p>Correct me if I'm wrong, but in all three examples you already <em>have</em> a reference to the needle you're looking for, so isn't this kinda like looking for your glasses when they're sitting on your nose? :p</p>\n\n<p>Pun aside, I think it really depends on what you consider the responsibility of the haystack to be within the given domain. Do we just care about it in the sense of being a thing which contains needles (a collection, essentially)? Then haystack.find(needlePredicate) is fine. Otherwise, farmBoy.find(predicate, haystack) might be more appropriate.</p>\n" }, { "answer_id": 25428, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 1, "selected": false, "text": "<pre><code>haystack.magnet().filter(needle);\n</code></pre>\n" }, { "answer_id": 33027, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 2, "selected": false, "text": "<p>Easy: Burn the haystack! Afterward, only the needle will remain. Also, you could try magnets.</p>\n\n<p>A harder question: How do you find one particular needle in a pool of needles?</p>\n\n<p>Answer: thread each one and attach the other end of each strand of thread to a sorted index (i.e. pointers)</p>\n" }, { "answer_id": 33056, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 1, "selected": false, "text": "<p>The haystack shouldn't know about the needle, and the needle shouldn't know about the haystack. The searcher needs to know about both, but whether or not the haystack should know how to search itself is the real point in contention.</p>\n\n<p>So I'd go with a mix of 2 and 3; the haystack should be able to tell someone else how to search it, and the searcher should be able to use that information to search the haystack.</p>\n" }, { "answer_id": 33156, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 1, "selected": false, "text": "<pre><code>class Haystack {//whatever\n };\nclass Needle {//whatever\n }:\nclass Searcher {\n virtual void find() = 0;\n};\n\nclass HaystackSearcher::public Searcher {\npublic:\n HaystackSearcher(Haystack, object)\n virtual void find();\n};\n\nHaystack H;\nNeedle N;\nHaystackSearcher HS(H, N);\nHS.find();\n</code></pre>\n" }, { "answer_id": 33331, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<p>A mix of 2 and 3, really.</p>\n\n<p>Some haystacks don't have a specialized search strategy; an example of this is an array. The only way to find something is to start at the beginning and test each item until you find the one you want.</p>\n\n<p>For this kind of thing, a free function is probably best (like C++).</p>\n\n<p>Some haystacks can have a specialized search strategy imposed on them. An array can be sorted, allowing you to use binary searching, for example. A free function (or pair of free functions, e.g. sort and binary_search) is probably the best option.</p>\n\n<p>Some haystacks have an integrated search strategy as part of their implementation; associative containers (hashed or ordered sets and maps) all do, for instance. In this case, finding is probably an essential lookup method, so it should probably be a method, i.e. haystack.find(needle).</p>\n" }, { "answer_id": 37511, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 2, "selected": false, "text": "<p>I can think of situations where either of the first two flavours makes sense:</p>\n\n<ol>\n<li><p>If the needle needs pre-processing, like in the Knuth-Morris-Pratt algorithm, <code>needle.findIn(haystack)</code> (or <code>pattern.findIn(text)</code>)makes sense, because the needle object holds the intermediate tables created for the algorithm to work effectively</p></li>\n<li><p>If the haystack needs pre-processing, like say in a trie, the <code>haystack.find(needle)</code> (or <code>words.hasAWordWithPrefix(prefix)</code>) works better.</p></li>\n</ol>\n\n<p>In both the above cases, one of needle or haystack is aware of the search. Also, they both are aware of each other. If you want the needle and haystack not to be aware of each other or of the search, <code>searcher.find(needle, haystack)</code> would be appropriate.</p>\n" }, { "answer_id": 49082, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>Is the code trying to find a specific needle or just any needle? It sounds like a stupid question, but it changes the problem.</p>\n\n<p>Looking for a specific needle the code in the question makes sense. Looking for any needle it would be more like</p>\n\n<pre><code>needle = haystack.findNeedle()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>needle = searcher.findNeedle(haystack)\n</code></pre>\n\n<p>Either way, I prefer having a searcher that class. A haystack doesn't know how to search. From a CS perspective it is just a data store with LOTS of crap that you don't want. </p>\n" }, { "answer_id": 49133, "author": "jklp", "author_id": 3847, "author_profile": "https://Stackoverflow.com/users/3847", "pm_score": 3, "selected": false, "text": "<p>If both Needle and Haystack are DAOs, then options 1 and 2 are out of the question.</p>\n\n<p>The reason for this is that DAOs should only be responsible for holding properties of the real world objects they are modeling, and only have getter and setter methods (or just direct property access). This makes serializing the DAOs to a file, or creating methods for a generic compare / generic copy easier to write, as the code wouldn't contain a whole bunch of \"if\" statements to skip these helper methods. </p>\n\n<p>This just leaves option 3, which most would agree to be correct behaviour. </p>\n\n<p>Option 3 has a few advantages, with the biggest advantage being unit testing. This is because both Needle and Haystack objects can be easily mocked up now, whereas if option 1 or 2 were used, the internal state of either Needle or Haystack would have to be modified before a search could be performed. </p>\n\n<p>Secondly, with the searcher now in a separate class, all search code can be held in one place, including common search code. Whereas if the search code was put into the DAO, common search code would either be stored in a complicated class hierarchy, or with a Searcher Helper class anyway. </p>\n" }, { "answer_id": 52336, "author": "Jimmy Chandra", "author_id": 5321, "author_profile": "https://Stackoverflow.com/users/5321", "pm_score": 1, "selected": false, "text": "<p>haystack can contain stuffs\none type of stuff is needle\nfinder is something that is responsible for searching of stuff\nfinder can accept a pile of stuffs as the source of where to find thing\nfinder can also accept a stuff description of thing that it need to find</p>\n\n<p>so, preferably, for a flexible solution you would do something like:\nIStuff interface</p>\n\n<p>Haystack = IList&lt;IStuff&gt;\nNeedle : IStuff</p>\n\n<p>Finder\n .Find(IStuff stuffToLookFor, IList&lt;IStuff&gt; stuffsToLookIn)</p>\n\n<p>In this case, your solution will not get tied to just needle and haystack but it is usable for any type that implement the interface</p>\n\n<p>so if you want to find a Fish in the Ocean, you can.</p>\n\n<p>var results = Finder.Find(fish, ocean)</p>\n" }, { "answer_id": 60803, "author": "user6246", "author_id": 6246, "author_profile": "https://Stackoverflow.com/users/6246", "pm_score": 2, "selected": false, "text": "<p>The answer to this question should actually depend on the domain the solution is implemented for.<br>\nIf you happen to simulate a physical search in a physical haystack, you might have the classes </p>\n\n<ul>\n<li>Space </li>\n<li>Straw </li>\n<li>Needle</li>\n<li>Seeker</li>\n</ul>\n\n<p><strong>Space</strong><br>\nknows which objects are located at which coordinates<br>\nimplements the laws of nature (converts energy, detects collisions, etc.) </p>\n\n<p><strong>Needle</strong>, <strong>Straw</strong><br>\nare located in Space<br>\nreact to forces </p>\n\n<p><strong>Seeker</strong><br>\ninteracts with space:<br>\n&nbsp;&nbsp;&nbsp;&nbsp;<em>moves hand, applies magnetic field, burns hay, applies x-rays, looks for needle</em>...</p>\n\n<p>Thus&nbsp;&nbsp;<code>seeker.find(needle, space)</code> &nbsp;&nbsp;or&nbsp;&nbsp; <code>seeker.find(needle, space, strategy)</code> </p>\n\n<p>The haystack just happens to be in the space where you are looking for the needle. When you abstract away space as a kind of virtual machine (think of: the matrix) you could get the above with haystack instead of space <em>(solution 3/3b)</em>: </p>\n\n<p><code>seeker.find(needle, haystack)</code> &nbsp;&nbsp;&nbsp;&nbsp;or&nbsp;&nbsp;&nbsp;&nbsp; <code>seeker.find(needle, haystack, strategy)</code> </p>\n\n<p>But the matrix was the Domain, which should only be replaced by haystack, if your needle couldn't be anywhere else. </p>\n\n<p>And then again, it was just an anology. Interestingly this opens the mind for totally new directions:<br>\n1. Why did you loose the needle in the first place? Can you change the process, so you wouldn't loose it?<br>\n2. Do you have to find the lost needle or can you simply get another one and forget about the first? (Then it would be nice, if the needle dissolved after a while)<br>\n3. If you loose your needles regularly and you need to find them again then you might want to </p>\n\n<ul>\n<li><p>make needles that are able to find themselves, e.g. they regularly ask themselves: Am I lost? If the answer is yes, they send their GPS-calculated position to somebody or start beeping or whatever:<br>\n<code>needle.find(space)</code> or <code>needle.find(haystack)</code>&nbsp;&nbsp;&nbsp; <em>(solution 1)</em> </p></li>\n<li><p>install a haystack with a camera on each straw, afterwards you can ask the haystack hive mind if it saw the needle lately:<br>\nhaystack.find(needle) <em>(solution 2)</em> </p></li>\n<li><p>attach RFID tags to your needles, so you can easily triangulate them</p></li>\n</ul>\n\n<p>That all just to say that in your implementation <em>you</em> made the needle and the haystack and most of the time the matrix on some kind of level. </p>\n\n<p>So decide according to your domain: </p>\n\n<ul>\n<li>Is it the purpose of the haystack to contain needles? Then go for solution 2. </li>\n<li>Is it natural that the needle gets lost just anywhere? Then go for solution 1. </li>\n<li>Does the needle get lost in the haystack by accident? Then go for solution 3. (or consider another recovering strategy)</li>\n</ul>\n" }, { "answer_id": 69227, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 2, "selected": false, "text": "<p>haystack.find(needle), but there should be a searcher field.</p>\n\n<p>I know that dependency injection is all the rage, so it doesn't surprise me that @Mike Stone's haystack.find(needle, searcher) has been accepted. But I disagree: the choice of what searcher is used seems to me a decision for the haystack. </p>\n\n<p>Consider two ISearchers: MagneticSearcher iterates over the volume, moving and stepping the magnet in a manner consistent with the magnet's strength. QuickSortSearcher divides the stack in two until the needle is evident in one of the subpiles. The proper choice of searcher may depend upon how large the haystack is (relative to the magnetic field, for instance), how the needle got into the haystack (i.e., is the needle's position truly random or it it biased?), etc. </p>\n\n<p>If you have haystack.find(needle, searcher), you're saying \"the choice of which is the best search strategy is best done outside the context of the haystack.\" I don't think that's likely to be correct. I think it's more likely that \"haystacks know how best to search themselves.\" Add a setter and you can still manually inject the searcher if you need to override or for testing.</p>\n" }, { "answer_id": 266251, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 1, "selected": false, "text": "<p>If you have a reference to needle object why do you search for it? :)\nThe problem domain and use-cases tell you that you do not need exact position of needle in a haystack (like what you could get from list.indexOf(element)), you just need a needle. And you do not have it yet. So my answer is something like this</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchByName(\"needle\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchWithFilter(new Filter(){\n public boolean isWhatYouNeed(Object obj)\n {\n return obj instanceof Needle;\n }\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Needle needle = (Needle)haystack.searchByPattern(Size.SMALL, \n Sharpness.SHARP, \n Material.METAL);\n</code></pre>\n\n<p>I agree that there are more possible solutions which are based on different search strategies, so they introduce searcher. There were anough comments on this, so I do not pay attentiont to it here. My point is solutions above forget about use-cases - what is the point to search for something if you already have reference to it? \nIn the most natural use-case you do not have a needle yet, so you do not use variable needle.</p>\n" }, { "answer_id": 287340, "author": "Jeff", "author_id": 23902, "author_profile": "https://Stackoverflow.com/users/23902", "pm_score": 0, "selected": false, "text": "<p>Definitely the third, IMHO.</p>\n\n<p>The question of a needle in a haystack is an example of an attempt to find one object in a large collection of others, which indicates it will need a complex search algorithm (possibly involving magnets or (more likely) child processes) and it doesn't make much sense for a haystack to be expected to do thread management or implement complex searches.</p>\n\n<p>A searching object, however, is dedicated to searching and can be expected to know how to manage child threads for a fast binary search, or use properties of the searched-for element to narrow the area (ie: a magnet to find ferrous items).</p>\n" }, { "answer_id": 287382, "author": "Varun Mahajan", "author_id": 6613, "author_profile": "https://Stackoverflow.com/users/6613", "pm_score": 0, "selected": false, "text": "<p>Another possible way can be to create two interfaces for Searchable object e.g. haystack and ToBeSearched object e.g. needle. \nSo, it can be done in this way </p>\n\n<pre><code>public Interface IToBeSearched\n{}\n\npublic Interface ISearchable\n{\n\n public void Find(IToBeSearched a);\n\n}\n\nClass Needle Implements IToBeSearched\n{}\n\nClass Haystack Implements ISearchable\n{\n\n public void Find(IToBeSearched needle)\n\n {\n\n //Here goes the original coding of find function\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1770119, "author": "Jason Orendorff", "author_id": 94977, "author_profile": "https://Stackoverflow.com/users/94977", "pm_score": 1, "selected": false, "text": "<p>Brad Wilson points out that objects should have a single responsibility. In the extreme case, an object has one responsibility and no state. Then it can become... a function.</p>\n\n<pre><code>needle = findNeedleIn(haystack);\n</code></pre>\n\n<p>Or you could write it like this:</p>\n\n<pre><code>SynchronizedHaystackSearcherProxyFactory proxyFactory =\n SynchronizedHaystackSearcherProxyFactory.getInstance();\nStrategyBasedHaystackSearcher searcher =\n new BasicStrategyBasedHaystackSearcher(\n NeedleSeekingStrategies.getMethodicalInstance());\nSynchronizedHaystackSearcherProxy proxy =\n proxyFactory.createSynchronizedHaystackSearcherProxy(searcher);\nSearchableHaystackAdapter searchableHaystack =\n new SearchableHaystackAdapter(haystack);\nFindableSearchResultObject foundObject = null;\nwhile (!HaystackSearcherUtil.isNeedleObject(foundObject)) {\n try {\n foundObject = proxy.find(searchableHaystack);\n } catch (GruesomeInjuryException exc) {\n returnPitchforkToShed(); // sigh, i hate it when this happens\n HaystackSearcherUtil.cleanUp(hay); // XXX fixme not really thread-safe,\n // but we can't just leave this mess\n HaystackSearcherUtil.cleanup(exc.getGruesomeMess()); // bug 510000884\n throw exc; // caller will catch this and get us to a hospital,\n // if it's not already too late\n }\n}\nreturn (Needle) BarnyardObjectProtocolUtil.createSynchronizedFindableSearchResultObjectProxyAdapterUnwrapperForToolInterfaceName(SimpleToolInterfaces.NEEDLE_INTERFACE_NAME).adapt(foundObject.getAdaptable());\n</code></pre>\n" }, { "answer_id": 11927019, "author": "Display Name", "author_id": 1418097, "author_profile": "https://Stackoverflow.com/users/1418097", "pm_score": 0, "selected": false, "text": "<pre><code>haystack.iterator.findFirst(/* pass here a predicate returning\n true if its argument is a needle that we want */)\n</code></pre>\n\n<p><code>iterator</code> can be interface to whatever immutable collection, with collections having common <code>findFirst(fun: T =&gt; Boolean)</code> method doing the job. As long as the haystack is immutable, no need to hide any useful data from \"outside\".\nAnd, of course, it's not good to tie together implementation of a custom non-trivial collection and some other stuff that does have <code>haystack</code>. Divide and conquer, okay?</p>\n" }, { "answer_id": 48103715, "author": "blizzrdof77", "author_id": 1313496, "author_profile": "https://Stackoverflow.com/users/1313496", "pm_score": 0, "selected": false, "text": "<p>In most cases I prefer to be able to perform simple helper operations like this on the core object, but depending on the language, the object in question may not have a sufficient or sensible method available.</p>\n\n<p>Even in languages like <a href=\"https://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">JavaScript</a>) that allow you to augment/extend built-in objects, I find it can be both convenient and problematic (e.g. if a future version of the language introduces a more efficient method that gets overridden by a custom one).</p>\n\n<p><a href=\"https://www.sitepoint.com/augmenting-javascript-core-objects-revisited/\" rel=\"nofollow noreferrer\">This article</a> does a good job of outlining such scenarios.</p>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives: ``` 1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack) ``` Which do you prefer, and why? I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world". In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?
Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate. You also have a fourth alternative that I think would be better than alternative 3: ``` haystack.find(needle, searcher) ``` In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on.
23,763
<p>I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.</p>
[ { "answer_id": 23795, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 3, "selected": false, "text": "<p>Let <code>Y = 0.3*R + 0.59*G + 0.11*B</code> for each pixel in the image, then set them to be</p>\n\n<p><code>((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)</code></p>\n\n<p>if <code>(R1,G1,B1)</code> is what you are colorizing with.</p>\n" }, { "answer_id": 27185, "author": "Bernie Perez", "author_id": 1992, "author_profile": "https://Stackoverflow.com/users/1992", "pm_score": 3, "selected": true, "text": "<p>I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a <strong><a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/image/LookupOp.html\" rel=\"nofollow noreferrer\">LookupOp</a>.</strong> Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage.</p>\n\n<p>Using Nicks example from above heres how I would do it.</p>\n\n<blockquote>\n <p>Let Y = 0.3*R + 0.59*G + 0.11*B for\n each pixel</p>\n \n <p>(R1,G1,B1) is what you are colorizing\n with</p>\n</blockquote>\n\n<pre><code>protected LookupOp createColorizeOp(short R1, short G1, short B1) {\n short[] alpha = new short[256];\n short[] red = new short[256];\n short[] green = new short[256];\n short[] blue = new short[256];\n\n int Y = 0.3*R + 0.59*G + 0.11*B\n\n for (short i = 0; i &lt; 256; i++) {\n alpha[i] = i;\n red[i] = (R1 + i*.3)/2;\n green[i] = (G1 + i*.59)/2;\n blue[i] = (B1 + i*.11)/2;\n }\n\n short[][] data = new short[][] {\n red, green, blue, alpha\n };\n\n LookupTable lookupTable = new ShortLookupTable(0, data);\n return new LookupOp(lookupTable, null);\n}\n</code></pre>\n\n<p>It creates a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImageOp.html\" rel=\"nofollow noreferrer\">BufferedImageOp</a> that will mask out each color if the mask boolean is true.</p>\n\n<p>Its simple to call too.</p>\n\n<pre><code>BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);\nBufferedImage targetImage = colorizeFilter.filter(sourceImage, null);\n</code></pre>\n\n<p>If this is not what your looking for I suggest you look more into BufferedImageOp's.</p>\n\n<p>This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.</p>\n" }, { "answer_id": 4720882, "author": "nwodb.com", "author_id": 579450, "author_profile": "https://Stackoverflow.com/users/579450", "pm_score": 1, "selected": false, "text": "<p>I wanted to do the exact same thing as the question poster wanted to do but the above conversion did not remove colors like the GIMP does (ie green with a red overlay made an unpleasant brown color etc). So I downloaded the source code for GIMP and converted the c code over to Java.</p>\n\n<p>Posting it in this thread just in case anyone else wants to do the same (since it is the first thread that comes up in Google). The conversion still changes the white color when it should not, it's probably a casting issue from double to int. The class converts a BufferedImage in-place.</p>\n\n<pre><code>public class Colorize {\n\npublic static final int MAX_COLOR = 256;\n\npublic static final float LUMINANCE_RED = 0.2126f;\npublic static final float LUMINANCE_GREEN = 0.7152f;\npublic static final float LUMINANCE_BLUE = 0.0722f;\n\ndouble hue = 180;\ndouble saturation = 50;\ndouble lightness = 0;\n\nint [] lum_red_lookup;\nint [] lum_green_lookup;\nint [] lum_blue_lookup;\n\nint [] final_red_lookup;\nint [] final_green_lookup;\nint [] final_blue_lookup;\n\npublic Colorize( int red, int green, int blue )\n{\n doInit();\n}\n\npublic Colorize( double t_hue, double t_sat, double t_bri )\n{\n hue = t_hue;\n saturation = t_sat;\n lightness = t_bri;\n doInit();\n}\n\npublic Colorize( double t_hue, double t_sat )\n{\n hue = t_hue;\n saturation = t_sat;\n doInit();\n}\n\npublic Colorize( double t_hue )\n{\n hue = t_hue;\n doInit();\n}\n\npublic Colorize()\n{\n doInit();\n}\n\nprivate void doInit()\n{\n lum_red_lookup = new int [MAX_COLOR];\n lum_green_lookup = new int [MAX_COLOR];\n lum_blue_lookup = new int [MAX_COLOR];\n\n double temp_hue = hue / 360f;\n double temp_sat = saturation / 100f;\n\n final_red_lookup = new int [MAX_COLOR];\n final_green_lookup = new int [MAX_COLOR];\n final_blue_lookup = new int [MAX_COLOR];\n\n for( int i = 0; i &lt; MAX_COLOR; ++i )\n {\n lum_red_lookup [i] = ( int )( i * LUMINANCE_RED );\n lum_green_lookup[i] = ( int )( i * LUMINANCE_GREEN );\n lum_blue_lookup [i] = ( int )( i * LUMINANCE_BLUE );\n\n double temp_light = (double)i / 255f;\n\n Color color = new Color( Color.HSBtoRGB( (float)temp_hue, \n (float)temp_sat, \n (float)temp_light ) );\n\n final_red_lookup [i] = ( int )( color.getRed() );\n final_green_lookup[i] = ( int )( color.getGreen() );\n final_blue_lookup [i] = ( int )( color.getBlue() );\n }\n}\n\npublic void doColorize( BufferedImage image )\n{\n int height = image.getHeight();\n int width;\n\n while( height-- != 0 )\n {\n width = image.getWidth();\n\n while( width-- != 0 )\n {\n Color color = new Color( image.getRGB( width, height ) );\n\n int lum = lum_red_lookup [color.getRed ()] +\n lum_green_lookup[color.getGreen()] +\n lum_blue_lookup [color.getBlue ()];\n\n if( lightness &gt; 0 )\n {\n lum = (int)((double)lum * (100f - lightness) / 100f);\n lum += 255f - (100f - lightness) * 255f / 100f;\n }\n else if( lightness &lt; 0 )\n {\n lum = (int)(((double)lum * lightness + 100f) / 100f);\n }\n\n Color final_color = new Color( final_red_lookup[lum],\n final_green_lookup[lum],\n final_blue_lookup[lum],\n color.getAlpha() );\n\n image.setRGB( width, height, final_color.getRGB() );\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 20411373, "author": "0circle0", "author_id": 3072177, "author_profile": "https://Stackoverflow.com/users/3072177", "pm_score": 2, "selected": false, "text": "<p>This works exactly like the Colorize function in GIMP and it preserves the transparency. I've also added a few things like Contrast and Brightness, Hue, Sat, and Luminosity - 0circle0 Google Me --> ' Sprite Creator 3'</p>\n\n<pre><code>import java.awt.Color;\nimport java.awt.image.BufferedImage;\n\npublic class Colorizer\n{\n public static final int MAX_COLOR = 256;\n\n public static final float LUMINANCE_RED = 0.2126f;\n public static final float LUMINANCE_GREEN = 0.7152f;\n public static final float LUMINANCE_BLUE = 0.0722f;\n\n double hue = 180;\n double saturation = 50;\n double lightness = 0;\n\n int[] lum_red_lookup;\n int[] lum_green_lookup;\n int[] lum_blue_lookup;\n\n int[] final_red_lookup;\n int[] final_green_lookup;\n int[] final_blue_lookup;\n\n public Colorizer()\n {\n doInit();\n }\n\n public void doHSB(double t_hue, double t_sat, double t_bri, BufferedImage image)\n {\n hue = t_hue;\n saturation = t_sat;\n lightness = t_bri;\n doInit();\n doColorize(image);\n }\n\n private void doInit()\n {\n lum_red_lookup = new int[MAX_COLOR];\n lum_green_lookup = new int[MAX_COLOR];\n lum_blue_lookup = new int[MAX_COLOR];\n\n double temp_hue = hue / 360f;\n double temp_sat = saturation / 100f;\n\n final_red_lookup = new int[MAX_COLOR];\n final_green_lookup = new int[MAX_COLOR];\n final_blue_lookup = new int[MAX_COLOR];\n\n for (int i = 0; i &lt; MAX_COLOR; ++i)\n {\n lum_red_lookup[i] = (int) (i * LUMINANCE_RED);\n lum_green_lookup[i] = (int) (i * LUMINANCE_GREEN);\n lum_blue_lookup[i] = (int) (i * LUMINANCE_BLUE);\n\n double temp_light = (double) i / 255f;\n\n Color color = new Color(Color.HSBtoRGB((float) temp_hue, (float) temp_sat, (float) temp_light));\n\n final_red_lookup[i] = (int) (color.getRed());\n final_green_lookup[i] = (int) (color.getGreen());\n final_blue_lookup[i] = (int) (color.getBlue());\n }\n }\n\n public void doColorize(BufferedImage image)\n {\n int height = image.getHeight();\n int width;\n\n while (height-- != 0)\n {\n width = image.getWidth();\n\n while (width-- != 0)\n {\n Color color = new Color(image.getRGB(width, height), true);\n\n int lum = lum_red_lookup[color.getRed()] + lum_green_lookup[color.getGreen()] + lum_blue_lookup[color.getBlue()];\n\n if (lightness &gt; 0)\n {\n lum = (int) ((double) lum * (100f - lightness) / 100f);\n lum += 255f - (100f - lightness) * 255f / 100f;\n }\n else if (lightness &lt; 0)\n {\n lum = (int) (((double) lum * (lightness + 100f)) / 100f);\n }\n Color final_color = new Color(final_red_lookup[lum], final_green_lookup[lum], final_blue_lookup[lum], color.getAlpha());\n image.setRGB(width, height, final_color.getRGB());\n }\n }\n }\n\n public BufferedImage changeContrast(BufferedImage inImage, float increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n for (int i = 0; i &lt; w; i++)\n {\n for (int j = 0; j &lt; h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n float fr, fg, fb;\n\n r = color.getRed();\n fr = (r - 128) * increasingFactor + 128;\n r = (int) fr;\n r = keep256(r);\n\n g = color.getGreen();\n fg = (g - 128) * increasingFactor + 128;\n g = (int) fg;\n g = keep256(g);\n\n b = color.getBlue();\n fb = (b - 128) * increasingFactor + 128;\n b = (int) fb;\n b = keep256(b);\n\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeGreen(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i &lt; w; i++)\n {\n for (int j = 0; j &lt; h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = color.getRed();\n g = keep256(color.getGreen() + increasingFactor);\n b = color.getBlue();\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeBlue(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i &lt; w; i++)\n {\n for (int j = 0; j &lt; h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = color.getRed();\n g = color.getGreen();\n b = keep256(color.getBlue() + increasingFactor);\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeRed(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i &lt; w; i++)\n {\n for (int j = 0; j &lt; h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n int r, g, b, a;\n r = keep256(color.getRed() + increasingFactor);\n g = color.getGreen();\n b = color.getBlue();\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public BufferedImage changeBrightness(BufferedImage inImage, int increasingFactor)\n {\n int w = inImage.getWidth();\n int h = inImage.getHeight();\n\n BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n\n for (int i = 0; i &lt; w; i++)\n {\n for (int j = 0; j &lt; h; j++)\n {\n Color color = new Color(inImage.getRGB(i, j), true);\n\n int r, g, b, a;\n\n r = keep256(color.getRed() + increasingFactor);\n g = keep256(color.getGreen() + increasingFactor);\n b = keep256(color.getBlue() + increasingFactor);\n a = color.getAlpha();\n\n outImage.setRGB(i, j, new Color(r, g, b, a).getRGB());\n }\n }\n return outImage;\n }\n\n public int keep256(int i)\n {\n if (i &lt;= 255 &amp;&amp; i &gt;= 0)\n return i;\n if (i &gt; 255)\n return 255;\n return 0;\n }\n}\n</code></pre>\n" } ]
2008/08/22
[ "https://Stackoverflow.com/questions/23763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.
I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a **[LookupOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/LookupOp.html).** Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage. Using Nicks example from above heres how I would do it. > > Let Y = 0.3\*R + 0.59\*G + 0.11\*B for > each pixel > > > (R1,G1,B1) is what you are colorizing > with > > > ``` protected LookupOp createColorizeOp(short R1, short G1, short B1) { short[] alpha = new short[256]; short[] red = new short[256]; short[] green = new short[256]; short[] blue = new short[256]; int Y = 0.3*R + 0.59*G + 0.11*B for (short i = 0; i < 256; i++) { alpha[i] = i; red[i] = (R1 + i*.3)/2; green[i] = (G1 + i*.59)/2; blue[i] = (B1 + i*.11)/2; } short[][] data = new short[][] { red, green, blue, alpha }; LookupTable lookupTable = new ShortLookupTable(0, data); return new LookupOp(lookupTable, null); } ``` It creates a [BufferedImageOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImageOp.html) that will mask out each color if the mask boolean is true. Its simple to call too. ``` BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1); BufferedImage targetImage = colorizeFilter.filter(sourceImage, null); ``` If this is not what your looking for I suggest you look more into BufferedImageOp's. This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.
23,787
<p>What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.</p> <p>Currently I use code like this:</p> <pre><code>// mObjList is a List&lt;MyObject&gt; MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } </code></pre> <p>or</p> <pre><code>// mObjList is a List&lt;MyObject&gt; bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } } </code></pre>
[ { "answer_id": 23794, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>Put the code in a method and you save a temporary and a <code>break</code> (and you recycle code, as a bonus):</p>\n\n<pre><code>T Find&lt;T&gt;(IEnumerable&lt;T&gt; items, Predicate&lt;T&gt; p) {\n foreach (T item in items)\n if (p(item))\n return item;\n\n return null;\n}\n</code></pre>\n\n<p>… but of course this method already exists anyway for Lists, even in .NET 2.0.</p>\n" }, { "answer_id": 23799, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>@ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber.</p>\n</blockquote>\n\n<p>In C# 2.0 you'd write:</p>\n\n<pre><code>result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });\n</code></pre>\n\n<p>3.0 knows lambdas:</p>\n\n<pre><code>result = mObjList.Find(x =&gt; x.ID == magicNumber);\n</code></pre>\n" }, { "answer_id": 23800, "author": "Todd", "author_id": 2572, "author_profile": "https://Stackoverflow.com/users/2572", "pm_score": 2, "selected": false, "text": "<p>Using a Lambda expression:</p>\n\n<pre><code>List&lt;MyObject&gt; list = new List&lt;MyObject&gt;();\n\n// populate the list with objects..\n\nreturn list.Find(o =&gt; o.Id == myCriteria);\n</code></pre>\n" }, { "answer_id": 23830, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>Evidently the performance hit of anonymous delegates is pretty significant.</p>\n\n<p>Test code:</p>\n\n<pre><code> static void Main(string[] args)\n {\n for (int kk = 0; kk &lt; 10; kk++)\n {\n List&lt;int&gt; tmp = new List&lt;int&gt;();\n for (int i = 0; i &lt; 100; i++)\n tmp.Add(i);\n int sum = 0;\n long start = DateTime.Now.Ticks;\n for (int i = 0; i &lt; 1000000; i++)\n sum += tmp.Find(delegate(int x) { return x == 3; });\n Console.WriteLine(\"Anonymous delegates: \" + (DateTime.Now.Ticks - start));\n\n\n start = DateTime.Now.Ticks;\n sum = 0;\n for (int i = 0; i &lt; 1000000; i++)\n {\n int match = 0;\n for (int j = 0; j &lt; tmp.Count; j++)\n {\n if (tmp[j] == 3)\n {\n match = tmp[j];\n break;\n }\n }\n sum += match;\n }\n Console.WriteLine(\"Classic C++ Style: \" + (DateTime.Now.Ticks - start));\n Console.WriteLine();\n }\n }\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Anonymous delegates: 710000\nClassic C++ Style: 340000\n\nAnonymous delegates: 630000\nClassic C++ Style: 320000\n\nAnonymous delegates: 630000\nClassic C++ Style: 330000\n\nAnonymous delegates: 630000\nClassic C++ Style: 320000\n\nAnonymous delegates: 610000\nClassic C++ Style: 340000\n\nAnonymous delegates: 630000\nClassic C++ Style: 330000\n\nAnonymous delegates: 650000\nClassic C++ Style: 330000\n\nAnonymous delegates: 620000\nClassic C++ Style: 330000\n\nAnonymous delegates: 620000\nClassic C++ Style: 340000\n\nAnonymous delegates: 620000\nClassic C++ Style: 400000\n</code></pre>\n\n<p>In every case, using anonymous delegates is about 100% slower than the other way.</p>\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/23787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: ``` // mObjList is a List<MyObject> MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } ``` or ``` // mObjList is a List<MyObject> bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } } ```
> > @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. > > > In C# 2.0 you'd write: ``` result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; }); ``` 3.0 knows lambdas: ``` result = mObjList.Find(x => x.ID == magicNumber); ```