qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
81,350 | <p>What are the private IP address ranges?</p>
| [{'answer_id': 81365, 'author': 'Sargun Dhillon', 'author_id': 10432, 'author_profile': 'https://Stackoverflow.com/users/10432', 'pm_score': 6, 'selected': True, 'text': '<p>You will find the answers to this in <a href="http://www.faqs.org/rfcs/rfc1918.html" rel="noreferrer">RFC 1918</a>. Though, I have listed them below for you.</p>\n\n<pre><code> 10.0.0.0 - 10.255.255.255 (10/8 prefix)\n 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)\n 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)\n</code></pre>\n\n<p>It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn\'t official RFC1918. Additional information about IPv4 addresses can be found in <a href="http://www.faqs.org/rfcs/rfc3300.html" rel="noreferrer">RFC 3300</a>. </p>\n\n<p>On the other hand IPv6 doesn\'t have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in <a href="http://www.faqs.org/rfcs/rfc4193.html" rel="noreferrer">RFC 4193</a>.</p>\n'}, {'answer_id': 81375, 'author': 'Muxa', 'author_id': 10793, 'author_profile': 'https://Stackoverflow.com/users/10793', 'pm_score': 2, 'selected': False, 'text': '<p>also, 169.254.0.0 - 169.254.255.255 are reserved for automatic private IP addressing. Refer to <a href="http://en.wikipedia.org/wiki/Link-local_address" rel="nofollow noreferrer">Link-local address wikipedia article</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11034/'] |
81,360 | <p>I cannot find an elegant way to get the return value from a stored procedure when using TableAdapters.</p>
<p>It appears the TableAdapter does not support SQL stored procedure return values when using a non-scalar stored procedure call. You'd expect the return value from the auto-generated function would be the return value from the stored procedure but it isn't (it is actually the number of rows affected). Although possible to use 'out' parameters and pass a variable as a ref to the auto generated functions it isn't a very clean solution.</p>
<p>I have seen some ugly hacks on the web to solve this, but no decent solution. Any help would be appreciated.</p>
| [{'answer_id': 81971, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 1, 'selected': False, 'text': '<p>The way to get the return value is to use a SqlParameter on the SqlCommand object which has its Direction set to ParameterDirection.ReturnValue. You should check the SelectCommand property of the TableAdapter after calling Fill.</p>\n'}, {'answer_id': 156145, 'author': 'Ty.', 'author_id': 8873, 'author_profile': 'https://Stackoverflow.com/users/8873', 'pm_score': 0, 'selected': False, 'text': '<p>I cannot say for certain because I have do not use TableAdapters, but you might need to look at your stored procedure and include the following around your procedure.</p>\n\n<pre><code>SET ROWCOUNT OFF\n\nBEGIN\n<Procedure Content>\nEND\n\nSET ROWCOUNT ON\n</code></pre>\n'}, {'answer_id': 158819, 'author': 'sharvell', 'author_id': 23095, 'author_profile': 'https://Stackoverflow.com/users/23095', 'pm_score': 1, 'selected': False, 'text': '<p><em>NOTE</em>: The way to go is using a SqlParameter where the Direction = ParameterDirection.ReturnValue</p>\n\n<p>With that said, as someone already mentioned SqlParameters, here is a dynamic method alternate using a DataSet. (if thats how you ride):</p>\n\n<p>Example SQL statement and C# as fallows:</p>\n\n<pre><code>string sql = @"DECLARE @ret int \n EXEC @ret = SP_DoStuff \'parm1\', \'parm2\'\n SELECT @ret as ret";\n\nDataSet ds = GetDatasetFromSQL(sql); //your sql to dataset code here...\n\nint resultCode = -1;\nint.TryParse(ds.Tables[ds.Tables.Count-1].Rows[0][0].ToString(), out resultCode); \n</code></pre>\n\n<p>The stored procedure results are loaded into a DataSet and will have as many DataTables as return select statements in the stored procedure.</p>\n\n<p>The last DataTable in the DataSet will have 1 row and 1 column that will contain the stored procedure return value.</p>\n'}, {'answer_id': 1049670, 'author': 'Chris Driver', 'author_id': 5217, 'author_profile': 'https://Stackoverflow.com/users/5217', 'pm_score': 1, 'selected': True, 'text': "<p>Closing this question as it appears return values aren't supported and there is no elegant workaround!</p>\n"}, {'answer_id': 1075006, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://blogs.msdn.com/smartclientdata/archive/2006/08/09/693113.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/smartclientdata/archive/2006/08/09/693113.aspx</a></p>\n'}, {'answer_id': 6301191, 'author': 'Eric Braun', 'author_id': 791980, 'author_profile': 'https://Stackoverflow.com/users/791980', 'pm_score': 0, 'selected': False, 'text': '<p>Actually, all you need to do is to return your final value from the stored procedure using a SELECT statement, not a RETURN statement. The result of the SELECT will be the return value. For example, if you simply make your sp exit statement "SELECT 1" then you\'ll get back a 1. Now just SELECT the actual scalar you want returned.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5217/'] |
81,361 | <p>I have set up a repository using SVN and uploaded projects. There are multiple users working on these projects. But, not everyone requires access to all projects. I want to set up user permissions for each project.</p>
<p>How can I achieve this?</p>
| [{'answer_id': 81396, 'author': 'Mladen Mihajlovic', 'author_id': 11421, 'author_profile': 'https://Stackoverflow.com/users/11421', 'pm_score': 2, 'selected': False, 'text': '<p>The best way is to set up Apache and to set the access through it. Check the <a href="http://svnbook.red-bean.com/" rel="nofollow noreferrer">svn book</a> for help. If you don\'t want to use Apache, you can also do minimalistic access control using svnserve.</p>\n'}, {'answer_id': 81457, 'author': 'Stephen Bailey', 'author_id': 15385, 'author_profile': 'https://Stackoverflow.com/users/15385', 'pm_score': 6, 'selected': False, 'text': '<p>In your <strong>svn\\repos\\YourRepo\\conf</strong> folder you will find two files, <strong>authz</strong> and <strong>passwd</strong>. These are the two you need to adjust.</p>\n\n<p>In the <strong>passwd</strong> file you need to add some usernames and passwords. I assume you have already done this since you have people using it:</p>\n\n<pre><code>[users]\nUser1=password1\nUser2=password2\n</code></pre>\n\n<p>Then you want to assign permissions accordingly with the <strong>authz</strong> file:</p>\n\n<p>Create the conceptual groups you want, and add people to it:</p>\n\n<pre><code>[groups]\nallaccess = user1\nsomeaccess = user2\n</code></pre>\n\n<p>Then choose what access they have from both the permissions and project level.</p>\n\n<p>So let\'s give our "all access" guys all access from the root:</p>\n\n<pre><code>[/]\n@allaccess = rw\n</code></pre>\n\n<p>But only give our "some access" guys read-only access to some lower level project:</p>\n\n<pre><code>[/someproject]\n@someaccess = r\n</code></pre>\n\n<p>You will also find some simple documentation in the <strong>authz</strong> and <strong>passwd</strong> files.</p>\n'}, {'answer_id': 81468, 'author': 'RB.', 'author_id': 15393, 'author_profile': 'https://Stackoverflow.com/users/15393', 'pm_score': 3, 'selected': False, 'text': '<p>Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.</p>\n\n<p>Assuming your repository is called "my_repo", and it is stored in C:\\svn_repos:</p>\n\n<ol>\n<li><p>Create a file called "passwd" in "C:\\svn_repos\\my_repo\\conf". This file should look like:</p>\n\n<pre><code>[Users]\nusername = password\njohn = johns_password\nsteve = steves_password\n</code></pre></li>\n<li><p>In C:\\svn_repos\\my_repo\\conf\\svnserve.conf set:</p>\n\n<pre><code>[general]\npassword-db = passwd\nauth-access=read\nauth-access=write\n</code></pre></li>\n</ol>\n\n<p>This will force users to log in to read or write to this repository.</p>\n\n<p>Follow these steps for each repository, only including the appropriate users in the <code>passwd</code> file for each repository.</p>\n'}, {'answer_id': 81711, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 3, 'selected': False, 'text': "<p>You can use svn+ssh:, and then it's based on access control to the repository at the given location.</p>\n\n<p>This is how I host a project group repository at my uni, where I can't set up anything else. Just having a directory that the group owns, and running svn-admin (or whatever it was) in there means that I didn't need to do any configuration.</p>\n"}, {'answer_id': 83418, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 5, 'selected': False, 'text': "<p>@Stephen Bailey </p>\n\n<p>To complete your answer, you can also delegate the user rights to the project manager, through a plain text file in your repository.</p>\n\n<p>To do that, you set up your SVN database with a default <code>authz</code> file containing the following:</p>\n\n<pre><code>###########################################################################\n# The content of this file always precedes the content of the\n# $REPOS/admin/acl_descriptions.txt file.\n# It describes the immutable permissions on main folders.\n###########################################################################\n[groups]\nsvnadmins = xxx,yyy,....\n\n[/]\n@svnadmins = rw\n* = r\n[/admin]\n@svnadmins = rw\n@projadmins = r\n* =\n\n[/admin/acl_descriptions.txt]\n@projadmins = rw\n</code></pre>\n\n<p>This default <code>authz</code> file authorizes the SVN administrators to modify a visible plain text file within your SVN repository, called <strong>'/admin/acl_descriptions.txt'</strong>, in which the SVN administrators or project managers will modify and register the users.</p>\n\n<p>Then you set up a pre-commit hook which will detect if the revision is composed of that file (and only that file). </p>\n\n<p>If it is, this hook's script will validate the content of your plain text file and check if each line is compliant with the SVN syntax.</p>\n\n<p>Then a post-commit hook will update the <code>\\conf\\authz</code> file with the <strong>concatenation</strong> of:</p>\n\n<ul>\n<li>the TEMPLATE <code>authz</code> file presented above</li>\n<li>the plain text file <code>/admin/acl_descriptions.txt</code></li>\n</ul>\n\n<p>The first iteration is done by the SVN administrator, who adds:</p>\n\n<pre><code>[groups]\nprojadmins = zzzz\n</code></pre>\n\n<p>He commits his modification, and that updates the <code>authz</code> file.</p>\n\n<p>Then the project manager 'zzzz' can add, remove or declare any group of users and any users he wants.\nHe commits the file and the <code>authz</code> file is updated.</p>\n\n<p><strong>That way, the SVN administrator does not have to individually manage any and all users for all SVN repositories</strong>.</p>\n"}, {'answer_id': 1793965, 'author': 'Chris Burgess', 'author_id': 43034, 'author_profile': 'https://Stackoverflow.com/users/43034', 'pm_score': 5, 'selected': False, 'text': "<p>One gotcha which caught me out:</p>\n\n<pre><code>[repos:/path/to/dir/] # this won't work\n</code></pre>\n\n<p>but</p>\n\n<pre><code>[repos:/path/to/dir] # this is right\n</code></pre>\n\n<p>You need to not include a trailing slash on the directory, or you'll see 403 for the OPTIONS request.</p>\n"}, {'answer_id': 61511926, 'author': 'bahrep', 'author_id': 761095, 'author_profile': 'https://Stackoverflow.com/users/761095', 'pm_score': 0, 'selected': False, 'text': '<p>Apache Subversion supports <a href="https://www.visualsvn.com/support/svnbook/serverconfig/pathbasedauthz/" rel="nofollow noreferrer">path-based authorization</a> that helps you configure granular permissions for user and group accounts on paths in your repositories (files or directories). Path-based authorization supports three access levels - No Access, Read Only and Read / Write.</p>\n\n<p>Path-based authorization permissions are stored in per-repository or per-server authorization files with a special syntax. Here is an example from SVNBook:</p>\n\n<pre><code>[calc:/branches/calc/bug-142]\nharry = rw\nsally = r\n</code></pre>\n\n<p>When you require a complex permission structure with many paths and accounts you can benefit from a GUI-based permission management tools provided by VisualSVN Server:</p>\n\n<ul>\n<li>Server administrators can manage user and group permissions via the VisualSVN Server Manager console or PowerShell,</li>\n<li>Non-admin users can manage permissions via RepoCfg.</li>\n</ul>\n\n<p><em>Repository permissions in VisualSVN Server Manager</em>\n<a href="https://i.stack.imgur.com/XjoMn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjoMn.png" alt="enter image description here"></a></p>\n\n<p><em>Repository permissions in PowerShell</em>\n<a href="https://i.stack.imgur.com/4DeLR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4DeLR.png" alt="enter image description here"></a></p>\n\n<p><em>Non-admin users can manage permissions via the RepoCfg tool</em>\n<a href="https://i.stack.imgur.com/RHPLJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RHPLJ.png" alt="enter image description here"></a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15425/'] |
81,376 | <p>Currently I am using NetTiers to generate my data access layer and service layer. I have been using NetTiers for over 2 years and have found it to be very useful. At some point I need to look at LINQ so my questions are...</p>
<ol>
<li>Has anyone else gone from NetTiers to LINQ To SQL?</li>
<li>Was this switch over a good or bad thing?</li>
<li>Is there anything that I should be aware of?</li>
<li>Would you recommend this switch?</li>
</ol>
<p>Basically I would welcome any thoughts
.</p>
| [{'answer_id': 81422, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 1, 'selected': False, 'text': "<p>NetTiers is very good for generating a heavy and robust DAL, and we use it internally for core libraries and frameworks.</p>\n\n<p>As I see it, LINQ (in all its incarnations, but specifically as I think you're asking to SQL) is fantastic for quick data access, and we generally use it for more agile cases.</p>\n\n<p>Both technologies are quite inflexible to change without regeneration of the code or dbml layer.</p>\n\n<p>That being said, used properly LINQ 2 SQL is quite a robust solution, and you might even start using it for future development due to it's ease of use, but I wouldn't throw away your current DAL for it - if it aint broke ...</p>\n"}, {'answer_id': 81529, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>My experience tells me that using by using linq you can get things done faster, however the actual actions to the database are slower.</p>\n\n<p>So... if you have a small database, i'll say go for it. If not, i would wait for some improvements before changing</p>\n"}, {'answer_id': 154525, 'author': 'Jason Jackson', 'author_id': 13103, 'author_profile': 'https://Stackoverflow.com/users/13103', 'pm_score': 2, 'selected': False, 'text': '<p>I tried to use Linq to SQL on a small project, thinking that I wanted something I could generate quickly. I ran into a lot of problems in the designer. For example, anytime you need to add a column to a table you basically have to remove and re-add the table definition in the designer. If you have set any properties on the table then you have to re-set those properties. For me this really slowed down the development process.</p>\n\n<p>LINQ to SQL itself is nice. I really like the extensibility. If they can improve the designer I might try it again. I think that the framework would benefit from a little more functionality aimed at a disconnected model like web development.</p>\n\n<p>Check out <a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" rel="nofollow noreferrer">Scott Guthrie\'s LINQ to SQL series</a> of blog posts for some great examples of how to use it.</p>\n'}, {'answer_id': 154553, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': 0, 'selected': False, 'text': "<p>I'm using LINQ to SQL on fairly large project right now (about 150 tables) and it is working out very well for me. The last ORM I used was IBatis and it worked well but took alot of legwork to get your mappings done. LINQ to SQL performs very well for me and so far has proved to be very easy to use out of the box. There are definately some differences you have to overcome in transition, but I would recommend it's use.</p>\n\n<p>Side note, I have never used or read about NetTiers so I won't discount it's effectiveness, but LINQ to SQL in general has proven to be an extremely viable ORM.</p>\n"}, {'answer_id': 185123, 'author': 'Steve T', 'author_id': 415, 'author_profile': 'https://Stackoverflow.com/users/415', 'pm_score': 4, 'selected': True, 'text': '<ol>\n<li>No</li>\n<li>See #1</li>\n<li>You should beware of standard abstraction overhead. Also it\'s very SQL Server based in it\'s current state.</li>\n<li>Are you using SQL Server, then maybe. If you are using LINQ for other things right now like over XML data (great), Object data, Datasets, then yes you should could switch to have a uniform data syntax for all of them. Like <a href="https://stackoverflow.com/questions/81376/should-i-start-using-linq-to-sql#81422">lagerdalek</a> mentioned if it ain\'t broke don\'t fix it.\nFrom the quick look at .netTiers Application Framework, I\'d say if you already have an investment with that solution it seems to give you much more than a simple Data Access Layer and you should stick with it.</li>\n</ol>\n\n<p>From my experience LINQ to SQL is a good solution for small-medium sized projects. It is an ORM which is a great way to enhance productivity. It also <strong><em>should</em></strong> give you another layer of abstraction that will allow you to change out the layer underneath for something else. The designer in Visual Studio (and I belive VS Express also) is very easy and simple to use. It gives you the common drag-drop and property-based editing of the object mappings. </p>\n\n<p>@ <a href="https://stackoverflow.com/questions/81376/should-i-start-using-linq-to-sql#154525">Jason Jackson</a> - The Designer does let you add properties by hand, however you need to specify the attributes for that property, but you do this once, it might take 3 minutes longer than the initial dragging of the table into the designer, however it is only necessary once per change in the database itself. This is not too different from other ORMs, however you are correct that they could make this much easier, and find only those properties that have changed, or even implement some kind of refactoring tool for such needs.</p>\n\n<p>Resources:</p>\n\n<ul>\n<li><a href="http://dotnet.org.za/hiltong/archive/2008/02/01/why-use-linq-to-sql-part-1-performance-considerations.aspx" rel="nofollow noreferrer">Why use LINQ to SQL?</a></li>\n<li><a href="http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx" rel="nofollow noreferrer">Scott Guthrie on LINQ to SQL</a></li>\n<li><a href="http://www.sidarok.com/web/blog/content/2008/05/02/10-tips-to-improve-your-linq-to-sql-application-performance.html" rel="nofollow noreferrer">10 Tips to Improve your LINQ to SQL Application Performance</a></li>\n<li><a href="http://www.davidhayden.com/blog/dave/archive/2007/09/28/LINQToSQLVisualStudio2008PerformanceUpdate.aspx" rel="nofollow noreferrer">LINQ To SQL and Visual Studio 2008 Performance Update</a></li>\n<li><a href="http://www.codeproject.com/KB/linq/performance_comparisons.aspx" rel="nofollow noreferrer">Performance Comparisons LINQ to SQL / ADO / C#</a></li>\n<li><a href="http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx" rel="nofollow noreferrer">LINQ to SQL 5 Minute Overview</a></li>\n</ul>\n\n<p>Note that <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx" rel="nofollow noreferrer">Parallel LINQ</a> is being developed to allow for much greater performance on multi-core machines.</p>\n'}, {'answer_id': 796006, 'author': 'Chris Conway', 'author_id': 2849, 'author_profile': 'https://Stackoverflow.com/users/2849', 'pm_score': 0, 'selected': False, 'text': "<p>Our team used to use NetTiers and found it to be useful. BUT... the more we used it, the more we found headaches and pain points with it. For example, anytime you make a change to the database, you need to re-generate the DAL with CodeSmith which involved:</p>\n\n<ul>\n<li>re-generating thousands of lines of code in 3 separate projects</li>\n<li>re-generating hundreds of stored procedures</li>\n</ul>\n\n<p>Maybe there are other ways of doing it, but this is what we had to do. The re-gen of the source code was ok, scary, but ok. The real issue came with the stored procedures. It didn't clean any unused stored procedures so if you removed a table from your schema and re-gened your DAL, the stored procedures for that table did not get removed. Also, this became quite a headache for database change scripts where we had to compare the old database structure to the new one and create a change script to update client installations. This script could run into the tens of thousands of lines of sql code and if there was an issue executing it, which there invariably was, it was quite a pain to resolve it.</p>\n\n<p>Then the light came on, NHibernate as an ORM. It certainly has a ramp-up time to it but it is well worth it. There is a ton of support for it so if there's something you need done, more than likely it's been done before. It is extremely flexible and allows you to control every aspect of it and then some. It is also becoming easier and easier to use. Fluent Nhibernate is up and coming as a great way to get rid of the xml mapping files that are needed and NHibernate Profiler provides an excellent interface to see what's going on behind the scenes to increase efficiency and remove redundancy.</p>\n\n<p>Moving from NetTiers to NHibernate has been painful, but in a good way. It has forced us to move into a better architecture and re-evaluate functional needs. NetTiers provided tons of data access code, get this entity by its id, get this other entity by its foreign key, get a tlist and vlist of this and that, but most of it was unnecessary and unused. NHibernate with a generic repository and custom repositories only where needed reduced tons of unused code and really increased readability and reliability.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15410/'] |
81,392 | <p>If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). </p>
<pre><code>byte a = 23;
byte b = 34;
byte c = a + b;
</code></pre>
<p>In this example, the compile error is on the third line.</p>
| [{'answer_id': 81394, 'author': 'Brad Richards', 'author_id': 7732, 'author_profile': 'https://Stackoverflow.com/users/7732', 'pm_score': 5, 'selected': True, 'text': '<p>Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.</p>\n\n<p>To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.</p>\n\n<pre>byte a = 23;\nbyte b = 34;\nbyte c = (byte) (a + b);</pre>\n\n<p>Here\'s a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)</p>\n\n<p>Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.</p>\n'}, {'answer_id': 81446, 'author': 'David Sykes', 'author_id': 3154, 'author_profile': 'https://Stackoverflow.com/users/3154', 'pm_score': 3, 'selected': False, 'text': '<p>The answer to your follow-up question is here: </p>\n\n<blockquote>\n <p>operands of type byte and short are automatically promoted to int before being handed to the operators</p>\n</blockquote>\n\n<p>So, in your example, <code>a</code> and <code>b</code> are both converted to an <code>int</code> before being handed to the + operator. The result of adding two <code>int</code>s together is also an <code>int</code>. Trying to then assign that <code>int</code> to a <code>byte</code> value causes the error because there is a potential loss of precision. By explicitly casting the result you are telling the compiler "I know what I am doing".</p>\n'}, {'answer_id': 81490, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 2, 'selected': False, 'text': "<p>I think, the matter is, that the JVM supports only two types of stack values: word sized and double word sized. </p>\n\n<p>Then they probably decided that they would need only one operation that works on word sized integers on the stack. So there's only iadd, imul and so on at bytecode level (and no operators for bytes and shorts).</p>\n\n<p>So you get an int value as the result of these operations which Java can't safely convert back to the smaller byte and short data types. So they force you to cast to narrow the value back down to byte/short.</p>\n\n<p>But in the end you are right: This behaviour is not consistent to the behaviour of ints, for example. You can without problem add two ints and get no error if the result overflows.</p>\n"}, {'answer_id': 81728, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 1, 'selected': False, 'text': "<p>The Java language always promotes arguments of arithmetic operators to int, long, float or double. So take the expression:</p>\n\n<pre><code>a + b\n</code></pre>\n\n<p>where a and b are of type byte. This is shorthand for:</p>\n\n<pre><code>(int)a + (int)b\n</code></pre>\n\n<p>This expression is of type int. It clearly makes sense to give an error when assigning an int value to a byte variable.</p>\n\n<p>Why would the language be defined in this way? Suppose a was 60 and b was 70, then a+b is -126 - integer overflow. As part of a more complicated expression that was expected to result in an int, this may become a difficult bug. Restrict use of byte and short to array storage, constants for file formats/network protocols and puzzlers.</p>\n\n<p>There is an interesting recording from JavaPolis 2007. James Gosling is giving an example about how complicated unsigned arithmetic is (and why it isn't in Java). Josh Bloch points out that his example gives the wrong example under normal signed arithmetic too. For understandable arithmetic, we need arbitrary precision.</p>\n"}, {'answer_id': 73372404, 'author': 'Dean', 'author_id': 8749628, 'author_profile': 'https://Stackoverflow.com/users/8749628', 'pm_score': 0, 'selected': False, 'text': '<p>In Java Language Specification (5.6.2 Binary Numeric Promotion):</p>\n<blockquote>\n<p>1 If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.</p>\n<p>2 Otherwise, if any expression is of type float, then the promoted type is float, and other expressions that are not of type float undergo widening primitive conversion to float.</p>\n<p>3 Otherwise, if any expression is of type long, then the promoted type is long, and other expressions that are not of type long undergo widening primitive conversion to long.</p>\n<p>4 Otherwise, none of the expressions are of type double, float, or long. In this case, the promoted type is int, and any expressions that are not of type int undergo widening primitive conversion to int.</p>\n</blockquote>\n<p>Your code belongs to case 4. variables <code>a</code> and <code>b</code> are both converted to an <code>int</code> before being handed to the <code>+</code> operator. The result of <code>+</code> operation is also of type <code>int</code> not <code>byte</code></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7732/'] |
81,404 | <p>Right now I have a database (about 2-3 GB) in PostgreSQL, which serves as a data storage to RoR/Python LAMP-like application.</p>
<p>What kind tools are there that are simple and robust enough for replication of the main database to a second machine?</p>
<p>I looked through some packages (Slony-I and etc.) but it would be great to hear real-life stories as well.</p>
<p>Right now I'm not concerned with load balancing and etc. I am thinking about using simple Write-Ahead-Log strategy for now.</p>
| [{'answer_id': 81596, 'author': 'Justin Cormack', 'author_id': 15495, 'author_profile': 'https://Stackoverflow.com/users/15495', 'pm_score': 2, 'selected': True, 'text': '<p>If you are not doing replication, Write ahead Logs are the simplest solution.</p>\n'}, {'answer_id': 4872087, 'author': 'eggie5', 'author_id': 304926, 'author_profile': 'https://Stackoverflow.com/users/304926', 'pm_score': 2, 'selected': False, 'text': '<p>If you can upgrade to pg 9 I would looking to streaming replication - very simple setup. Or if you can\'t upgrade you can just look at a hot-standby (which you can query to).</p>\n\n<p>See here: <a href="http://eggie5.com/15-setting-up-pg9-streaming-replication" rel="nofollow">http://eggie5.com/15-setting-up-pg9-streaming-replication</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11104/'] |
81,406 | <p>Which parsers are available for parsing C# code?</p>
<p>I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.</p>
| [{'answer_id': 81415, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.codeplex.com/csparser" rel="nofollow noreferrer">http://www.codeplex.com/csparser</a></p>\n'}, {'answer_id': 81427, 'author': 'Julien Hoarau', 'author_id': 12248, 'author_profile': 'https://Stackoverflow.com/users/12248', 'pm_score': 8, 'selected': True, 'text': '<p>Works on source code:</p>\n\n<ul>\n<li><a href="http://www.codeplex.com/csparser" rel="noreferrer">CSParser</a>:\nFrom C# 1.0 to 2.0, open-source</li>\n<li><a href="http://www.csharpparser.com/csparser.php" rel="noreferrer">Metaspec C# Parser</a>:\nFrom C# 1.0 to 3.0, commercial product (about 5000$)</li>\n<li><a href="http://www.sharprecognize.com/" rel="noreferrer">#recognize!</a>:\nFrom C# 1.0 to 3.0, commercial product (about 900€) (answer by <a href="https://stackoverflow.com/questions/81406/parser-for-c#185380">SharpRecognize</a>)</li>\n<li><a href="http://www.icsharpcode.net/OpenSource/SD/" rel="noreferrer">SharpDevelop Parser</a> (answer by <a href="https://stackoverflow.com/questions/81406/parser-for-c#81434">Akselsson</a>)</li>\n<li><a href="https://github.com/icsharpcode/NRefactory/" rel="noreferrer">NRefactory</a>:\nFrom C# 1.0 to 4.0 (+async), open-source, parser used in SharpDevelop. Includes semantic analysis.</li>\n<li><a href="http://www.inevitablesoftware.com/Products.aspx" rel="noreferrer">C# Parser and CodeDOM</a>:\nA complete C# 4.0 Parser, already support the C# 5.0 async feature. Commercial product (49$ to 299$) (answer by <a href="https://stackoverflow.com/questions/81406/parser-for-c/7631455#7631455">Ken Beckett</a>)</li>\n<li><a href="http://msdn.microsoft.com/en-us/roslyn" rel="noreferrer">Microsoft Roslyn CTP</a>:\nCompiler as a service. </li>\n</ul>\n\n<p>Works on assembly:</p>\n\n<ul>\n<li>System.Reflection</li>\n<li><a href="http://ccimetadata.codeplex.com/" rel="noreferrer">Microsoft Common Compiler Infrastructure</a>:\nFrom C# 1.0 to 3.0, Microsoft Public License. Used by <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9aeaa970-f281-4fb0-aba1-d59d7ed09772&displaylang=en" rel="noreferrer">Fxcop</a> and <a href="http://research.microsoft.com/en-us/projects/specsharp/" rel="noreferrer">Spec#</a></li>\n<li><a href="http://www.mono-project.com/Cecil" rel="noreferrer">Mono.Cecil</a>:\nFrom C# 1.0 to 3.0, open-source</li>\n</ul>\n\n<p>The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods)</p>\n\n<p>I personnaly recommend <strong>Mono.Cecil</strong> and <strong>NRefactory</strong>.</p>\n'}, {'answer_id': 81429, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.mono-project.com/" rel="noreferrer">Mono</a> (open source) includes C# compiler (and of course parser)</p>\n'}, {'answer_id': 81434, 'author': 'Akselsson', 'author_id': 8862, 'author_profile': 'https://Stackoverflow.com/users/8862', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.icsharpcode.net/OpenSource/SD/" rel="nofollow noreferrer">SharpDevelop</a>, an open source IDE, comes with a visitor-based code parser which works really well. It can be used independently of the IDE.</p>\n'}, {'answer_id': 81473, 'author': 'Hallgrim', 'author_id': 15454, 'author_profile': 'https://Stackoverflow.com/users/15454', 'pm_score': 2, 'selected': False, 'text': '<p>Consider to use reflection on a built binary instead of parsing the C# code directly. The reflection API is really easy to use and perhaps you can get all the information you need?</p>\n'}, {'answer_id': 186117, 'author': 'leppie', 'author_id': 15541, 'author_profile': 'https://Stackoverflow.com/users/15541', 'pm_score': -1, 'selected': False, 'text': '<p><a href="http://plas.fit.qut.edu.au/gppg/" rel="nofollow noreferrer">GPPG</a> might be of use, if you are willing to write your own parser (which is fun). </p>\n'}, {'answer_id': 231082, 'author': 'sbeskur', 'author_id': 10446, 'author_profile': 'https://Stackoverflow.com/users/10446', 'pm_score': 2, 'selected': False, 'text': '<p>Have a look at <a href="http://www.devincook.com/goldparser/" rel="nofollow noreferrer">Gold Parser</a>. It has a very intuitive IU that lets you interactively test your grammar and generate C# code. There are plenty of examples available with it and it is completely free.</p>\n'}, {'answer_id': 2214810, 'author': 'Dinis Cruz', 'author_id': 262379, 'author_profile': 'https://Stackoverflow.com/users/262379', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve implemented just what you are asking (AST Parsing of C# code) at the <a href="http://www.owasp.org/index.php/OWASP_O2_Platform" rel="nofollow noreferrer">OWASP O2 Platform</a> project using SharpDevelop AST APIs. </p>\n\n<p>In order to make it easier to consume I wrote a quick API that exposes a number of key source code elements (using statements, types, methods, properties, fields, comments) and is able to rewrite the original C# code into C# and into VBNET.</p>\n\n<p>You can see this API in action on this O2 XRule script file: <a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/DotNet/ascx_View_SourceCode_AST.cs.o2" rel="nofollow noreferrer">ascx_View_SourceCode_AST.cs.o2</a> . </p>\n\n<p>For example this is how you process a C# source code text and populate a number of TreeViews & TextBoxes:</p>\n\n<pre><code> public void updateView(string sourceCode)\n { \n var ast = new Ast_CSharp(sourceCode);\n ast_TreeView.show_Ast(ast);\n types_TreeView.show_List(ast.astDetails.Types, "Text");\n usingDeclarations_TreeView.show_List(ast.astDetails.UsingDeclarations,"Text");\n methods_TreeView.show_List(ast.astDetails.Methods,"Text");\n fields_TreeView.show_List(ast.astDetails.Fields,"Text");\n properties_TreeView.show_List(ast.astDetails.Properties,"Text");\n comments_TreeView.show_List(ast.astDetails.Comments,"Text");\n\n rewritenCSharpCode_SourceCodeEditor.setDocumentContents(ast.astDetails.CSharpCode, ".cs");\n rewritenVBNet_SourceCodeEditor.setDocumentContents(ast.astDetails.VBNetCode, ".vb"); \n }\n</code></pre>\n\n<p>The example on <a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/DotNet/ascx_View_SourceCode_AST.cs.o2" rel="nofollow noreferrer">ascx_View_SourceCode_AST.cs.o2</a> also shows how you can then use the information gathered from the AST to select on the source code a type, method, comment, etc..</p>\n\n<p>For reference here is the API code that wrote (note that this is my first pass at using SharpDevelop\'s C# AST parser, and I am still getting my head around how it works):</p>\n\n<ul>\n<li><a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2%20Modules%20Using%203rd%20Party%20Dlls/O2_External_SharpDevelop/AST/AstDetails.cs" rel="nofollow noreferrer">AstDetails.cs</a></li>\n<li><a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2%20Modules%20Using%203rd%20Party%20Dlls/O2_External_SharpDevelop/AST/AstTreeView.cs" rel="nofollow noreferrer">AstTreeView.cs</a></li>\n<li><a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2%20Modules%20Using%203rd%20Party%20Dlls/O2_External_SharpDevelop/AST/AstValue.cs" rel="nofollow noreferrer">AstValue.cs</a></li>\n<li><a href="http://code.google.com/p/o2platform/source/browse/trunk/O2%20-%20All%20Active%20Projects/O2%20Modules%20Using%203rd%20Party%20Dlls/O2_External_SharpDevelop/AST/Ast_CSharp.cs" rel="nofollow noreferrer">Ast_CSharp.cs</a></li>\n</ul>\n'}, {'answer_id': 2408588, 'author': 'Ira Baxter', 'author_id': 120163, 'author_profile': 'https://Stackoverflow.com/users/120163', 'pm_score': 0, 'selected': False, 'text': '<p>Not in C#, but a full C# 2/3/4 parser that builds full ASTs is available with our <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow noreferrer">DMS Software Reengineering Toolkit</a>.</p>\n\n<p>DMS provides a vast infrastructure for parsing, tree building, construction of symbol tables and flow analyses, source-to-source transformation, and regeneration of source code from the (modified) ASTs. (It also handles many other languages than just C#.)</p>\n\n<p>EDIT (September) 2013: This answer hasn\'t been updated recently. DMS has long handled C# 5.0</p>\n'}, {'answer_id': 2408671, 'author': 'zproxy', 'author_id': 94411, 'author_profile': 'https://Stackoverflow.com/users/94411', 'pm_score': 3, 'selected': False, 'text': '<p>If you are going to compile C# v3.5 to .net assemblies:</p>\n\n<pre><code>var cp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });\n</code></pre>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx</a></p>\n'}, {'answer_id': 3920241, 'author': 'prosseek', 'author_id': 260127, 'author_profile': 'https://Stackoverflow.com/users/260127', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re familiar with ANTLR, you can use <a href="http://antlrcsharp.codeplex.com/" rel="noreferrer">Antlr C# grammar</a>.</p>\n'}, {'answer_id': 4561545, 'author': 'SeeSoft', 'author_id': 556927, 'author_profile': 'https://Stackoverflow.com/users/556927', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe you could try with Irony on irony.codeplex.com.</p>\n\n<p>It\'s very fast and a c# grammar already exists.</p>\n\n<p>The grammar itself is written directly in c# in a BNF like way (acheived with some operators overloads)</p>\n\n<p>The best thing with it is that the "grammar" produces the AST directly.</p>\n'}, {'answer_id': 7631455, 'author': 'Ken Beckett', 'author_id': 910651, 'author_profile': 'https://Stackoverflow.com/users/910651', 'pm_score': 2, 'selected': False, 'text': '<p>We have recently released a C# parser that handles all C# 4.0 features plus the new async feature: <a href="http://www.inevitablesoftware.com/Products.aspx" rel="nofollow" title="C# Parser and CodeDOM">C# Parser and CodeDOM</a></p>\n\n<p>This library generates a semantic object model which retains comments and formatting information and can be modified and saved. It also supports the use of LINQ queries to analyze source code.</p>\n'}, {'answer_id': 11523386, 'author': 'Stéphane', 'author_id': 156415, 'author_profile': 'https://Stackoverflow.com/users/156415', 'pm_score': 0, 'selected': False, 'text': '<p>Something that is gaining momentum and very appropriate for the job is <a href="http://nemerle.org/" rel="nofollow">Nemerle</a> </p>\n\n<p>you can see how it could solve it in these videos from NDC : </p>\n\n<ul>\n<li><a href="http://vimeo.com/43690661" rel="nofollow">Igor Tkachev - Metaprogramming with Nemerle</a></li>\n<li><a href="http://vimeo.com/43588432" rel="nofollow">Igor Tkachev - Nemerle Programming Language</a></li>\n</ul>\n'}, {'answer_id': 23073744, 'author': 'Jason', 'author_id': 3534027, 'author_profile': 'https://Stackoverflow.com/users/3534027', 'pm_score': 2, 'selected': False, 'text': '<p>You should definitely check out Roslyn since MS just opened (or will soon open) the code with an Apache 2 license <a href="http://roslyn.codeplex.com/" rel="nofollow">here</a>. You can also check out a way to parse this info with this code from <a href="https://github.com/Zenoware/RoslynParser" rel="nofollow">GitHub</a>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12248/'] |
81,410 | <p>I've got a <a href="http://notebooks.readerville.com/" rel="noreferrer">site</a> that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?</p>
| [{'answer_id': 81505, 'author': 'matt lohkamp', 'author_id': 14026, 'author_profile': 'https://Stackoverflow.com/users/14026', 'pm_score': 4, 'selected': True, 'text': '<p>you could always petition wp to add your widget to their \'approved\' list, but who knows how long that would take. you\'re talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here\'s a classic ones to try:</p>\n\n<p>put the javascript in a weird place, like anywhere that executes a URL. for instance:</p>\n\n<pre><code><div style="background:url(\'javascript:alert(this);\');" />\n</code></pre>\n\n<p>sometimes the word \'javascript\' gets cut out, but occasionally you can sneak it through as java\\nscript, or something similar.</p>\n\n<p>sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters.</p>\n\n<p>sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.</p>\n'}, {'answer_id': 89760, 'author': 'Devin Reams', 'author_id': 16248, 'author_profile': 'https://Stackoverflow.com/users/16248', 'pm_score': 3, 'selected': False, 'text': '<p>From the official <a href="http://faq.wordpress.com/2006/05/07/javascript-can-i-use-that-on-my-blog/" rel="nofollow noreferrer">WordPress.com FAQ</a>:</p>\n\n<blockquote>\n <p>Javascript can be used for malicious purposes and while what you want to do is okay it does not mean all javascript will be okay.</p>\n</blockquote>\n\n<p>It goes on to remind the reader that both MySpace and LiveJournal had been affected by malicious Javascript and, therefore, will not be permitted (as it may be exploited by users with poor intentions). They can\'t risk it with amazingly large sites (think I Can Has Cheezburger, Anderson Cooper 360, Fox, etc.).</p>\n\n<p>If you think you have Javascript that would benefit WordPress.com you can <a href="http://wordpress.com/contact-support/" rel="nofollow noreferrer">contact them directly</a>.</p>\n'}, {'answer_id': 2510303, 'author': 'MLCWO', 'author_id': 301092, 'author_profile': 'https://Stackoverflow.com/users/301092', 'pm_score': 1, 'selected': False, 'text': '<p>There is not work around for it. Wordpress does not currently support Javascript. Sorry.</p>\n'}, {'answer_id': 3501756, 'author': 'naugtur', 'author_id': 173077, 'author_profile': 'https://Stackoverflow.com/users/173077', 'pm_score': 0, 'selected': False, 'text': '<p>Just find a good site about XSS if You really need that js to work. But if it works for You it works for anybody, and You post a tutorian on how to do an XSS attack on Your page with posts or comments. </p>\n\n<p>reference:\n<a href="http://ha.ckers.org/xss.html" rel="nofollow noreferrer">http://ha.ckers.org/xss.html</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6478/'] |
81,423 | <p>We have a client/server application with a rich client front end (in .Net) and also an administration portal (Asp.Net). Currently users have to sign on in both the rich client and on the website. We'd like to enable them to sign into the rich client, but not have to sign on to the website if they launch it from within the client. How can we do that?</p>
<p>Going the other way is less important, but would be nice if possible: signing on to the website, then not having to sign into the rich client.</p>
| [{'answer_id': 81435, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': "<p>You could add a token, to identify them, to the URL which opens the site.</p>\n\n<p>You'll have to add some security to the token: TTL, a hash, a salt</p>\n"}, {'answer_id': 81444, 'author': 'Muxa', 'author_id': 10793, 'author_profile': 'https://Stackoverflow.com/users/10793', 'pm_score': 4, 'selected': True, 'text': '<p>A possible solution is:</p>\n\n<ul>\n<li>sign-in to the rich client</li>\n<li>a random token is generated by the server and stored againsed the signed-in user</li>\n<li>rich client gets that token from the server</li>\n<li>that token is used in the url pointing to the website</li>\n<li>going to that url (using a link or a button from the rich client) will auto-login the user and reset the token</li>\n</ul>\n'}, {'answer_id': 87945, 'author': 'Luke', 'author_id': 14275, 'author_profile': 'https://Stackoverflow.com/users/14275', 'pm_score': 1, 'selected': False, 'text': '<p>Make sure there is a timeout on the token, say 2-5 minutes, to ensure it is authentic.</p>\n'}, {'answer_id': 88049, 'author': 'Andreas Petersson', 'author_id': 16542, 'author_profile': 'https://Stackoverflow.com/users/16542', 'pm_score': 2, 'selected': False, 'text': '<p>simple token solutions suffer from a design flaw: you will have some sort of secret that can be reverse-engineered if wanted. this can be avoided entirely if dome correct.</p>\n\n<p>i would propose a challenge-response algorithm.</p>\n\n<p>*) user loggs in to rich client with pw</p>\n\n<p>*) from salt+password a sha256 or similar hash is calculated. (Hash A)</p>\n\n<p>*) user klicks "go to website" link.</p>\n\n<p>*) a http response is started (such as as a webservice), user fetches "get ticket number" for user account. this ticket will be valid for a short time (some minutes)</p>\n\n<p>*) client calculates hash(HashA+ticket) HashB</p>\n\n<p>*) finally - browser is pointed to www.example.org/?username=donkey&key=99754106633f94d350db34d548d6091a</p>\n\n<p>*) server checks if his calculated hash is the same as the one submitted.</p>\n\n<p>advantages of this method:</p>\n\n<p>-server never knows password, only salted hash.</p>\n\n<p>-even the hash is never transmitted through the wire -> no replay attacks.</p>\n'}, {'answer_id': 88095, 'author': 'andyuk', 'author_id': 2108, 'author_profile': 'https://Stackoverflow.com/users/2108', 'pm_score': 2, 'selected': False, 'text': '<p>How about <a href="http://oauth.net/" rel="nofollow noreferrer">OAuth</a>?</p>\n\n<blockquote>\n <p>An open protocol to allow secure API\n authorization in a simple and\n standard method from desktop and web\n applications.</p>\n</blockquote>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1727/'] |
81,445 | <p>Currently, we're using a wiki at work to share insights, tips and information. But somehow, people aren't sharing snippets that way. It's probably too inconvenient to write and too difficult to find snippets there.</p>
<p>So, is there a multi-user/collaborative snippets manager around? Something like <a href="http://code.google.com/p/snippely/" rel="nofollow noreferrer">Snippely</a>. (Has anyone tried Snippely in multi-user mode?)</p>
<ul>
<li>Since we're all on the same site, it would probably be best if it used mapped network drives or ODBC instead of its own server process.</li>
<li>Oh, and it has to support Unicode and let us choose any truetype font. We're using the hideous APL language, which uses <a href="http://en.wikipedia.org/wiki/APL_(programming_language)#APL_symbols_and_keyboard_layout" rel="nofollow noreferrer">special characters</a>.</li>
<li>It would be nice if it didn't cost money, so I wouldn't have to convince management to pay for it as well as the other developers to use it.</li>
</ul>
| [{'answer_id': 83415, 'author': 'scunliffe', 'author_id': 6144, 'author_profile': 'https://Stackoverflow.com/users/6144', 'pm_score': 2, 'selected': True, 'text': '<p><strong>Pastebin</strong> is a common solution to this. Just install somewhere on your network, then paste snippets. <a href="http://pastebin.com/" rel="nofollow noreferrer">http://pastebin.com/</a></p>\n\n<p>Works well when trying to debug a piece of code, or stack trace also.</p>\n'}, {'answer_id': 85963, 'author': 'deadprogrammer', 'author_id': 556, 'author_profile': 'https://Stackoverflow.com/users/556', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s Snip-it pro ( <a href="http://www.snipitpro.com" rel="nofollow noreferrer">http://www.snipitpro.com</a> ), I looked at it a while back, and the interface seemed to be pretty horrible. It\'s 40 bucks / seat, which is not too bad. Last time I was looking for a tool like that I found nothing at all, and I found that it\'s very hard to get my co-workers to start using snippet libraries - everybody is happy to google it or search their old codebases. These days I use Evernote for all of my own snippeting needs.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12534/'] |
81,448 | <p>In Oracle, what is the difference between :</p>
<pre><code>CREATE TABLE CLIENT
(
NAME VARCHAR2(11 BYTE),
ID_CLIENT NUMBER
)
</code></pre>
<p>and</p>
<pre><code>CREATE TABLE CLIENT
(
NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11)
ID_CLIENT NUMBER
)
</code></pre>
| [{'answer_id': 81465, 'author': 'Matthias Kestenholz', 'author_id': 317346, 'author_profile': 'https://Stackoverflow.com/users/317346', 'pm_score': 5, 'selected': False, 'text': '<p>One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.</p>\n\n<p>See also <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n'}, {'answer_id': 81469, 'author': 'Seldaek', 'author_id': 6512, 'author_profile': 'https://Stackoverflow.com/users/6512', 'pm_score': 2, 'selected': False, 'text': '<p>I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.</p>\n\n<p>Also those field types might be treated differently in regard to accented characters or case, for example \'binaryField(ete) = "été"\' will not match while \'charField(ete) = "été"\' might (again not sure about Oracle).</p>\n'}, {'answer_id': 81492, 'author': 'David Sykes', 'author_id': 3154, 'author_profile': 'https://Stackoverflow.com/users/3154', 'pm_score': 9, 'selected': True, 'text': '<p>Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.</p>\n\n<p>If you define the field as <code>VARCHAR2(11 BYTE)</code>, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.</p>\n\n<p>By defining the field as <code>VARCHAR2(11 CHAR)</code> you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.</p>\n'}, {'answer_id': 81714, 'author': 'user15453', 'author_id': 15453, 'author_profile': 'https://Stackoverflow.com/users/15453', 'pm_score': 4, 'selected': False, 'text': '<p>Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:</p>\n\n<ol>\n<li>Limits field to 11 <b>BYTE</b></li>\n<li>Limits field to 11 <b>CHAR</b>acters</li>\n</ol>\n\n<p><hr/>\nConclusion: 1 CHAR is not equal to 1 BYTE.<br/><br/></p>\n'}, {'answer_id': 67398489, 'author': 'Aman Singh Rajpoot', 'author_id': 12937828, 'author_profile': 'https://Stackoverflow.com/users/12937828', 'pm_score': 1, 'selected': False, 'text': '<p>In simple words when you write <code>NAME VARCHAR2(11 BYTE)</code> then only 11 Byte can be accommodated in that variable.</p>\n<p>No matter which characters set you are using, for example, if you are using Unicode (UTF-16) then only half of the size of Name can be accommodated in <code>NAME</code>.</p>\n<p>On the other hand, if you write <code>NAME VARCHAR2(11 CHAR)</code> then <code>NAME</code> can accommodate 11 CHAR regardless of their character encoding.</p>\n<p><code>BYTE</code> is the default if you do not specify <code>BYTE</code> or <code>CHAR</code></p>\n<p>So if you write <code>NAME VARCHAR2(4000 BYTE)</code> and use Unicode(UTF-16) character encoding then only 2000 characters can be accommodated in <code>NAME</code></p>\n<p>That means the size limit on the variable is applied in <code>BYTES</code> and it depends on the character encoding that how many characters can be accommodated in that vraible.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12388/'] |
81,449 | <p>In a server-side application running on Tomcat, I am generating full HTML pages (with header) based on random user-requested sites pulled down from the Internet. The client-side application uses asynchronous callbacks for requesting processing of a particular web page. Since processing can take a while, I want to inform the user about progress via polling, hence the callbacks.</p>
<p>On server-side, after the web page is retrieved, it is processed and an "enhanced" version is created. Then this version has to go back to the user.
Displaying the page as part of the page of the client-side application is not an option.</p>
<p>Currently, the server generates a temporary file and sends back a link to it. This is clearly suboptimal.</p>
<p>The next best solution I can come up with inolves creating a caching-DB that stores the HTML content together with its md5-sums or sha1-ids and then sends back a link to a servlet, with the hash-ID as an argument. The servlet then requests the site from the caching-DB.</p>
<p>Is there any better solution? If not, which DB-backend would you propose? I'm thinking of SQLite. Part of the problem to be solved is: how do I push a page <code><html></code> to <code></html></code> back to client side?</p>
| [{'answer_id': 81465, 'author': 'Matthias Kestenholz', 'author_id': 317346, 'author_profile': 'https://Stackoverflow.com/users/317346', 'pm_score': 5, 'selected': False, 'text': '<p>One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.</p>\n\n<p>See also <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n'}, {'answer_id': 81469, 'author': 'Seldaek', 'author_id': 6512, 'author_profile': 'https://Stackoverflow.com/users/6512', 'pm_score': 2, 'selected': False, 'text': '<p>I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.</p>\n\n<p>Also those field types might be treated differently in regard to accented characters or case, for example \'binaryField(ete) = "été"\' will not match while \'charField(ete) = "été"\' might (again not sure about Oracle).</p>\n'}, {'answer_id': 81492, 'author': 'David Sykes', 'author_id': 3154, 'author_profile': 'https://Stackoverflow.com/users/3154', 'pm_score': 9, 'selected': True, 'text': '<p>Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.</p>\n\n<p>If you define the field as <code>VARCHAR2(11 BYTE)</code>, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.</p>\n\n<p>By defining the field as <code>VARCHAR2(11 CHAR)</code> you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.</p>\n'}, {'answer_id': 81714, 'author': 'user15453', 'author_id': 15453, 'author_profile': 'https://Stackoverflow.com/users/15453', 'pm_score': 4, 'selected': False, 'text': '<p>Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:</p>\n\n<ol>\n<li>Limits field to 11 <b>BYTE</b></li>\n<li>Limits field to 11 <b>CHAR</b>acters</li>\n</ol>\n\n<p><hr/>\nConclusion: 1 CHAR is not equal to 1 BYTE.<br/><br/></p>\n'}, {'answer_id': 67398489, 'author': 'Aman Singh Rajpoot', 'author_id': 12937828, 'author_profile': 'https://Stackoverflow.com/users/12937828', 'pm_score': 1, 'selected': False, 'text': '<p>In simple words when you write <code>NAME VARCHAR2(11 BYTE)</code> then only 11 Byte can be accommodated in that variable.</p>\n<p>No matter which characters set you are using, for example, if you are using Unicode (UTF-16) then only half of the size of Name can be accommodated in <code>NAME</code>.</p>\n<p>On the other hand, if you write <code>NAME VARCHAR2(11 CHAR)</code> then <code>NAME</code> can accommodate 11 CHAR regardless of their character encoding.</p>\n<p><code>BYTE</code> is the default if you do not specify <code>BYTE</code> or <code>CHAR</code></p>\n<p>So if you write <code>NAME VARCHAR2(4000 BYTE)</code> and use Unicode(UTF-16) character encoding then only 2000 characters can be accommodated in <code>NAME</code></p>\n<p>That means the size limit on the variable is applied in <code>BYTES</code> and it depends on the character encoding that how many characters can be accommodated in that vraible.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11797/'] |
81,451 | <p>I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through <code>db.TextProperty</code> and <code>db.BlobProperty</code>.</p>
<p>I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.</p>
| [{'answer_id': 81479, 'author': 'Guido', 'author_id': 12388, 'author_profile': 'https://Stackoverflow.com/users/12388', 'pm_score': 1, 'selected': False, 'text': '<p>You can not store files as there is not a traditional file system. You can only store them in their own DataStore (in a field defined as a <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html" rel="nofollow noreferrer">BlobProperty</a>)</p>\n\n<p>There is an example in the previous link:</p>\n\n<pre><code>class MyModel(db.Model):\n blob = db.BlobProperty()\n\nobj = MyModel()\nobj.blob = db.Blob( file_contents )\n</code></pre>\n'}, {'answer_id': 81489, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s no flat file storing in Google App Engine. Everything has to go in to the <a href="http://code.google.com/appengine/docs/datastore/" rel="nofollow noreferrer">Datastore</a> which is a bit like a relational database but not quite.</p>\n\n<p>You could store the files as <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#TextProperty" rel="nofollow noreferrer">TextProperty</a> or <a href="http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#BlobProperty" rel="nofollow noreferrer">BlobProperty</a> attributes.</p>\n\n<p>There is a 1MB limit on DataStore entries which may or may not be a problem.</p>\n'}, {'answer_id': 143798, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>There is a thread in Google Groups about it:</p>\n\n<p><a href="http://groups.google.com/group/google-appengine/browse_thread/thread/f9d0f22d8de8c025/bba32165e308dd13?lnk=gst&q=uploading+files#bba32165e308dd13" rel="noreferrer">Uploading Files</a></p>\n\n<p>With a lot of useful code, that discussion helped me very much in uploading files.</p>\n'}, {'answer_id': 173918, 'author': 'sastanin', 'author_id': 25450, 'author_profile': 'https://Stackoverflow.com/users/25450', 'pm_score': 6, 'selected': False, 'text': '<p>In fact, this question is answered in the App Egnine documentation. See an example on <a href="http://code.google.com/appengine/docs/images/usingimages.html#Uploading" rel="noreferrer">Uploading User Images</a>.</p>\n\n<p>HTML code, inside <form></form>:</p>\n\n<pre><input type="file" name="img"/></pre>\n\n<p>Python code:</p>\n\n<pre>class Guestbook(webapp.RequestHandler):\n def post(self):\n greeting = Greeting()\n if users.get_current_user():\n greeting.author = users.get_current_user()\n greeting.content = self.request.get("content")\n avatar = self.request.get("img")\n greeting.avatar = db.Blob(avatar)\n greeting.put()\n self.redirect(\'/\')</pre>\n'}, {'answer_id': 534354, 'author': 'Joe Petrini', 'author_id': 53488, 'author_profile': 'https://Stackoverflow.com/users/53488', 'pm_score': 2, 'selected': False, 'text': '<p>If your still having a problem, check you are using enctype in the form tag</p>\n\n<p>No:</p>\n\n<pre><code><form encoding="multipart/form-data" action="/upload">\n</code></pre>\n\n<p>Yes:</p>\n\n<pre><code><form enctype="multipart/form-data" action="/upload">\n</code></pre>\n'}, {'answer_id': 1240820, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Personally I found the tutorial described <a href="http://shogi-software.blogspot.com/2009/04/google-app-engine-and-file-upload.html" rel="nofollow noreferrer">here</a> useful when using the Java run time with GAE. For some reason, when I tried to upload a file using</p>\n\n<pre><code><form action="/testservelet" method="get" enctype="multipart/form-data">\n <div>\n Myfile:<input type="file" name="file" size="50"/>\n </div>\n\n <div>\n <input type="submit" value="Upload file">\n </div>\n</form>\n</code></pre>\n\n<p>I found that my HttpServlet class for some reason wouldn\'t accept the form with the \'enctype\' attribute. Removing it works, however, this means I can\'t upload any files.</p>\n'}, {'answer_id': 1987486, 'author': 'jbochi', 'author_id': 230636, 'author_profile': 'https://Stackoverflow.com/users/230636', 'pm_score': 3, 'selected': False, 'text': '<p>Google has released a service for storing large files. Have a look at <a href="http://code.google.com/appengine/docs/python/blobstore/" rel="nofollow noreferrer">blobstore API documentation</a>. If your files are > 1MB, you should use it.</p>\n'}, {'answer_id': 3050807, 'author': 'Bili', 'author_id': 331191, 'author_profile': 'https://Stackoverflow.com/users/331191', 'pm_score': 3, 'selected': False, 'text': '<p>I try it today, It works as following:</p>\n\n<p>my sdk version is 1.3.x</p>\n\n<p>html page:</p>\n\n<pre><code><form enctype="multipart/form-data" action="/upload" method="post" > \n<input type="file" name="myfile" /> \n<input type="submit" /> \n</form> \n</code></pre>\n\n<p>Server Code:</p>\n\n<pre><code>file_contents = self.request.POST.get(\'myfile\').file.read() \n</code></pre>\n'}, {'answer_id': 3545032, 'author': 'Honza Pokorny', 'author_id': 244182, 'author_profile': 'https://Stackoverflow.com/users/244182', 'pm_score': 0, 'selected': False, 'text': '<p>I have observed some strange behavior when uploading files on App Engine. When you submit the following form:</p>\n\n<pre><code><form method="post" action="/upload" enctype="multipart/form-data">\n <input type="file" name="img" />\n ...\n</form>\n</code></pre>\n\n<p>And then you extract the <code>img</code> from the request like this:</p>\n\n<pre><code>img_contents = self.request.get(\'img\')\n</code></pre>\n\n<p>The <code>img_contents</code> variable is a <code>str()</code> in Google Chrome, but it\'s unicode in Firefox. And as you now, the <code>db.Blob()</code> constructor takes a string and will throw an error if you pass in a unicode string. </p>\n\n<p>Does anyone know how this can be fixed?</p>\n\n<p>Also, what I find absolutely strange is that when I copy and paste the Guestbook application (with avatars), it works perfectly. I do everything exactly the same way in my code, but it just won\'t work. I\'m very close to pulling my hair out.</p>\n'}, {'answer_id': 4787543, 'author': '101010', 'author_id': 451007, 'author_profile': 'https://Stackoverflow.com/users/451007', 'pm_score': 7, 'selected': True, 'text': '<p>Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.</p>\n\n<p>A few things to notice:</p>\n\n<ol>\n<li>This code uses the <a href="http://code.google.com/appengine/docs/python/blobstore/" rel="noreferrer">BlobStore API</a></li>\n<li><p>The purpose of this line in the\nServeHandler class is to "fix" the\nkey so that it gets rid of any name\nmangling that may have occurred in\nthe browser (I didn\'t observe any in\nChrome)</p>\n\n<pre><code>blob_key = str(urllib.unquote(blob_key))\n</code></pre></li>\n<li><p>The "save_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens.</p>\n\n<pre><code>self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n</code></pre></li>\n</ol>\n\n<p>Good Luck!</p>\n\n<pre><code>import os\nimport urllib\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass MainHandler(webapp.RequestHandler):\n def get(self):\n upload_url = blobstore.create_upload_url(\'/upload\')\n self.response.out.write(\'<html><body>\')\n self.response.out.write(\'<form action="%s" method="POST" enctype="multipart/form-data">\' % upload_url)\n self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""")\n\n for b in blobstore.BlobInfo.all():\n self.response.out.write(\'<li><a href="/serve/%s\' % str(b.key()) + \'">\' + str(b.filename) + \'</a>\')\n\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n upload_files = self.get_uploads(\'file\')\n blob_info = upload_files[0]\n self.redirect(\'/\')\n\nclass ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, blob_key):\n blob_key = str(urllib.unquote(blob_key))\n if not blobstore.get(blob_key):\n self.error(404)\n else:\n self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)\n\ndef main():\n application = webapp.WSGIApplication(\n [(\'/\', MainHandler),\n (\'/upload\', UploadHandler),\n (\'/serve/([^/]+)?\', ServeHandler),\n ], debug=True)\n run_wsgi_app(application)\n\nif __name__ == \'__main__\':\n main()\n</code></pre>\n'}, {'answer_id': 11814685, 'author': 'vivek_jonam', 'author_id': 586836, 'author_profile': 'https://Stackoverflow.com/users/586836', 'pm_score': 0, 'selected': False, 'text': '<p>There is a way of using <strong>flat file system</strong>( Atleast in usage perspective)</p>\n\n<p>There is this <a href="http://code.google.com/p/gaevfs/" rel="nofollow"><strong>Google App Engine Virtual FileSystem project</strong></a>. that is implemented with the help of datastore and memcache APIs to emulate an ordinary filesystem. Using this library you can use in you project a <strong>similar filesystem access(read and write)</strong>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3834/'] |
81,459 | <p>If I understand correctly, <code>ClickOnce</code> only checks for prerequisites with the first install of an application through the setup.exe file that contains the prerequisite information. If the user opens the app in the future it will check for new versions, but it does not launch the setup.exe again, thus not checking for any NEW prerequisites that might have been added.</p>
<p>Is there any way to force ClickOnce to check the prerequisites again or does anyone have a good solution without asking the user to run the <code>setup.exe</code> again?</p>
| [{'answer_id': 82249, 'author': 'HAdes', 'author_id': 11989, 'author_profile': 'https://Stackoverflow.com/users/11989', 'pm_score': 5, 'selected': True, 'text': '<p>Unfortunately, your users will have to re-run the setup.exe to check and install all the new prerequisites that you have added.</p>\n\n<p>Applications deployed using ClickOnce only check for application updates (if enabled), not prerequisites as it\'s the bootstrapper\'s job to make sure all dependencies are installed before the application is installed.</p>\n\n<p>I found this at <a href="http://msdn.microsoft.com/en-us/library/h4k032e1.aspx" rel="noreferrer">Microsoft\'s site</a>:</p>\n\n<blockquote>\n <p>The Setup.exe (bootstrapper) is\n responsible for installing all\n dependencies before your application\n runs. This bootstrapper runs as a\n separate process that is independent\n of the ClickOnce run-time engine.</p>\n</blockquote>\n'}, {'answer_id': 93794, 'author': 'codeConcussion', 'author_id': 1321, 'author_profile': 'https://Stackoverflow.com/users/1321', 'pm_score': 2, 'selected': False, 'text': '<p>HAdes is correct. However, as long as your app can <em>start</em> without the new prerequisite, you have the option of checking for it in code.</p>\n\n<p>I had the exact same situation with Crystal Reports and ended up writing code to check if it was installed, download the installation files, and run it in the background. Definitely a pain, but the end result worked well.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15415/'] |
81,472 | <p>I am developing an ASP.NET mobile website using .NET 3.5 and mobile controls that come with the framework. I have a login form where the system will authenticate the user so he/she can access certain restricted pages. </p>
<p>In a standard ASP.NET website, I can use a session to store some flag after a user had logined, but I wonder can I do the same for the mobile version? Is session variable (or cookies) being support by those mobile device's browser? Is there any standard pratice also on doing authentication for mobile pages?</p>
| [{'answer_id': 81549, 'author': 'Davide Vosti', 'author_id': 1812, 'author_profile': 'https://Stackoverflow.com/users/1812', 'pm_score': 1, 'selected': False, 'text': "<p>Session variables are stored in the server so you can forget the device browser capabilities.</p>\n\n<p>I've not practice developing for mobile device, but 4 years ago I was using a service that used cookie authentication and the phone was not top-notch so... I think you can take for granted the cookie availability. Full futured browsers for mobile are taking on so... invest in the future, don't spend energy with old techologies soon to be deprecated...</p>\n\n<p>In my opinion, prefer cookie authentication, it's more standard, and you can save the cookie on the phone preventing further authentications....</p>\n"}, {'answer_id': 94301, 'author': 'Shane Breatnach', 'author_id': 10264, 'author_profile': 'https://Stackoverflow.com/users/10264', 'pm_score': 0, 'selected': False, 'text': '<p><p>You can indeed support cookie authentication but the only guaranteed way for it to work is to attach the cookie ID as part of the URL i.e. cookieless sessions. Yes, this is bad practice as it\'s ugly and very insecure and all modern phones support cookies.</p> <p>But some devices have cookie limitations and, what\'s more, some networks strip all cookie information from the HTTP headers that pass through their gateways even though the phone has no problems (NTT DoCoMo do this in Japan). It may not apply in your situation but it\'s something to keep in mind.</p></p>\n\n<p>Lucky for you ASP.NET does support cookieless sessions easily. In the app.config file:</p>\n\n<pre><code><sessionState cookieless="true" />\n</code></pre>\n\n<p>does the trick.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14790/'] |
81,484 | <p>I am using a <B> FTPS </b> connection to send a text file
<i>[this file will contain EDI(Electronic Data Interchange) information]</i>to a mailbox INOVIS.I have configured the system to open a FTPS connection and using the PUT command I write the file to a folder on the FTP server.
The problem is: what mode of file transfer should I use? How do I switch between modes?</p>
<p>Moreover which mode is the 'best-practice' to use when transferring file over FTPS connection.
If some one can provide me a small ftp script it would be helpful.</p>
| [{'answer_id': 81503, 'author': 'stephbu', 'author_id': 12702, 'author_profile': 'https://Stackoverflow.com/users/12702', 'pm_score': -1, 'selected': False, 'text': '<p>If you want an exact copy the data use binary mode - using ascii mode will assume the data is 7bit text (chars 0-127) and truncate any data outside of this range. Dates back to arcane 7bit networking days where ascii mode could save you time.</p>\n\n<p>In a globalized environment that we live in - such that it is quite common to find non-ascii characters e.g. foreign languages, currency symbols etc. - you should always use BINARY mode.</p>\n'}, {'answer_id': 81515, 'author': 'GodEater', 'author_id': 6756, 'author_profile': 'https://Stackoverflow.com/users/6756', 'pm_score': 0, 'selected': False, 'text': "<p>ASCII mode also makes file sharing of text files across different platforms more straightforward for end users. They won't have to worry about the default line ending (cr/lf versus just lf for example) since the ASCII mode will do that translation for them on the fly.</p>\n\n<p>For most file types you will ALWAYS want to use BINARY mode though.</p>\n"}, {'answer_id': 81523, 'author': 'Victor', 'author_id': 14514, 'author_profile': 'https://Stackoverflow.com/users/14514', 'pm_score': 1, 'selected': False, 'text': '<p>ASCII mode changes new line characters between unix and DOS formats. \\n to \\r\\n and viceversa.</p>\n'}, {'answer_id': 81528, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 0, 'selected': False, 'text': "<p>ACSII mode converts text files between UNIX and Windows formats based on the server and client platform (CR/LF vs LF), Binary doesn't. Of course, if you transfer nearly anything in ASCII mode that isn't text, it will probably be corrupted for that reason.</p>\n"}, {'answer_id': 81530, 'author': 'pilif', 'author_id': 5083, 'author_profile': 'https://Stackoverflow.com/users/5083', 'pm_score': 1, 'selected': False, 'text': "<p>Actually, ASCII/BINARY has nothing to do with the 8th bit. It's a convention for translating line endings.</p>\n\n<p>When you are on a windows machine talking to a Unix FTP server (FTPS or FTP - doesn't matter - the protocol is the same), the server will replace any <CR><LF>-Combination with <LF> before storing the file and consequently do the translation in reverse in case you get the file from the unix server.</p>\n\n<p>The idea behind ASCII mode is to convert the line endings to the respective endings of the target platform.</p>\n\n<p>As todays world seems to be converging to the unix convention (<LF>) and as nearly all of todays editors (aside of notepad) can easily handle Unix-Line-Endings, the days of ASCII mode are, indeed, numbered and I would by all means recommend to always use BINARY transfer mode.</p>\n\n<p>The prospect of having data altered in mid-transfer is somewhat frightening anyways.</p>\n"}, {'answer_id': 81545, 'author': 'PierreBdR', 'author_id': 7136, 'author_profile': 'https://Stackoverflow.com/users/7136', 'pm_score': -1, 'selected': False, 'text': '<p>For the FTP protocol, the ASCII transfer mode will consider the 8th bit of each of your character as insignificant and will use it for error checking. As for binary transfer mode, your data will be sent as is. Note that sending binary data in ASCII mode will (almost) always end up in data corruption. However, transferring ASCII data in binary mode will work as long as the sending and receiving systems use the 8th bit in the same way (in modern system the 8th bit should stay at 0 to prevent collision with extended ASCII charsets).</p>\n'}, {'answer_id': 235136, 'author': 'Darron', 'author_id': 22704, 'author_profile': 'https://Stackoverflow.com/users/22704', 'pm_score': 2, 'selected': False, 'text': "<p>Many of the other answers to this question are a collection of nearly correct to outright wrong information.</p>\n\n<p>ASCII mode means that the file should be converted to canonical text form on the wire. Among other things this means:</p>\n\n<ul>\n<li>NVT-ASCII character set. Even if the original file is in some other character set, such as ASCII, EBCDIC or UTF-8. Technically this disallows characters with the 8th bit set, but most implementations won't enforce this.</li>\n<li>CRLF line endings.</li>\n</ul>\n\n<p>EBCDIC mode means a similar set of rules, except that the data on the wire should be in EBCDIC.</p>\n\n<p>LOCAL mode allows sending data with a size other than 8 bits per byte.</p>\n\n<p>IMAGE (or BINARY) mode means that the data should be send without any changes. It is up to the user to ensure that the target system can understand the data once it arrives.</p>\n\n<p>Among other things, this means that the recommendation to use BINARY mode to send text data will fail if one of the systems involved doesn't use a ASCII based character set.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15460/'] |
81,491 | <p>Has anyone gotten VisualWorks running under OpenBSD? It's not an officially supported platform, but one of the Cincom guys was telling me that it should be able to run under a linux compatibility mode. How did you set it up?</p>
<p>I already have Squeak running without a problem, so I'm not looking for an alternative. I specifically need to run VisualWorks's Web Velocity for a project.</p>
<p>Thanks,</p>
| [{'answer_id': 82334, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>if you're wondering about setting up linux compatibility mode and you're running the GENERIC kernel:</p>\n\n<pre><code># sysctl kern.emul.linux=1\n</code></pre>\n\n<p>to enable at boot uncomment the kern.emul.linux=1 line in /etc/sysctl.conf</p>\n"}, {'answer_id': 959964, 'author': 'dwc', 'author_id': 57301, 'author_profile': 'https://Stackoverflow.com/users/57301', 'pm_score': 3, 'selected': True, 'text': '<p>See the <a href="http://www.openbsd.org/faq/" rel="nofollow noreferrer">OpenBSD FAQ</a>, specifically section <a href="http://www.openbsd.org/faq/faq9.html#Interact" rel="nofollow noreferrer">9.4 - Running Linux Binaries on OpenBSD</a>. </p>\n\n<p>Typically there are more steps needed then just <code>kern.emul.linux=1</code> unless you have statically linked (i.e. completely stand-alone) binaries. The good news is that packages exist that contain Linux libs, and they are easy to install. This is all detailed in the above link.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2766176/'] |
81,495 | <p>I'm writing a J2SE desktop application that requires one of its components to be pluggable. I've already defined the Java interface for this plugin. The user should be able to select at runtime (via the GUI) which implementation of this interface they want to use (e.g. in an initialisation dialog). I envisage each plugin being packaged as a JAR file containing the implementing class plus any helper classes it may require.</p>
<p>What's the best technology for doing this type of thing in a desktop Java app?</p>
| [{'answer_id': 81510, 'author': 'Andrew Swan', 'author_id': 10433, 'author_profile': 'https://Stackoverflow.com/users/10433', 'pm_score': 0, 'selected': False, 'text': '<p>One approach I\'m considering is having my application start up a lightweight OSGi container, which if I understand correctly would be able to discover what plugin JAR files exist in a designated folder, which in turn would let me list them for the user to choose from. Is this feasible?</p>\n\n<p>I also found <a href="http://www.deadman.ca/articles/pluggableArticle.html" rel="nofollow noreferrer">this article</a> by Richard Deadman, but it looks a little dated (2006?) and mentions neither OSGi (at least not by name) nor the <code>java.util.jar</code> package</p>\n'}, {'answer_id': 81513, 'author': 'Philip Helger', 'author_id': 15254, 'author_profile': 'https://Stackoverflow.com/users/15254', 'pm_score': 0, 'selected': False, 'text': '<p>Did you think of using OSGi as a plugin framework? With OSGi you are able to update/replace, load or unload your modules on demand.</p>\n'}, {'answer_id': 81540, 'author': 'Olaf Kock', 'author_id': 13447, 'author_profile': 'https://Stackoverflow.com/users/13447', 'pm_score': 1, 'selected': False, 'text': '<p>If you are "just" needing one component to be pluggable, it\'s enough to simply instantiate the classes based on meta information, e.g. read via a classloaders META-INF/ information from the various jars that are on your classpath or in a certain plugin directory.</p>\n\n<p>OSGi on the other hand provides means to structure your whole application. If you already have a large Desktop application that needs one part pluggable, this would be a steep learning curve. If you start blank with what will be a Desktop app, OSGi provides means to modularizing the whole application. It\'s about "isolation of components" and independence of modules. </p>\n\n<p>Apache Felix provides a nice start if you want to go down OSGi lane. It might look complicated and heavyweight, but that\'s only because one is not used to that level of isolation between modules. It used to be so easy to just call any public method...</p>\n'}, {'answer_id': 81558, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 2, 'selected': False, 'text': "<p>OSGI is certainly a valid way to go. But, assuming you dont need to unload to reload the plugin, it might be using a hammer to crack a nut. </p>\n\n<p>You could use the classes in 'java.util.jar' to scan each JAR file in your plugins folder and then use a 'java.net.URLClassLoader' to load in the correct one.</p>\n"}, {'answer_id': 82108, 'author': 'Riduidel', 'author_id': 15619, 'author_profile': 'https://Stackoverflow.com/users/15619', 'pm_score': 4, 'selected': True, 'text': '<p>After many tries for plugin-based Java architectures (what is precisely what you seem to look for), I finally found <a href="http://code.google.com/p/jspf/" rel="noreferrer">JSPF</a> to be the best solution for Java5 code. it do not have the huge needs of OSGI like solutions, but is instead rather easy to use.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10433/'] |
81,497 | <p>I need an encoder that can convert mp3 files to he-aac (aka aac+).
So far the best one I have found is <a href="http://www.nero.com/eng/down-ndaudio.php" rel="nofollow noreferrer">nero aac encoder</a> .
I have two problemes with it :
- Only one input format : wav . It is a little bit slow to transform mp3 files to wav and then to he-aac.
- a free license for <strong>non commercial</strong> use.</p>
<p>Too bad ffmpeg does not support he-aac ...
There is a commercial solution, <a href="https://flix.on2.com/" rel="nofollow noreferrer">on2 flix</a>, but it seems to be a golden hammer for the simple task I need to do.</p>
| [{'answer_id': 81537, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 4, 'selected': True, 'text': "<p>Nero AAC is the only one as far as I know. Even if FAAC supported HE-AAC it would be useless, since as an encoder its pretty awfully designed and its quality is not even competitive with LAME, let alone a good AAC encoder.</p>\n\n<p>Kostya on the FFMPEG team is currently working on an AAC encoder but it has a long way to go--its not ready for primetime with LC-AAC, let alone HE-AAC (its not even committed to the repository yet). The first step before anything will be to get the ffmpeg decoder to support HE-AAC; currently it can only be decoded through FAAD.</p>\n\n<p>I don't believe there is <em>any</em> HE-AAC encoder on any platform with a more permissive license than Nero's at this point in time.</p>\n"}, {'answer_id': 436512, 'author': 'catlan', 'author_id': 23028, 'author_profile': 'https://Stackoverflow.com/users/23028', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t have an idea about the quality, but I just found\n<a href="http://dgaapenc.berlios.de/en/" rel="nofollow noreferrer">enhAacPlusEnc</a></p>\n'}, {'answer_id': 440914, 'author': 'catlan', 'author_id': 23028, 'author_profile': 'https://Stackoverflow.com/users/23028', 'pm_score': 1, 'selected': False, 'text': '<p>Another encoder: <a href="http://teknoraver.net/software/mp4tools/" rel="nofollow noreferrer">mp4tools</a></p>\n'}, {'answer_id': 4600868, 'author': 'polemon', 'author_id': 414121, 'author_profile': 'https://Stackoverflow.com/users/414121', 'pm_score': 2, 'selected': False, 'text': "<p>I've been using <code>neroAacEnc</code> for quite a while now, and I'm largely satisfied with the results. If you're on Linux, making an <code>.AAC</code> file out of an <code>.MP3</code> or whatever else, is quite easy, all you need is a small wrapper script, that takes care of decoding into <code>.WAV</code> and after encoding, removes the <code>.WAV</code> file.</p>\n\n<p>Be advised: Converting from one lossy encoding to another further reduces quality. So when you can live with <code>.MP3</code> and you don't have lossless sources, you better stick to them.</p>\n\n<p>Here's a small script, that converts from <code>.FLAC</code>to <code>.AAC</code>, it accepts only <code>.FLAC</code> files as arguments:</p>\n\n<pre><code>#!/bin/zsh\n\nfor file in ${argv[*]}; do\n flac -d ${file}\n neroAacEnc -q 0.6 -if ${file%%.flac}.wav -of ${file%%.flac}.aac\n rm ${file%%.flac}.wav\ndone\n</code></pre>\n\n<p>This script is sequential, but it can be easily made into a multithreaded script.</p>\n"}, {'answer_id': 8120392, 'author': 'freechelmi', 'author_id': 1016264, 'author_profile': 'https://Stackoverflow.com/users/1016264', 'pm_score': 2, 'selected': False, 'text': '<p>There is an encoder called <code>accplus</code> which is under the GNU license <a href="http://ffmpeg.org/doxygen/trunk/libaacplus_8c-source.html" rel="nofollow">available here</a>.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11897/'] |
81,504 | <p>I had a discussion with a developer earlier today re identifying TCP packets going out on a particular interface with the same payload. He told me that the probability of finding a TCP packet that has an equal payload (even if the same data is sent out several times) is very low due to the way TCP packets are constructed at system level. I was aware this may be the case due to the system's MTU settings (usually 1500 bytes) etc., but what sort of probability stats am I really looking at? Are there any specific protocols that would make it easier identifying matching payloads?</p>
| [{'answer_id': 81865, 'author': 'mdec', 'author_id': 15534, 'author_profile': 'https://Stackoverflow.com/users/15534', 'pm_score': 2, 'selected': True, 'text': '<p>EDIT: Sorry, my original idea was ridiculous. </p>\n\n<p>You got me interested so I googled a little bit and found <a href="http://monkey.org/~jose/software/flowgrep/" rel="nofollow noreferrer">this</a>. If you wanted to write your own tool you would probably have to inspect each payload, the easiest way would probably be some sort of hash/checksum to check for identical payloads. Just make sure you are checking the payload, not the whole packet.</p>\n\n<p>As for the statistics I will have to defer to someone with greater knowledge on the workings of TCP.</p>\n'}, {'answer_id': 82178, 'author': 'Chris', 'author_id': 15578, 'author_profile': 'https://Stackoverflow.com/users/15578', 'pm_score': 2, 'selected': False, 'text': "<p>It is the protocol running over tcp that defines the uniqueness of the payload, not the tcp protocol itself.</p>\n\n<p>For example, you might naively think that HTTP requests would all be identical when asking for a server's home page, but the referrer and user agent strings make the payloads different.</p>\n\n<p>Similarly, if the response is dynamically generated, it may have a date header:</p>\n\n<p>Date: Fri, 12 Sep 2008 10:44:27 GMT</p>\n\n<p>So that will render the response payloads different. However, subsequent payloads may be identical, if the content is static.</p>\n\n<p>Keep in mind that the actual packets will be different because of differing sequence numbers, which are supposed to be incrementing and pseudorandom.</p>\n"}, {'answer_id': 82313, 'author': 'Desty', 'author_id': 2161072, 'author_profile': 'https://Stackoverflow.com/users/2161072', 'pm_score': 2, 'selected': False, 'text': '<p>Chris is right. More specifically, two or three pieces of information in the packet header should be different:</p>\n\n<ul>\n<li>the sequence number (which is\nintended to be unpredictable) which\nis increases with the number of\nbytes transmitted and received.</li>\n<li>the timestamp, a field containing two\ntimestamps (although this field is optional).</li>\n<li>the checksum, since both the payload <em>and header</em> are checksummed, including the changing sequence number.</li>\n</ul>\n'}, {'answer_id': 595544, 'author': 'jdizzle', 'author_id': 70603, 'author_profile': 'https://Stackoverflow.com/users/70603', 'pm_score': 1, 'selected': False, 'text': "<p>Sending the same PAYLOAD is probably fairly common (particularly if you're running some sort of network service). If you mean sending out the same tcp segment (header and all) or the whole network packet (ip and up), then the probability is substantially reduced.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/368855/'] |
81,512 | <p>I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them:</p>
<pre><code>var lists = ["pageitems","rowitems","columnitems"];
Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false });
Sortable.create("rowitems", { dropOnEmpty: true, containment: lists, constraint: false });
Sortable.create("columnitems", { dropOnEmpty: true, containment: lists, constraint: false });
</code></pre>
<p>How can I make it so that if the user drags all the items out of a list, they're able to put them back again? At the moment it won't allow items to be dragged onto an empty list.</p>
| [{'answer_id': 82201, 'author': 'mercutio', 'author_id': 1951, 'author_profile': 'https://Stackoverflow.com/users/1951', 'pm_score': 3, 'selected': True, 'text': "<p>Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need to set a minimum height, or some padding on the block.</p>\n"}, {'answer_id': 124415, 'author': 'Ross Morrissey', 'author_id': 6997, 'author_profile': 'https://Stackoverflow.com/users/6997', 'pm_score': -1, 'selected': False, 'text': '<p>Make sure your target list is styled float:left</p>\n\n<p>I had a similar experience today.</p>\n'}, {'answer_id': 2189260, 'author': 'Colby', 'author_id': 264910, 'author_profile': 'https://Stackoverflow.com/users/264910', 'pm_score': 1, 'selected': False, 'text': '<p>add dropOnEmpty:true to the options parameters.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
81,520 | <p>How can you suppress the <code>Terminated</code> message that comes up after you kill a
process in a bash script?</p>
<p>I tried <code>set +bm</code>, but that doesn't work.</p>
<p>I know another solution involves calling <code>exec 2> /dev/null</code>, but is that
reliable? How do I reset it back so that I can continue to see stderr?</p>
| [{'answer_id': 81539, 'author': 'Matthias Kestenholz', 'author_id': 317346, 'author_profile': 'https://Stackoverflow.com/users/317346', 'pm_score': 3, 'selected': False, 'text': '<p>Maybe detach the process from the current shell process by calling <code>disown</code>?</p>\n'}, {'answer_id': 81672, 'author': 'wnoise', 'author_id': 15464, 'author_profile': 'https://Stackoverflow.com/users/15464', 'pm_score': 5, 'selected': True, 'text': '<p>The short answer is that you can\'t. Bash always prints the status of foreground jobs. The monitoring flag only applies for background jobs, and only for interactive shells, not scripts.</p>\n\n<p>see notify_of_job_status() in jobs.c.</p>\n\n<p>As you say, you can redirect so standard error is pointing to /dev/null but then you miss any other error messages. You can make it temporary by doing the redirection in a subshell which runs the script. This leaves the original environment alone.</p>\n\n<pre><code>(script 2> /dev/null)\n</code></pre>\n\n<p>which will lose all error messages, but just from that script, not from anything else run in that shell.</p>\n\n<p>You can save and restore standard error, by redirecting a new filedescriptor to point there:</p>\n\n<pre><code>exec 3>&2 # 3 is now a copy of 2\nexec 2> /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2>&3 # restore stderr to saved\nexec 3>&- # close saved version\n</code></pre>\n\n<p>But I wouldn\'t recommend this -- the only upside from the first one is that it saves a sub-shell invocation, while being more complicated and, possibly even altering the behavior of the script, if the script alters file descriptors.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p><em>For more appropriate answer check answer given by <a href="https://stackoverflow.com/users/129332/mark-edgar">Mark Edgar</a></em></p>\n'}, {'answer_id': 4833055, 'author': 'clemep', 'author_id': 594384, 'author_profile': 'https://Stackoverflow.com/users/594384', 'pm_score': 1, 'selected': False, 'text': "<p>disown did exactly the right thing for me -- the exec 3>&2 is risky for a lot of reasons -- set +bm didn't seem to work inside a script, only at the command prompt</p>\n"}, {'answer_id': 4849503, 'author': 'MarcH', 'author_id': 317623, 'author_profile': 'https://Stackoverflow.com/users/317623', 'pm_score': 4, 'selected': False, 'text': '<p>Solution: use SIGINT (works only in non-interactive shells)</p>\n\n<p>Demo:</p>\n\n<pre><code>cat > silent.sh <<"EOF"\nsleep 100 &\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n</code></pre>\n\n<p><a href="http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798" rel="noreferrer">http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798</a></p>\n'}, {'answer_id': 5722874, 'author': 'Mark Edgar', 'author_id': 129332, 'author_profile': 'https://Stackoverflow.com/users/129332', 'pm_score': 7, 'selected': False, 'text': '<p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href="http://ss64.com/bash/kill.html" rel="noreferrer"><code>kill</code></a> command sends a signal and doesn\'t wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href="http://ss64.com/bash/wait.html" rel="noreferrer"><code>wait</code></a> was made specifically for this purpose.</p>\n\n<p>Here is very simple example that kills the most recent background command. (<a href="https://stackoverflow.com/a/5163260/117471">Learn more about $! here.</a>)</p>\n\n<pre><code>kill $!\nwait $! 2>/dev/null\n</code></pre>\n\n<p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p>\n\n<pre><code>kill $(jobs -rp)\nwait $(jobs -rp) 2>/dev/null\n</code></pre>\n\n<p>I was led here from <a href="https://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850">bash: silently kill background function process</a>.</p>\n'}, {'answer_id': 12198152, 'author': 'Ralph', 'author_id': 1636189, 'author_profile': 'https://Stackoverflow.com/users/1636189', 'pm_score': 2, 'selected': False, 'text': "<p>Is this what we are all looking for?</p>\n\n<p>Not wanted: </p>\n\n<pre><code>$ sleep 3 &\n[1] 234\n<pressing enter a few times....>\n$\n$\n[1]+ Done sleep 3\n$\n</code></pre>\n\n<p>Wanted:</p>\n\n<pre><code>$ (set +m; sleep 3 &)\n<again, pressing enter several times....>\n$\n$\n$\n$\n$\n</code></pre>\n\n<p>As you can see, no job end message. Works for me in bash scripts as well, also for killed background processes.</p>\n\n<p>'set +m' disables job control (see 'help set') for the current shell. So if you enter your command in a subshell (as done here in brackets) you will not influence the job control settings of the current shell. Only disadvantage is that you need to get the pid of your background process back to the current shell if you want to check whether it has terminated, or evaluate the return code.</p>\n"}, {'answer_id': 13223242, 'author': 'Coder of Salvation', 'author_id': 1659796, 'author_profile': 'https://Stackoverflow.com/users/1659796', 'pm_score': 2, 'selected': False, 'text': '<p>This also works for killall (for those who prefer it):</p>\n\n<pre class="lang-sh prettyprint-override"><code>killall -s SIGINT (yourprogram) \n</code></pre>\n\n<p>suppresses the message... I was running mpg123 in background mode.\nIt could only silently be killed by sending a ctrl-c (SIGINT) instead of a SIGTERM (default).</p>\n'}, {'answer_id': 15300185, 'author': 'phily', 'author_id': 2149422, 'author_profile': 'https://Stackoverflow.com/users/2149422', 'pm_score': 0, 'selected': False, 'text': '<p>Another way to disable job notifications is to place your command to be backgrounded in a <code>sh -c \'cmd &\'</code> construct.</p>\n\n<pre><code>#!/bin/bash\n# ...\npid="`sh -c \'sleep 30 & echo ${!}\' | head -1`"\nkill "$pid"\n# ...\n\n# or put several cmds in sh -c \'...\' construct\nsh -c \'\nsleep 30 &\npid="${!}"\nsleep 5 \nkill "${pid}"\n\'\n</code></pre>\n'}, {'answer_id': 16424178, 'author': 'J-o-h-n-', 'author_id': 2359158, 'author_profile': 'https://Stackoverflow.com/users/2359158', 'pm_score': 0, 'selected': False, 'text': "<p>Had success with adding '<code>jobs 2>&1 >/dev/null</code>' to the script, not certain if it will help anyone else's script, but here is a sample.</p>\n\n<pre><code> while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2>&1 >/dev/null\n sleep 3\n done\n</code></pre>\n"}, {'answer_id': 17257986, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>Simple:</p>\n\n<pre class="lang-sh prettyprint-override"><code>{ kill $! } 2>/dev/null\n</code></pre>\n\n<p>Advantage? can use any signal</p>\n\n<p>ex:</p>\n\n<pre class="lang-sh prettyprint-override"><code>{ kill -9 $PID } 2>/dev/null\n</code></pre>\n'}, {'answer_id': 48726125, 'author': 'Al Joslin', 'author_id': 2912739, 'author_profile': 'https://Stackoverflow.com/users/2912739', 'pm_score': -1, 'selected': False, 'text': '<p>I found that putting the kill command in a function and then backgrounding the function suppresses the termination output</p>\n\n<pre><code>function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &\n</code></pre>\n'}, {'answer_id': 66355103, 'author': 'James Z.M. Gao', 'author_id': 7704140, 'author_profile': 'https://Stackoverflow.com/users/7704140', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>Terminated</code> is logged by the default signal handler of bash 3.x and 4.x. Just trap the TERM signal at the very first of child process:</p>\n<pre class="lang-sh prettyprint-override"><code>#!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap \'exit 0\' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\nfoo &\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14437/'] |
81,521 | <p>I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations.</p>
<p>Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea?</p>
<p>I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly).</p>
| [{'answer_id': 81539, 'author': 'Matthias Kestenholz', 'author_id': 317346, 'author_profile': 'https://Stackoverflow.com/users/317346', 'pm_score': 3, 'selected': False, 'text': '<p>Maybe detach the process from the current shell process by calling <code>disown</code>?</p>\n'}, {'answer_id': 81672, 'author': 'wnoise', 'author_id': 15464, 'author_profile': 'https://Stackoverflow.com/users/15464', 'pm_score': 5, 'selected': True, 'text': '<p>The short answer is that you can\'t. Bash always prints the status of foreground jobs. The monitoring flag only applies for background jobs, and only for interactive shells, not scripts.</p>\n\n<p>see notify_of_job_status() in jobs.c.</p>\n\n<p>As you say, you can redirect so standard error is pointing to /dev/null but then you miss any other error messages. You can make it temporary by doing the redirection in a subshell which runs the script. This leaves the original environment alone.</p>\n\n<pre><code>(script 2> /dev/null)\n</code></pre>\n\n<p>which will lose all error messages, but just from that script, not from anything else run in that shell.</p>\n\n<p>You can save and restore standard error, by redirecting a new filedescriptor to point there:</p>\n\n<pre><code>exec 3>&2 # 3 is now a copy of 2\nexec 2> /dev/null # 2 now points to /dev/null\nscript # run script with redirected stderr\nexec 2>&3 # restore stderr to saved\nexec 3>&- # close saved version\n</code></pre>\n\n<p>But I wouldn\'t recommend this -- the only upside from the first one is that it saves a sub-shell invocation, while being more complicated and, possibly even altering the behavior of the script, if the script alters file descriptors.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p><em>For more appropriate answer check answer given by <a href="https://stackoverflow.com/users/129332/mark-edgar">Mark Edgar</a></em></p>\n'}, {'answer_id': 4833055, 'author': 'clemep', 'author_id': 594384, 'author_profile': 'https://Stackoverflow.com/users/594384', 'pm_score': 1, 'selected': False, 'text': "<p>disown did exactly the right thing for me -- the exec 3>&2 is risky for a lot of reasons -- set +bm didn't seem to work inside a script, only at the command prompt</p>\n"}, {'answer_id': 4849503, 'author': 'MarcH', 'author_id': 317623, 'author_profile': 'https://Stackoverflow.com/users/317623', 'pm_score': 4, 'selected': False, 'text': '<p>Solution: use SIGINT (works only in non-interactive shells)</p>\n\n<p>Demo:</p>\n\n<pre><code>cat > silent.sh <<"EOF"\nsleep 100 &\nkill -INT $!\nsleep 1\nEOF\n\nsh silent.sh\n</code></pre>\n\n<p><a href="http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798" rel="noreferrer">http://thread.gmane.org/gmane.comp.shells.bash.bugs/15798</a></p>\n'}, {'answer_id': 5722874, 'author': 'Mark Edgar', 'author_id': 129332, 'author_profile': 'https://Stackoverflow.com/users/129332', 'pm_score': 7, 'selected': False, 'text': '<p>In order to silence the message, you must be redirecting <code>stderr</code> <strong>at the time the message is generated</strong>. Because the <a href="http://ss64.com/bash/kill.html" rel="noreferrer"><code>kill</code></a> command sends a signal and doesn\'t wait for the target process to respond, redirecting <code>stderr</code> of the <code>kill</code> command does you no good. The bash builtin <a href="http://ss64.com/bash/wait.html" rel="noreferrer"><code>wait</code></a> was made specifically for this purpose.</p>\n\n<p>Here is very simple example that kills the most recent background command. (<a href="https://stackoverflow.com/a/5163260/117471">Learn more about $! here.</a>)</p>\n\n<pre><code>kill $!\nwait $! 2>/dev/null\n</code></pre>\n\n<p>Because both <code>kill</code> and <code>wait</code> accept multiple pids, you can also do batch kills. Here is an example that kills all background processes (of the current process/script of course).</p>\n\n<pre><code>kill $(jobs -rp)\nwait $(jobs -rp) 2>/dev/null\n</code></pre>\n\n<p>I was led here from <a href="https://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process/5722850">bash: silently kill background function process</a>.</p>\n'}, {'answer_id': 12198152, 'author': 'Ralph', 'author_id': 1636189, 'author_profile': 'https://Stackoverflow.com/users/1636189', 'pm_score': 2, 'selected': False, 'text': "<p>Is this what we are all looking for?</p>\n\n<p>Not wanted: </p>\n\n<pre><code>$ sleep 3 &\n[1] 234\n<pressing enter a few times....>\n$\n$\n[1]+ Done sleep 3\n$\n</code></pre>\n\n<p>Wanted:</p>\n\n<pre><code>$ (set +m; sleep 3 &)\n<again, pressing enter several times....>\n$\n$\n$\n$\n$\n</code></pre>\n\n<p>As you can see, no job end message. Works for me in bash scripts as well, also for killed background processes.</p>\n\n<p>'set +m' disables job control (see 'help set') for the current shell. So if you enter your command in a subshell (as done here in brackets) you will not influence the job control settings of the current shell. Only disadvantage is that you need to get the pid of your background process back to the current shell if you want to check whether it has terminated, or evaluate the return code.</p>\n"}, {'answer_id': 13223242, 'author': 'Coder of Salvation', 'author_id': 1659796, 'author_profile': 'https://Stackoverflow.com/users/1659796', 'pm_score': 2, 'selected': False, 'text': '<p>This also works for killall (for those who prefer it):</p>\n\n<pre class="lang-sh prettyprint-override"><code>killall -s SIGINT (yourprogram) \n</code></pre>\n\n<p>suppresses the message... I was running mpg123 in background mode.\nIt could only silently be killed by sending a ctrl-c (SIGINT) instead of a SIGTERM (default).</p>\n'}, {'answer_id': 15300185, 'author': 'phily', 'author_id': 2149422, 'author_profile': 'https://Stackoverflow.com/users/2149422', 'pm_score': 0, 'selected': False, 'text': '<p>Another way to disable job notifications is to place your command to be backgrounded in a <code>sh -c \'cmd &\'</code> construct.</p>\n\n<pre><code>#!/bin/bash\n# ...\npid="`sh -c \'sleep 30 & echo ${!}\' | head -1`"\nkill "$pid"\n# ...\n\n# or put several cmds in sh -c \'...\' construct\nsh -c \'\nsleep 30 &\npid="${!}"\nsleep 5 \nkill "${pid}"\n\'\n</code></pre>\n'}, {'answer_id': 16424178, 'author': 'J-o-h-n-', 'author_id': 2359158, 'author_profile': 'https://Stackoverflow.com/users/2359158', 'pm_score': 0, 'selected': False, 'text': "<p>Had success with adding '<code>jobs 2>&1 >/dev/null</code>' to the script, not certain if it will help anyone else's script, but here is a sample.</p>\n\n<pre><code> while true; do echo $RANDOM; done | while read line\n do\n echo Random is $line the last jobid is $(jobs -lp)\n jobs 2>&1 >/dev/null\n sleep 3\n done\n</code></pre>\n"}, {'answer_id': 17257986, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>Simple:</p>\n\n<pre class="lang-sh prettyprint-override"><code>{ kill $! } 2>/dev/null\n</code></pre>\n\n<p>Advantage? can use any signal</p>\n\n<p>ex:</p>\n\n<pre class="lang-sh prettyprint-override"><code>{ kill -9 $PID } 2>/dev/null\n</code></pre>\n'}, {'answer_id': 48726125, 'author': 'Al Joslin', 'author_id': 2912739, 'author_profile': 'https://Stackoverflow.com/users/2912739', 'pm_score': -1, 'selected': False, 'text': '<p>I found that putting the kill command in a function and then backgrounding the function suppresses the termination output</p>\n\n<pre><code>function killCmd() {\n kill $1\n}\n\nkillCmd $somePID &\n</code></pre>\n'}, {'answer_id': 66355103, 'author': 'James Z.M. Gao', 'author_id': 7704140, 'author_profile': 'https://Stackoverflow.com/users/7704140', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>Terminated</code> is logged by the default signal handler of bash 3.x and 4.x. Just trap the TERM signal at the very first of child process:</p>\n<pre class="lang-sh prettyprint-override"><code>#!/bin/sh\n\n## assume script name is test.sh\n\nfoo() {\n trap \'exit 0\' TERM ## here is the key\n while true; do sleep 1; done\n}\n\necho before child\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\nfoo &\npid=$!\n\nsleep 1 # wait trap is done\n\necho before kill\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\nkill $pid ## no need to redirect stdin/stderr\n\nsleep 1 # wait kill is done\n\necho after kill\nps aux | grep \'test\\.s[h]\\|slee[p]\'\n\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11436/'] |
81,533 | <p>I'm currently trying to improve the design of a legacy db and I have the following situation</p>
<p>Currently I have a table SalesLead in which we store the the LeadSource.</p>
<pre><code>Create Table SalesLead(
....
LeadSource varchar(20)
....
)
</code></pre>
<p>The Lead Sources are helpfully stored in a table.</p>
<pre><code>Create Table LeadSource (
LeadSourceId int, /*the PK*/
LeadSource varchar(20)
)
</code></pre>
<p>And so I just want to Create a foreign key from one to the other and drop the non-normalized column.</p>
<p>All standard stuff, I hope.</p>
<p>Here is my problem. I can't seem to get away from the issue that instead of writing</p>
<pre><code> SELECT * FROM SalesLead Where LeadSource = 'foo'
</code></pre>
<p>Which is totally unambiguous I now have to write </p>
<pre><code>SELECT * FROM SalesLead where FK_LeadSourceID = 1
</code></pre>
<p>or </p>
<pre><code>SELECT * FROM SalesLead
INNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId
where LeadSource.LeadSource = "foo"
</code></pre>
<p>Which breaks if we ever alter the content of the LeadSource field.</p>
<p>In my application when ever I want to alter the value of SalesLead's LeadSource I don't want to update from 1 to 2 (for example) as I don't want to have developers having to remember these <strong>magic numbers</strong>. The ids are arbitrary and should be kept so.</p>
<p><strong><em>How do I remove or negate the dependency on them in my app's code?</em></strong></p>
<p><strong>Edit</strong> Languages my solution will have to support</p>
<ul>
<li>.NET 2.0 + 3 (for what its worth asp.net, vb.net and c#)</li>
<li>vba (access)</li>
<li>db (MSSQL 2000)</li>
</ul>
<p><strong>Edit 2.0</strong> The join is fine is just that 'foo' may change on request to 'foobar' and I don't want to haul through the queries.</p>
| [{'answer_id': 81553, 'author': 'LohanJ', 'author_id': 11286, 'author_profile': 'https://Stackoverflow.com/users/11286', 'pm_score': 1, 'selected': False, 'text': '<p>Did you consider an updatable view? Depending on your database server and the integrity of your database design you will be able to create a view that, when its values change, in turn it will update the constituent tables.</p>\n'}, {'answer_id': 81565, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to de-normalize the table, simply add the LeadSource (Varchar) column to your SalesLead table, instead of using a FK or an ID.</p>\n\n<p>On the other hand, if your language has support for ENUM structures, the "magic numbers" should be safely stored in an enum, so you could: </p>\n\n<pre><code>SELECT * FROM SALESLEAD WHERE LeadSouce = (int) EnmLeadSource.Foo; //pseudocode\n</code></pre>\n\n<p>And your code will have a</p>\n\n<pre><code>public enum EnmLeadSource \n{\n Foo = 1,\n Bar = 2\n}\n</code></pre>\n\n<p>It is OK to remove some excessive normalization if this causes you more trouble than what it fixes. However, bear in mind that if you use a VARCHAR field (as oposed to a Magic Number) you must maintain consistency and it could be hard to localize later if you need multiple languages or cultures.</p>\n\n<p>The best approach after Normalization seems to be the usage of an Enum structure. It keeps the code clean and you can always pass enums across methods and functions. (I\'m assuming .NET here but in other languages as well)</p>\n\n<p><strong>Update</strong>: Since you\'re using .NET, the DB Backend is "irrelevant" if you\'re constructing a query through code. Imagine this function:</p>\n\n<pre><code>public void GiveMeSalesLeadGiven( EnmLeadSource thisLeadSource )\n{\n // Construct your string using the value of thisLeadSource \n}\n</code></pre>\n\n<p>In the table you\'ll have a LeadSource (INT) column. But the fact that it has 1,2 or N won\'t matter to you. If you later need to change foo to foobar, that can mean that:</p>\n\n<p>1) All the "number 1" have to be number "2". You\'ll have to update the table.\n2) Or You need Foo to now be number 2 and Bar number 1. You just change the Enum (but make sure that the table values remain consistent).</p>\n\n<p>The Enum is a very useful structure if properly used. </p>\n\n<p>Hope this helps.</p>\n'}, {'answer_id': 81570, 'author': 'pilif', 'author_id': 5083, 'author_profile': 'https://Stackoverflow.com/users/5083', 'pm_score': 0, 'selected': False, 'text': '<p>I really don\'t see your problem behind the join. </p>\n\n<p>Naturally, asking directly by the FK_LeadSourceID is wrong, but using the JOIN seems to be the right way to go as I masks changing IDs perfectly fine. If, for example, "foo" becomes 3 at one day (and you update the foreign key field), the last query you\'ve displayed will still work exactly the same.</p>\n\n<p>If you want to make the change to the schema without altering the current queries in the application, then a view encompassing this join is the way to go.</p>\n\n<p>Or if you fear that the join Syntax is non-intuitive, there\'s always the subselect...</p>\n\n<pre><code>SELECT * FROM SalesLead where FK_LeadSourceID = \n (SELECT LeadSourceID from LeadSource WHERE LeadSource = \'foo\')\n</code></pre>\n\n<p>but remember to keep an index on LeadSource.LeadSource - at least if you have a lot of them stored in the table.</p>\n'}, {'answer_id': 81623, 'author': 'Olaf Kock', 'author_id': 13447, 'author_profile': 'https://Stackoverflow.com/users/13447', 'pm_score': 0, 'selected': False, 'text': '<p>If you "improve design" by introducing new relations/tables, you\'ll certainly have the need for different entities. If so, you\'ll need to deal with their semantics. </p>\n\n<p>In the previous solution you were able to just update the LeadSource name to whatever you wanted in the appropriate SalesLead row. If you update the name in your new structure, you do so for all SalesLead rows.</p>\n\n<p>There is no way around dealing with these different semantics. You just have to do so. In order to make the tables easier to query, you might use views as already suggested, but I\'d expect them mostly for reporting purposes or backward compatibility, provided they are not updatable, because everybody updating this view would not be aware of changed semantics.</p>\n\n<p>If you dislike the join try\nSELECT * FROM SalesLead where LeadSourceId IN (SELECT Id FROM LeadSource WHERE LeadSource = \'foo\')</p>\n'}, {'answer_id': 81642, 'author': 'Seb Rose', 'author_id': 12405, 'author_profile': 'https://Stackoverflow.com/users/12405', 'pm_score': 0, 'selected': False, 'text': "<p>In a typical application the user would be presented with a list of Lead Sources (returned by querying the LeadSource table) and the subsequent SalesLead query would be dynamically created by the application based upon the user's selection.</p>\n\n<p>Your application appears to have some 'well known' lead sources that you need to write specific queries for. If this is the case, then add a third (unique) field to the LeadSource table that includes an invariant 'name' that you can use as the basis of your application's queries. </p>\n\n<p>This shifts the burden of magic-ness from a DB generated magic number (that may vary from installation to installation) to a system defined magic name (that is fixed by design).</p>\n"}, {'answer_id': 82185, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': '<p>There\'s a false dichotomy here.</p>\n\n<pre><code>SELECT * FROM SalesLead \nINNER JOIN LeadSource ON SalesLead.FK_LeadSourceID = LeadSource.LeadSourceId \nwhere LeadSource.LeadSource = "foo"\n</code></pre>\n\n<p>doesn\'t break any more than the original</p>\n\n<pre><code>SELECT * FROM SalesLead Where LeadSource = \'foo\'\n</code></pre>\n\n<p>when <code>foo</code> changes to <code>foobar</code>. Also, if you\'re using parameterized queries (and you really should be), you don\'t have to change anything when <code>foo</code> changes to <code>foobar</code>.</p>\n'}, {'answer_id': 82628, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 2, 'selected': False, 'text': '<p>Have you considered just not using an artificial key for the <code>LeadSource</code> table? Then you get to use <code>LeadSource</code> as the FK in <code>SalesLead</code>, which simplifies your queries while retaining the benefits of using a canonical set of values (the rows in <code>LeadSource</code>).</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
81,548 | <p>I am running blazeds on the server side. I would like to filter http requests using an http header. My goal is to send extra parameters to the server without changing the signatures of my blazeds services.</p>
<p>On the client side, I am using Flex <strong>RemoteObject</strong> methods. </p>
<p>With Flex WebService components, it is possible to set an http header using the property <strong>httpHeaders</strong>. I have not found anything similar on the RemoteObject class...</p>
| [{'answer_id': 81607, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>You might be trying to re-invent the wheel. Is there a reason you can't use the standard HTTP(s) authentication?</p>\n"}, {'answer_id': 133095, 'author': 'Verdant', 'author_id': 450527, 'author_profile': 'https://Stackoverflow.com/users/450527', 'pm_score': 1, 'selected': False, 'text': '<p>RemoteObject uses AMF as the data channel, and is managed in a completely different way than HttpService or WebService (which use Http). \nWhat you can do, is call <code>setCredentials(username,password)</code> and then capture this on the server side using the FlexLoginCommand (either the standard one for your container, or derive your own).\nLookup <code>setCredentials</code> and how you should handle this on both sides (client and server).</p>\n'}, {'answer_id': 776559, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>A reason I was thinking too to use http headers was for the server to be able to 'recognize' the flex client in the a context of service versionning.\nOn the server I can always build an indirection/proxy that would allow the different clients to only use 1 end point and route to the right adapter depending on the client version. \nThe question is on the client side. How would the server identify the flex client token or 'version'. One way is certainly via authentication. But, assuming there is not authentication involved?</p>\n"}, {'answer_id': 3156087, 'author': 'Radek', 'author_id': 380861, 'author_profile': 'https://Stackoverflow.com/users/380861', 'pm_score': 1, 'selected': False, 'text': '<p>I have similar problem, and I afraid there is no simple way to set HTTP header when using AMF. But I\'ve designed following solution.</p>\n\n<p>Flex uses HTTP to transfer AMF, but invokes it through browser interfaces, this allows you to set cookie. Just in document containing application invoke following JavaScript</p>\n\n<pre><code>document.cookie="clientVersion=1.0;expires=2100-01-01;path=/";\n</code></pre>\n\n<p>Browser should transfer it to server, and you can filter (problem will be if the user will have cookies turned off).</p>\n\n<p>Much more you can invoke JavaScript functions from Flex (more is here: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_4.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_4.html</a>).</p>\n'}, {'answer_id': 3178195, 'author': 'hongo', 'author_id': 383503, 'author_profile': 'https://Stackoverflow.com/users/383503', 'pm_score': 2, 'selected': False, 'text': '<p>I couldnt modify http request from flex, instead I can add custom headers to the <code>mx.messaging.messages.IMessage</code> that <code>RemoteObject</code> sends to the server and there, extending <code>flex.messaging.services.remoting.adapters.JavaAdapter</code> (used for accessing Spring beans), it\'s posible to read the header parameters and put them into the HTTPRequest.</p>\n\n<p>In the flex part, I had to extend <code>mx.rpc.AsyncRequest</code>:\ndeclares a new property "header" and overwrites invoke method that checks if there is a not null value for set the msg.headers.</p>\n\n<p>and <code>mx.rpc.remoting.mxml.RemoteObject</code>: \nthe constructor creates a new instance of our custom AsyncRequest and overwrite old <code>AsyncRequest</code> and it defines a <code>setHeaders</code> method that set the argument to the custom <code>AsyncRequest</code>.</p>\n\n<p><code>com.asfusion.mate.actions.builders.RemoteObjectInvoker</code> (extra :P): \nthis one reads the param declared in the Mate\'s map <code>RemoteObjectInvoker</code> and puts in the <code>RemoteObject</code> header.</p>\n\n<p>I hope it will be understandable (with my apache english xDDD)</p>\n\n<p>Bye. Agur!</p>\n'}, {'answer_id': 15371118, 'author': 'Marcelo Rodovalho', 'author_id': 1213594, 'author_profile': 'https://Stackoverflow.com/users/1213594', 'pm_score': -1, 'selected': False, 'text': "<p>You can debug the $GLOBALS in PHP to see that.\nI think this is in the </p>\n\n<pre><code>$GLOBALS['HTTP_RAW_POST_DATA'];\n</code></pre>\n\n<p>or you can simple do </p>\n\n<pre><code>file_get_contents('php://input');\n</code></pre>\n"}, {'answer_id': 26745792, 'author': 'yiotix', 'author_id': 2435139, 'author_profile': 'https://Stackoverflow.com/users/2435139', 'pm_score': 0, 'selected': False, 'text': "<p>We recently run into the same issue and this is how we added our custom headers without creating a subclass:</p>\n\n<pre><code>var operation:AbstractOperation = _remoteSession.getOperation('myRemoteOperation');\nvar async:AsyncRequest = operation.mx_internal::asyncRequest;\nasync.defaultHeaders = {my_header:'my_value'};\n</code></pre>\n\n<p>The AsyncRequest object is actually accessible via the operation object via the mx_internal namespace.</p>\n"}, {'answer_id': 29437014, 'author': 'Ronny Shibley', 'author_id': 3040886, 'author_profile': 'https://Stackoverflow.com/users/3040886', 'pm_score': 2, 'selected': False, 'text': '<p>This worked for me using BlazeDS and Spring-Flex 1.5.2</p>\n\n<p><strong>Flex:</strong></p>\n\n<pre><code>use namespace mx_internal;\n\nvar service:RemoteObject = new RemoteObject(destination);\nvar operation:Operation = service[functionName];\noperation.asyncRequest.defaultHeaders = {company:\'company\'};\n\nvar token:AsyncToken = operation.send();\n</code></pre>\n\n<p>Java Spring-Flex:</p>\n\n<pre><code>public class FlexJavaCustomAdapter extends JavaAdapter{\n @Override\n public Object invoke(Message message) {\n String locale = (String) message.getHeader("com.foo.locale"); \n return super.invoke(message);\n } \n}\n</code></pre>\n\n<p><strong>dispatcher-servlet.xml</strong></p>\n\n<pre><code><bean id="customAdapter" class="org.springframework.flex.core.ManageableComponentFactoryBean">\n <constructor-arg value="com.codefish.model.flex.FlexJavaCustomAdapter"/>\n </bean> \n\n <flex:message-broker id="_messageBroker" services-config-path="classpath*:/com/codefish/resources/spring/services-config.xml" > \n <flex:remoting-service default-adapter-id="customAdapter" \n default-channels="my-amf, my-secure-amf" />\n </flex:message-broker>\n</bean>\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11897/'] |
81,552 | <p>There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop. </p>
<p>I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0. </p>
| [{'answer_id': 81579, 'author': 'ageektrapped', 'author_id': 631, 'author_profile': 'https://Stackoverflow.com/users/631', 'pm_score': 5, 'selected': False, 'text': "<p>There's the <code>Dictionary</code> constructor that takes another <code>Dictionary</code>.</p>\n\n<p>You'll have to cast it <code>IDictionary</code>, but there is an <code>Add()</code> overload that takes <code>KeyValuePair<TKey, TValue></code>. You're still using foreach, though.</p>\n"}, {'answer_id': 81615, 'author': 'Oli', 'author_id': 12870, 'author_profile': 'https://Stackoverflow.com/users/12870', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re dealing with two existing objects, you might get some mileage with the CopyTo method: <a href="http://msdn.microsoft.com/en-us/library/cc645053.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc645053.aspx</a></p>\n\n<p>Use the Add method of the other collection (receiver) to absorb them.</p>\n'}, {'answer_id': 81624, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 0, 'selected': False, 'text': "<p>I don't understand, why not using the Dictionary( Dictionary ) (as suggested by ageektrapped ). </p>\n\n<p>Do you want to perform a Shallow Copy or a Deep Copy? (that is, both Dictionaries pointing to the same references or new copies of every object inside the new dictionary?)</p>\n\n<p>If you want to create a <em>new</em> Dictionary pointing to <em>new</em> objects, I think that the only way is through a <strong>foreach</strong>.</p>\n"}, {'answer_id': 81952, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 5, 'selected': True, 'text': "<p>There's nothing wrong with a for/foreach loop. That's all a hypothetical AddRange method would do anyway.</p>\n\n<p>The only extra concern I'd have is with memory allocation behaviour, because adding a large number of entries could cause multiple reallocations and re-hashes. There's no way to increase the capacity of an existing Dictionary by a given amount. You might be better off allocating a new Dictionary with sufficient capacity for both current ones, but you'd still need a loop to load at least one of them.</p>\n"}, {'answer_id': 84308, 'author': 'BFree', 'author_id': 15861, 'author_profile': 'https://Stackoverflow.com/users/15861', 'pm_score': 2, 'selected': False, 'text': '<p>For fun, I created this extension method to dictionary. This should do a deep copy wherever possible.</p>\n<pre><code>public static Dictionary<TKey, TValue> DeepCopy<TKey,TValue>(this Dictionary<TKey, TValue> dictionary)\n {\n Dictionary<TKey, TValue> d2 = new Dictionary<TKey, TValue>();\n\n bool keyIsCloneable = default(TKey) is ICloneable;\n bool valueIsCloneable = default(TValue) is ICloneable;\n\n foreach (KeyValuePair<TKey, TValue> kvp in dictionary)\n {\n TKey key = default(TKey);\n TValue value = default(TValue);\n if (keyIsCloneable)\n {\n key = (TKey)((ICloneable)(kvp.Key)).Clone();\n }\n\n else\n {\n key = kvp.Key;\n }\n\n if (valueIsCloneable)\n {\n value = (TValue)((ICloneable)(kvp.Value)).Clone();\n }\n\n else\n {\n value = kvp.Value;\n }\n\n d2.Add(key, value);\n }\n\n return d2;\n }\n</code></pre>\n'}, {'answer_id': 45593250, 'author': 'Mahendra Thorat', 'author_id': 7305904, 'author_profile': 'https://Stackoverflow.com/users/7305904', 'pm_score': 4, 'selected': False, 'text': '<pre><code>var Animal = new Dictionary<string, string>();\n</code></pre>\n\n<p>one can pass existing animal Dictionary to the constructor.</p>\n\n<pre><code>Dictionary<string, string> NewAnimals = new Dictionary<string, string>(Animal);\n</code></pre>\n'}, {'answer_id': 60526164, 'author': 'Marcello', 'author_id': 6366781, 'author_profile': 'https://Stackoverflow.com/users/6366781', 'pm_score': 0, 'selected': False, 'text': '<p>For a primitive type dictionary:</p>\n\n<pre><code>public void runIntDictionary()\n{\n Dictionary<int, int> myIntegerDict = new Dictionary<int, int>() { { 0, 0 }, { 1, 1 }, { 2, 2 } };\n Dictionary<int, int> cloneIntegerDict = new Dictionary<int, int>();\n cloneIntegerDict = myIntegerDict.Select(x => x.Key).ToList().ToDictionary<int, int>(x => x, y => myIntegerDict[y]);\n}\n</code></pre>\n\n<p>or with an Object that implement ICloneable:</p>\n\n<pre><code>public void runObjectDictionary()\n{\n Dictionary<int, number> myDict = new Dictionary<int, number>() { { 3, new number(3) }, { 4, new number(4) }, { 5, new number(5) } };\n Dictionary<int, number> cloneDict = new Dictionary<int, number>();\n cloneDict = myDict.Select(x => x.Key).ToList().ToDictionary<int, number>(x => x, y => myDict[y].Clone());\n}\n\npublic class number : ICloneable\n{\n public number()\n {\n }\n public number(int newNumber)\n {\n nr = newnumber;\n }\n public int nr;\n\n public object Clone()\n {\n return new number() { nr = nr };\n }\n public override string ToString()\n {\n return nr.ToString();\n }\n}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13028/'] |
81,556 | <p>Opening an Infopath form with parameter can be done like this:</p>
<pre><code>System.Diagnostics.Process.Start(PathToInfopath + "infopath.exe", "Template.xsn /InputParameters Id=123");
</code></pre>
<p>But that requires I know the path to Infopath.exe which changes with each version of Office. Is there a way to simply launch the template and pass a parameter? Or is there a standard way to find where Infopath.exe resides?</p>
| [{'answer_id': 82291, 'author': 'Steve', 'author_id': 15526, 'author_profile': 'https://Stackoverflow.com/users/15526', 'pm_score': 1, 'selected': False, 'text': "<p>Play around with System.Diagnostics.ProcessStartInfo which allows you to specify a file you wish to open and also allows you to specify arguments.</p>\n\n<p>You can then use Process.Start(ProcessStartInfo) to kick off the process. The framework will determine which application to run based on the file specified in the ProcessStartInfo.</p>\n\n<p>I don't have Infopath installed so I unfortunately can't try it out. But hopefully it helps you out a little.</p>\n"}, {'answer_id': 90804, 'author': 'bryansh', 'author_id': 211367, 'author_profile': 'https://Stackoverflow.com/users/211367', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s an article about finding the install path for Office Apps:</p>\n\n<p><a href="http://support.microsoft.com/kb/234788" rel="nofollow noreferrer">http://support.microsoft.com/kb/234788</a></p>\n'}, {'answer_id': 984209, 'author': 'Jason Watts', 'author_id': 117526, 'author_profile': 'https://Stackoverflow.com/users/117526', 'pm_score': 0, 'selected': False, 'text': '<p>Try using browser based form and querystring instead</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
81,557 | <p>Is there a way to prevent packages in Delphi to implicitly import units that are not listed in the "Contains" list? I'm looking for a compiler directive that makes the build to fail if it tries to do an implicit import.</p>
<p>Problems occur when you install a package into the IDE that implicitly imports unit A and then you try to install another package that really contains unit A and the IDE tells you that it cannot install that package because unit A is already contained in the first package even if it shouldn't be!</p>
| [{'answer_id': 81876, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 3, 'selected': False, 'text': '<p>Delphi 2009 has the option to make warnings into failures. That would do what you want to do as far as making it fail.</p>\n\n<p>To prevent the implicit importing you need to import it explicitly, or remove the unit that is implicitly importing it.</p>\n'}, {'answer_id': 81921, 'author': 'Lars Truijens', 'author_id': 1242, 'author_profile': 'https://Stackoverflow.com/users/1242', 'pm_score': 0, 'selected': False, 'text': '<p>There is no way to make that warning into an error. In Delphi 2009 you can make treat all warnings as errors.</p>\n\n<p>PS: It is an error in Delphi for .Net</p>\n'}, {'answer_id': 182022, 'author': 'Liron Yahdav', 'author_id': 62, 'author_profile': 'https://Stackoverflow.com/users/62', 'pm_score': 3, 'selected': True, 'text': '<p>If you\'re on a version of Delphi that\'s older that 2009, you can make the warning cause an error by using <a href="http://andy.jgknet.de/blog/?page_id=10" rel="nofollow noreferrer">DDevExtensions</a> (it\'s free). Once you install it, go to Tools > DDevExtensions - Options and in the "Compiler Enhancements" section select the "Active" check box and "Treat warnings as errors". You can add the warnings you want to not be treated as errors in the memo below that. Unfortunately, in your case, it looks like you just want one warning to be treated as an error, so you\'ll have to add pretty much every warning except the one about implicit importing to the list, although it\'s generally good coding practice to resolve all compiler warnings anyways, so you might want to just have all warnings cause errors.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4101/'] |
81,560 | <p>I feel like I have a very basic/stupid question, yet I never saw/read/heard anything in this direction.</p>
<p>Say I have a table <em>users(userId, name)</em> and a table <em>preferences(id, userId, language)</em>. The example is trivial but could be extended to a situation with multi-level relations and way more tables..<br>
When my UI requests to delete a user I first want to show a warning stating that also its preferences will be deleted. If at some point the database gets extended with more tables and relationships, but the software isn't adapted accordingly (the client didn't update) a generic message should be shown.</p>
<p>How can I implement this? The UI cannot know about the whole data structure and should not be bothered to walk down all the relations to manually delete all the depending records. </p>
<p>I would think this would be with constraints.<br>
The constraint would be <em>no action</em> at first so the constraint will throw an error that can be caught by the UI. After the UI receives a confirmation, the constraint should become a <em>cascade</em>.</p>
<p>Somehow I'm feeling like I'm getting this all wrong..</p>
| [{'answer_id': 81586, 'author': 'RB.', 'author_id': 15393, 'author_profile': 'https://Stackoverflow.com/users/15393', 'pm_score': 1, 'selected': False, 'text': '<p>What I would do is this:</p>\n\n<ol>\n<li>The constraint is CASCADE</li>\n<li>The application checks if preferences exist.</li>\n<li>If they do, show the warning.</li>\n<li>If no preferences exist, or the warning is accepted, delete the client.</li>\n</ol>\n\n<p>Changing database relationships on the fly is not going to be a good idea!!</p>\n\n<p>Cheers,</p>\n\n<p>RB.</p>\n'}, {'answer_id': 81665, 'author': 'hamishmcn', 'author_id': 3590, 'author_profile': 'https://Stackoverflow.com/users/3590', 'pm_score': 0, 'selected': False, 'text': '<p>If you are worried about the user not realising the full impact of their delete, you might want to consider not actually deleting the data - instead you could simply set a flag on a column called say "<code>marked_for_deletion</code>". (the entries could then be deleted a safe time later)<br>\nThe downside is that you need to remember to filter out the marked rows in other queries. This can be mitigated by creating a view on the table with the marked rows filtered out, and then always using the view in your queries.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11333/'] |
81,567 | <p>How do you ensure, that you can checkout the code into Eclipse or NetBeans and work there with it?</p>
<p>Edit: If you not checking in ide-related files, you have to reconfigure buildpath, includes and all this stuff, each time you checkout the project. I don't know, if ant (especially an ant buildfile which is created/exported from eclipse) will work with an other ide seamlessly.</p>
| [{'answer_id': 81588, 'author': 'Seldaek', 'author_id': 6512, 'author_profile': 'https://Stackoverflow.com/users/6512', 'pm_score': 1, 'selected': False, 'text': "<p>The best thing is probably to <em>not</em> commit any IDE related file (such as Eclipse's .project), that way everyone can checkout the project and do his thing as he wants. </p>\n\n<p>That being said, I guess most IDEs have their own config file scheme, so maybe you can commit it all without having any conflict, but it feels messy imo.</p>\n"}, {'answer_id': 81639, 'author': 'Henry B', 'author_id': 6414, 'author_profile': 'https://Stackoverflow.com/users/6414', 'pm_score': 0, 'selected': False, 'text': "<p>For the most part I'd agree with seldaek, but I'm also inclined to say that you should at least give a file that says what the dependencies are, what Java version to use to compile, etc, and anything extra that a NetBeans/Eclipse developer might need to compile in their IDE.</p>\n\n<p>We currently only use Eclipse and so we commit all the Eclipse .classpath .project files to svn which I think is the better solution because then everyone is able too reproduce errors and what-not easily instead of faffing about with IDE specifics.</p>\n"}, {'answer_id': 81675, 'author': 'Olaf Kock', 'author_id': 13447, 'author_profile': 'https://Stackoverflow.com/users/13447', 'pm_score': 4, 'selected': True, 'text': '<p>The smart ass answer is "by doing so" - unless you aren\'t working with multiple IDEs you don\'t know if you are really prepared for working with multiple IDEs. Honest. :)</p>\n\n<p>I always have seen multiple platforms as more cumbersome, as they may use different encoding standards (e.g. Windows may default to ISO-8859-1, Linux to UTF-8) - for me encoding has caused way more issues than IDEs.</p>\n\n<p>Some more pointers:</p>\n\n<ul>\n<li>You might want to go with Maven (<a href="http://maven.apache.org" rel="nofollow noreferrer">http://maven.apache.org</a>), let it generate IDE specific files and never commit them to source control.</li>\n<li>In order to be sure that you are generating the correct artefacts, you should have a dedicated server build your deliverables (e.g. cruisecontrol), either with the help of ant, maven or any other tool. These deliverables are the ones that are tested outside of development machines. Great way to make people aware that there is another world outside their own machine.</li>\n<li>Prohibit any machine specific path to be contained in any IDE specific file found in source control. Always reference external libraries by logical path names, preferable containing their version (if you don\'t use maven)</li>\n</ul>\n'}, {'answer_id': 81789, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m of the philosophy that the build should be done with a "lowest common denominator" approach. What goes into source control is what is required to do the build. While I develop exclusively in with Eclipse, my build is with ant at the command line. </p>\n\n<p>With respect to source control, I only check in files that are essential to the build from the command line. No Eclipse files. When I setup a new development machine (seems like twice a year), it takes a little effort to get Eclipse to import the project from an ant build file but nothing scary. (In theory, this should work the same for other IDEs, no? Surly they must be able to import from ant?)</p>\n\n<p>I\'ve also documented how to setup a bare minimum build environment. </p>\n'}, {'answer_id': 81924, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 0, 'selected': False, 'text': '<p>I use maven, and check in just the pom & source.<br>\nAfter checking out a project, I run mvn eclipse:eclipse<br>\nI tell svn to ignore the generated .project, etc.</p>\n'}, {'answer_id': 84958, 'author': 'Jay R.', 'author_id': 5074, 'author_profile': 'https://Stackoverflow.com/users/5074', 'pm_score': 3, 'selected': False, 'text': "<p>We actually maintain a Netbeans and an Eclipse project for our code in SVN right now with no troubles at all. The Netbeans files don't step on the Eclipse files. We have our projects structured like this:</p>\n\n<pre><code>sample-project \n+ bin\n+ launches \n+ lib \n+ logs\n+ nbproject \n+ src \n + java\n.classpath\n.project\nbuild.xml\n</code></pre>\n\n<p>The biggest points seem to be:</p>\n\n<ul>\n<li>Prohibit any absolute paths in the\nproject files for either IDE. </li>\n<li>Set the project files to output the\nclass files to the same directory.</li>\n<li>svn:ignore the private\ndirectory in the .nbproject\ndirectory.</li>\n<li>svn:ignore the directory used for\nclass file output from the IDEs and any other runtime generated directories like the logs directory above.</li>\n<li>Have people using both consistently\nso that differences get resolved\nquickly.</li>\n<li>Also maintain a build system\nindependent of the IDEs such as\ncruisecontrol.</li>\n<li>Use UTF-8 and correct any encoding issues\nimmediately.</li>\n</ul>\n\n<p>We are developing on Fedora 9 32-bit and 64-bit, Vista, and WindowsXP and about half of the developers use one IDE or the other. A few use both and switch back and forth regularly.</p>\n"}, {'answer_id': 89205, 'author': 'Brad at Kademi', 'author_id': 17025, 'author_profile': 'https://Stackoverflow.com/users/17025', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s what i do:</p>\n\n<ol>\n<li>Only maintain in source control your ant build script and associated classpath. Classpath could either be explicit in the ant script, a property file or managed by ivy.</li>\n<li>write an ant target to generate the Eclipse .classpath file from the ant classpath</li>\n<li>Netbeans will use your build script and classpath, just configure it to do so through a free form project.</li>\n</ol>\n\n<p>This way you get IDE independent build scripts and happy developers :)</p>\n\n<p>There\'s a blog on netbeans site on how to do 3. but i can\'t find it right now. I\'ve put some notes on how to do the above on my site - <a href="http://www.bradmcevoy.com/ant_netbeans_eclipse.html" rel="nofollow noreferrer" title="Ant+Netbeans+Eclipse">link text</a> (quick and ugly though, sorry)</p>\n\n<p>Note that if you\'re using Ivy (a good idea) and eclipse you might be tempted to use the eclipse ivy plugin. I\'ve used it and found it to be horribly buggy and unreliable. Better to use 2. above.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5751/'] |
81,587 | <p>We have in the process of upgrading our application to full Unicode comptibility as we have recently got Delphi 2009 which provides this out of the box. I am looking for anyone who has experience of upgrading an application to accept Unicode characters. Specifically answers to any of the following questions.</p>
<ul>
<li>We need to change VarChars to NVarchar, Char to NChar. Are there any gotchas here.</li>
<li>We need to update all sql statements to include N in front of any sql strings. So Update tbl_Customer set Name = 'Smith' must become Update tbl_Customer set Name = <strong>N</strong>'Smith' . Is there any way to default to this for certain Fields. It seems extraordinary this is still required.</li>
<li>Is it possible to get any defaults set up in SQLServer that will make this simpler?</li>
</ul>
<p>ps We also need to upgrade our Oracle code</p>
| [{'answer_id': 81649, 'author': 'Toby Allen', 'author_id': 6244, 'author_profile': 'https://Stackoverflow.com/users/6244', 'pm_score': 0, 'selected': False, 'text': "<p>Damien </p>\n\n<p>I'm not sure how useful your answer is. We have a large 700,000 lines of compiled codebase that was written over the last ten years which contains a large number of sql queries. Most are standardised down to a few functions which are the basis for most of the updates on the database. These can be updated quite simply. However we also need to check every where clause for CustomerName = '%s' which should now be CustomerName = N'%s'</p>\n\n<p>This is a real question which needs a real answer.</p>\n"}, {'answer_id': 81895, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 2, 'selected': True, 'text': "<p>Oracle doesn't require you to use <code>nvarchar</code> to store Unicode strings—the server can be configured to store <code>varchar2</code> in UTF-8. If you only supported ASCII before, it should be transparent. That should prevent the need for all the application-side search-and-replace for <code>'</code> to <code>N'</code>.</p>\n\n<p>As for Damien's point: it might not help you now, but you should really make it a priority to get rid of non-parameterized queries. They are nothing but a drag on your system from a maintenance, performance, and safety standpoint.</p>\n"}, {'answer_id': 83060, 'author': 'Damien_The_Unbeliever', 'author_id': 15498, 'author_profile': 'https://Stackoverflow.com/users/15498', 'pm_score': 1, 'selected': False, 'text': '<p>Obvious with SQL Server is that the limits for nchar/nvarchar are half of their char/varchar counterparts (unless you migrate everything > 4000 to nvarchar(max))</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6244/'] |
81,589 | <p>My workplace has sales people using a 3rd party desktop application that connects directly the a Sql Server and the software is leaving hundreds of sleeping connections for each user. Is there anyway to clear these connection programmatically?</p>
| [{'answer_id': 83416, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Which version of SQL Server do you run? You can write a stored procedure to do this, looking at the data from sp_who and then making some guess about the last activity. There\'s a "LastBatch" column that does the last time something was submitted by this user. I\'d say if that is over an hour old (or whatever interval), execute a KILL for that SPID.</p>\n\n<p>You could do this in SQL 2005 like this:</p>\n\n<pre><code>declare @spid int\n , @cmd varchar(200)\ndeclare Mycurs cursor for\nselect spid\n from master..sysprocesses\n where status = \'sleeping\'\n and last_batch > dateadd( s, -1, getdate())\nopen mycurs\nfetch next from mycurs into @spid\nwhile @@fetch_status = 0\n begin\n select @cmd = \'kill \' + cast(@spid as varchar)\n exec(@cmd )\n fetch next from mycurs into @spid\n end\ndeallocate MyCurs\n</code></pre>\n'}, {'answer_id': 811204, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>But, instead of killing these processes manually, shouldn\'t there be a way to avoid these? I have the same problem in a project</p>\n\n<p>In our Web application, we are performing some updates using a Web service (i.e. a program calls a webservice method. The method opens a connection, does an update, commits and closes the connection using connection.close()) </p>\n\n<p>In the sqlserver mgmt studio if I do a sp_who2, I see that the connections increase as teh app is running - in fact at the rate of 1 connection per update execution. AND the concerning part is that it crosses the 100 and then does not allow more connections into the db. Users are not able to login as well the programs fail as they cannot get any more new connections.</p>\n\n<p>How to ensure that the connections are reused - We have not written any connection pooling code, using the default asp.net and Sqlserver connection pooling. Why are the connections not be reused and why are they not vanishing after being "Closed" ?\nDoes this depend on the fact that a webservice is handling the transaction ?</p>\n\n<p>Thanks a lot</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5802/'] |
81,591 | <p>If my email id receives an email from a particular sender, can I ask sendmail to trigger a different program and pass on the newly arrived email to it for further processing? This is similar to filters in gmail. Wait for some email to arrive, see if it matches the criteria and take some action if it does.</p>
| [{'answer_id': 81619, 'author': 'ColinYounger', 'author_id': 1223, 'author_profile': 'https://Stackoverflow.com/users/1223', 'pm_score': 0, 'selected': False, 'text': "<p>We handle this by having a cron process running on the mail server which watches the inbox directory and scans any new messages (files) every 10 minutes or so.</p>\n\n<p>When the process finds an email of interest, it fires the information off to another process which then reacts to the new message (and, in our case, removes the message from the inbox).</p>\n\n<p>--edit--</p>\n\n<p>Finding the email inbox depends on your implementation - check the 'manual' your version of sendmail for details - we direct incoming email to a special directory or have parameters to work out the inbox details. I don't feel it would be useful to be more specific as the answer to 'where is the inbox' is 'it depends'.</p>\n\n<p>As for the pattern to search for - we decode the email message (a text file) into a DOM that we can manipulate. For example, we can then look for specific words in property 'subject'.</p>\n"}, {'answer_id': 81620, 'author': 'Shoban', 'author_id': 12178, 'author_profile': 'https://Stackoverflow.com/users/12178', 'pm_score': 0, 'selected': False, 'text': '<p>are you talking about email clients? If so then you can set rules in outlook and I am sure there mustbe ways in other email cleints too!! If u are asking something else. sorry</p>\n'}, {'answer_id': 81625, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': "<p>This is what Procmail is for.</p>\n\n<p>Set Sendmail up to use procmail as the mail delivery agent (MDA), or set up your .forward to pipe stuff through procmail. (See the man page.)</p>\n\n<p>Then you can write your .procmailrc to do all sorts of things along these lines.</p>\n\n<p>This filter predates gmail. Still useful if you're running a mail server.</p>\n"}, {'answer_id': 82096, 'author': 'Shoban', 'author_id': 12178, 'author_profile': 'https://Stackoverflow.com/users/12178', 'pm_score': 0, 'selected': False, 'text': '<p>ok. then I suggest Colins method.. I use cron to monitor emails (for a particluar domain) and send text messages as alerts!. Similar to what you are asking!</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11107/'] |
81,597 | <p>How can I find and delete unused references in my projects? </p>
<p>I know you can easily remove the using statements in vs 2008, but this doesn't remove the actual reference in your projects. The referenced dll will still be copied in your bin/setup package.</p>
| [{'answer_id': 81610, 'author': 'Chris Canal', 'author_id': 5802, 'author_profile': 'https://Stackoverflow.com/users/5802', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://www.jetbrains.com/resharper/" rel="nofollow noreferrer">ReSharper</a> will do this for you (and so so much more!)</p>\n'}, {'answer_id': 228834, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 0, 'selected': False, 'text': "<p>Given that VisualStudio (or is it msbuild?) detects unused references and doesn't include them in the output file, you can write a script which parses the references out of the csproj, and compares that with the referenced Assemblies detected by reflexion on the project output.</p>\n\n<p>If you're motivated...</p>\n"}, {'answer_id': 1382776, 'author': 'jlo', 'author_id': 48148, 'author_profile': 'https://Stackoverflow.com/users/48148', 'pm_score': 7, 'selected': True, 'text': '<p>*Note: see <a href="http://www.jetbrains.net/devnet/message/5244658" rel="noreferrer">http://www.jetbrains.net/devnet/message/5244658</a> for another version of this answer.</p>\n\n<p>Reading through the posts, it looks like there is some confusion as to the original question. Let me take a stab at it.</p>\n\n<p>The original post is really asking the question: "How do I identify and remove references from one Visual Studio project to other projects/assemblies that are not in use?" The poster wants the assemblies to no longer appear as part of the build output. </p>\n\n<p>In this case, ReSharper can help you <em>identify</em> them, but you have to <em>remove</em> them yourself. </p>\n\n<p>To do this, open up the References inth Solution Browser, right mouse click on each referenced assembly, and pick "Find Dependent Code". See:</p>\n\n<p><a href="http://www.jetbrains.com/resharper/features/navigation_search.html#Find_ReferencedDependent_Code" rel="noreferrer">http://www.jetbrains.com/resharper/features/navigation_search.html#Find_ReferencedDependent_Code</a></p>\n\n<p>You will either get:</p>\n\n<ol>\n<li><p>A list of the dependencies on that Reference in a browser window, or</p></li>\n<li><p>A dialog telling you "Code dependent on module XXXXXXX was not found.".</p></li>\n</ol>\n\n<p>If you get the the second result, you can then right mouse click the Reference, select Remove, and remove it from your project.</p>\n\n<p>While you have to to this "manually", i.e. one reference at a time, it will get the job done. If anyone has automated this in some manner I am interested in hearing how it was done.</p>\n\n<p>You can pretty much ignore the ones in the .Net Framework as they don\'t normally get copied to your build output (typically - although not necessarily true for Silverlight apps).</p>\n\n<p>Some posts seem to be answering the question: "How do I remove using clauses (C#) from a source code file that are not needed to resolve any references within that file". </p>\n\n<p>In this case, ReSharper does help in a couple ways:</p>\n\n<ol>\n<li><p>Identifies unused using clauses for you during on the fly error detection. They appear as Code Inspection Warnings - the code will appear greyed out (be default) in the file and ReSharper will provide a Hint to remove it: </p>\n\n<p><a href="http://www.jetbrains.com/resharper/features/code_analysis.html#On-the-fly_Error_Detection" rel="noreferrer">http://www.jetbrains.com/resharper/features/code_analysis.html#On-the-fly_Error_Detection</a></p></li>\n<li><p>Allows you to automatically remove them as part of the Code Cleanup Process:</p>\n\n<p><a href="http://www.jetbrains.com/resharper/features/code_formatting.html#Optimizing_Namespace_Import_Directives" rel="noreferrer">http://www.jetbrains.com/resharper/features/code_formatting.html#Optimizing_Namespace_Import_Directives</a></p></li>\n</ol>\n\n<p><strong>Finally, realize that ReSharper does static code analysis on your solution. So, if you have a dynamic reference to the assembly - say through reflection or an assembly that is dynamically loaded at runtime and accessed through an interface - it won\'t pick it up.</strong> There is no substitute for understanding your code base and the project dependencies as you work on your project. I do find the ReSharper features very useful.</p>\n'}, {'answer_id': 1729352, 'author': 'jbe', 'author_id': 103988, 'author_profile': 'https://Stackoverflow.com/users/103988', 'pm_score': 3, 'selected': False, 'text': '<p>Removing unused references is a feature Visual Studio 2008 already supports. Unfortunately, only for VB .NET projects.</p>\n\n<p>I have opened a suggestion on Microsoft Connect to get this feature for C# projects too:</p>\n\n<p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=510326" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=510326</a> </p>\n\n<p>If you like this feature as well then you might vote my suggestion.</p>\n'}, {'answer_id': 5961469, 'author': 'Spongman', 'author_id': 204555, 'author_profile': 'https://Stackoverflow.com/users/204555', 'pm_score': 4, 'selected': False, 'text': '<p>you can use the \'<strong>Remove Unused References</strong>\' extension I wrote: </p>\n\n<p><a href="http://visualstudiogallery.msdn.microsoft.com/9811e528-cfa8-4fe7-9dd1-4021978b5097">http://visualstudiogallery.msdn.microsoft.com/9811e528-cfa8-4fe7-9dd1-4021978b5097</a></p>\n'}, {'answer_id': 8133979, 'author': 'Kirill Skrygan', 'author_id': 185103, 'author_profile': 'https://Stackoverflow.com/users/185103', 'pm_score': 2, 'selected': False, 'text': '<p>ReSharper 6.1 will include these features:</p>\n<ul>\n<li><p><strong>Optimize references</strong>: analyze your assembly references and their usages in code, get list of redundant references and remove them.</p>\n</li>\n<li><p><strong>Remove Unused References</strong>: quick refactoring to remove redundant assembly references.</p>\n</li>\n<li><p><strong>Safe delete on assembly references</strong>: will delete assembly references if all of them are redundant, otherwise dispalies usages and can remove only redundant assembly references of the selected list.</p>\n</li>\n</ul>\n'}, {'answer_id': 9154751, 'author': 'Leniel Maccaferri', 'author_id': 114029, 'author_profile': 'https://Stackoverflow.com/users/114029', 'pm_score': 3, 'selected': False, 'text': '<p>Try this one: <a href="http://visualstudiogallery.msdn.microsoft.com/fc504cc6-5808-4da8-ae86-8d3f9ed81606" rel="noreferrer">Reference Assistant</a></p>\n\n<blockquote>\n <p>Summary</p>\n \n <p>Reference Assistant helps to remove unused references from C#, F#,\n VB.NET or VC++/CLI projects in the Visual Studio 2010.</p>\n</blockquote>\n'}, {'answer_id': 13108045, 'author': 'mes', 'author_id': 1016092, 'author_profile': 'https://Stackoverflow.com/users/1016092', 'pm_score': 2, 'selected': False, 'text': '<p>I done this without extension in the VS 2010 Ultimate\nArchitecture->Generate Dependency Graph->By Assembly, it shows used assemblies, and manually removed unused references.</p>\n'}, {'answer_id': 27364730, 'author': 'hdmq', 'author_id': 3792118, 'author_profile': 'https://Stackoverflow.com/users/3792118', 'pm_score': 0, 'selected': False, 'text': '<p>I think that are copied in bin\\, because in the project that removed the reference have reference o other project that have the same reference...</p>\n'}, {'answer_id': 32232580, 'author': 'toddmo', 'author_id': 1045881, 'author_profile': 'https://Stackoverflow.com/users/1045881', 'pm_score': 2, 'selected': False, 'text': '<p>I have a free answer that works in any version of Visual Studio and any Framework version. It doesn\'t remove the unused references, but it identifies them.</p>\n\n<p>You can use <a href="http://www.telerik.com/products/decompiler.aspx" rel="nofollow noreferrer">Telerik JustDecompile</a> on your project dll. Just open the dll in JustDecompile and go under <code>References</code> to see what is actually used in the compiled dll.</p>\n\n<p><a href="https://i.stack.imgur.com/Lc9BT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lc9BT.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 34355618, 'author': 'fat', 'author_id': 1035174, 'author_profile': 'https://Stackoverflow.com/users/1035174', 'pm_score': 0, 'selected': False, 'text': '<p>If you know which references are not used you can remove them manually.<br>\nIn Solution Explorer, right-click the reference in the <em>References</em> node, and then click Remove. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11333/'] |
81,627 | <p>I am using Qt Dialogs in one of my application.
I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.</p>
| [{'answer_id': 81927, 'author': 'amos', 'author_id': 15429, 'author_profile': 'https://Stackoverflow.com/users/15429', 'pm_score': 7, 'selected': True, 'text': '<p>By default the <em>Qt::WindowContextHelpButtonHint</em> flag is added to dialogs.\nYou can control this with the <em>WindowFlags</em> parameter to the dialog constructor. </p>\n\n<p>For instance you can specify only the <em>TitleHint</em> and <em>SystemMenu</em> flags by doing:</p>\n\n<pre><code>QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);\nd->exec();\n</code></pre>\n\n<p>If you add the <em>Qt::WindowContextHelpButtonHint</em> flag you will get the help button back.</p>\n\n<p>In PyQt you can do:</p>\n\n<pre><code>from PyQt4 import QtGui, QtCore\napp = QtGui.QApplication([])\nd = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)\nd.exec_()\n</code></pre>\n\n<p>More details on window flags can be found on the <a href="https://doc.qt.io/qt-5.7/qt.html#WindowType-enum" rel="noreferrer">WindowType enum</a> in the Qt documentation.</p>\n'}, {'answer_id': 82303, 'author': 'AMM', 'author_id': 11212, 'author_profile': 'https://Stackoverflow.com/users/11212', 'pm_score': 5, 'selected': False, 'text': '<p>Ok , I found a way to do this.</p>\n\n<p>It does deal with the Window flags. So here is the code i used:</p>\n\n<pre><code>Qt::WindowFlags flags = windowFlags()\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags & (~helpFlag); \nsetWindowFlags(flags);\n</code></pre>\n\n<p>But by doing this sometimes the icon of the dialog gets reset. So to make sure the icon of the dialog does not change you can add two lines.</p>\n\n<pre><code>QIcon icon = windowIcon();\n\nQt::WindowFlags flags = windowFlags();\n\nQt::WindowFlags helpFlag =\nQt::WindowContextHelpButtonHint;\n\nflags = flags & (~helpFlag); \n\nsetWindowFlags(flags);\n\nsetWindowIcon(icon);\n</code></pre>\n'}, {'answer_id': 358270, 'author': 'Michael Bishop', 'author_id': 45114, 'author_profile': 'https://Stackoverflow.com/users/45114', 'pm_score': 2, 'selected': False, 'text': "<p>The answers listed here will work, but to answer it yourself, I'd recommend you run the example program <code>$QTDIR/examples/widgets/windowflags</code>. That will allow you to test all the configurations of window flags and their effects. Very useful for figuring out squirrelly windowflags problems.</p>\n"}, {'answer_id': 3817398, 'author': 'brandoneggar', 'author_id': 461134, 'author_profile': 'https://Stackoverflow.com/users/461134', 'pm_score': 0, 'selected': False, 'text': "<p>I couldn't find a slot but you can override the virtual <code>winEvent</code> function.</p>\n\n<pre><code>#if defined(Q_WS_WIN)\nbool MyWizard::winEvent(MSG * msg, long * result)\n{\n switch (msg->message)\n {\n case WM_NCLBUTTONDOWN:\n if (msg->wParam == HTHELP)\n {\n\n }\n break;\n default:\n break;\n }\n return QWizard::winEvent(msg, result);\n}\n#endif\n</code></pre>\n"}, {'answer_id': 22039439, 'author': 'rrwick', 'author_id': 2438989, 'author_profile': 'https://Stackoverflow.com/users/2438989', 'pm_score': 4, 'selected': False, 'text': '<p>I ran into this issue in Windows 7, Qt 5.2, and the flags combination that worked best for me was this:</p>\n\n<p><strong>Qt::WindowTitleHint | Qt::WindowCloseButtonHint</strong></p>\n\n<p>This gives me a working close button but no question mark help button. Using just Qt::WindowTitleHint or Qt::WindowSystemMenuHint got rid of the help button, but it also disabled the close button.</p>\n\n<p>As Michael Bishop suggested, it was playing with the windowflags example that led me to this combination. Thanks!</p>\n'}, {'answer_id': 30934930, 'author': 'Jens A. Koch', 'author_id': 1163786, 'author_profile': 'https://Stackoverflow.com/users/1163786', 'pm_score': 6, 'selected': False, 'text': '<pre><code>// remove question mark from the title bar\nsetWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);\n</code></pre>\n'}, {'answer_id': 45939311, 'author': 'Predelnik', 'author_id': 1269661, 'author_profile': 'https://Stackoverflow.com/users/1269661', 'pm_score': 2, 'selected': False, 'text': '<p>The following way to remove question marks by default for all the dialogs in application could be used:</p>\n\n<p>Attach the following event filter to <code>QApplication</code> somewhere at the start of your program:</p>\n\n<pre><code> bool eventFilter (QObject *watched, QEvent *event) override\n {\n if (event->type () == QEvent::Create)\n {\n if (watched->isWidgetType ())\n {\n auto w = static_cast<QWidget *> (watched);\n w->setWindowFlags (w->windowFlags () & (~Qt::WindowContextHelpButtonHint));\n }\n }\n return QObject::eventFilter (watched, event);\n }\n</code></pre>\n'}, {'answer_id': 49905954, 'author': 'Parker Coates', 'author_id': 4757, 'author_profile': 'https://Stackoverflow.com/users/4757', 'pm_score': 5, 'selected': False, 'text': '<p>As of Qt 5.10, you can disable these buttons globally with a single <code>QApplication</code> attribute!</p>\n\n<pre><code>QApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);\n</code></pre>\n'}, {'answer_id': 70467468, 'author': 'Pascal Vallaster', 'author_id': 15889585, 'author_profile': 'https://Stackoverflow.com/users/15889585', 'pm_score': 2, 'selected': False, 'text': "<p>As the solution for PyQt4 from @amos didn't work for me and the version of PyQt4 is deprecated, here is my solution on how to remove the "?" in the dialog-box in PyQt5:</p>\n<pre><code>class window(QDialog):\n def __init__(self):\n super(window, self).__init__()\n loadUi("window.ui", self)\n self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint,False) # This removes it\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11212/'] |
81,628 | <p>I'd like to build a query string based on values taken from 5 groups of radio buttons.</p>
<p>Selecting any of the groups is optional so you could pick set A or B or both. How would I build the querystring based on this? I'm using VB.NET 1.1</p>
<p>The asp:Radiobuttonlist control does not like null values so I'm resorting to normal html radio buttons. My question is how do I string up the selected values into a querystring</p>
<p>I have something like this right now:</p>
<p>HTML:</p>
<pre><code><input type="radio" name="apBoat" id="Apb1" value="1" /> detail1
<input type="radio" name="apBoat" id="Apb2" value="2" /> detail2
<input type="radio" name="cBoat" id="Cb1" value="1" /> detail1
<input type="radio" name="cBoat" id="Cb2" value="2" /> detail2
</code></pre>
<p>VB.NET</p>
<pre><code>Public Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim queryString As String = "nextpage.aspx?"
Dim aBoat, bBoat, cBoat bas String
aBoat = "apb=" & Request("aBoat")
bBoat = "bBoat=" & Request("bBoat")
cBoat = "cBoat=" & Request("cBoat ")
queryString += aBoat & bBoat & cBoat
Response.Redirect(queryString)
End Sub
</code></pre>
<p>Is this the best way to build the query string or should I take a different approach altogether? Appreciate all the help I can get. Thanks much.</p>
| [{'answer_id': 81678, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 0, 'selected': False, 'text': '<p>You could use StringBuilder instead of creating those three different strings. You can help it out by preallocating about how much memory you need to store your string. You could also use String.Format instead.</p>\n\n<p>If this is all your submit button is doing why make it a .Net page at all and instead just have a GET form go to nextpage.aspx for processing?</p>\n'}, {'answer_id': 81704, 'author': 'Ian Oxley', 'author_id': 1904, 'author_profile': 'https://Stackoverflow.com/users/1904', 'pm_score': 2, 'selected': True, 'text': '<p>The easiest way would be to use a non-server-side <form> tag with the method="get" then when the form was submitted you would automatically get the querystring you are after (and don\'t forget to add <label> tags and associate them with your radio buttons):</p>\n\n<pre><code><form action="..." method="get">\n <input type="radio" name="apBoat" id="Apb1" value="1" /> <label for="Apb1">detail1</label>\n <input type="radio" name="apBoat" id="Apb2" value="2" /> <label for="Apb2">detail2</label>\n\n <input type="radio" name="cBoat" id="Cb1" value="1" /> <label for="Cb1">detail1</label>\n <input type="radio" name="cBoat" id="Cb2" value="2" /> <label for="Cb2">detail2</label>\n</form>\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12232/'] |
81,631 | <p>I want:
all links which not contained filename (not .html, .jpg, .png, .css) redirect with state 301 to directory, for example: <a href="http://mysite.com/article" rel="nofollow noreferrer">http://mysite.com/article</a> -> <a href="http://mysite.com/article/" rel="nofollow noreferrer">http://mysite.com/article/</a>
But <a href="http://mysite.com/article/article-15.html" rel="nofollow noreferrer">http://mysite.com/article/article-15.html</a> not redirects.
What regulat expression I must write to .htaccess for adding slash to virtual directories?</p>
| [{'answer_id': 81648, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Clarification needed:</p>\n\n<p>Given the url:\n<a href="http://server/path/file" rel="nofollow noreferrer">http://server/path/file</a></p>\n\n<p>Does that get redirected to:\n<a href="http://server/path/" rel="nofollow noreferrer">http://server/path/</a></p>\n\n<p>Or does it get redirected to:\n<a href="http://server/path/file/" rel="nofollow noreferrer">http://server/path/file/</a></p>\n\n<p>As in: Do you want the redirects to go to the parent path, or do you just want to add a slash and assume directory out of the current path?</p>\n'}, {'answer_id': 81760, 'author': 'MB.', 'author_id': 11961, 'author_profile': 'https://Stackoverflow.com/users/11961', 'pm_score': 3, 'selected': True, 'text': '<p>I think the following might work:</p>\n\n<pre><code>RewriteEngine on \nRewriteCond %{REQUEST_URI} ^/[^\\.]+[^/]$\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n</code></pre>\n\n<p>When it comes to mod_rewrite I can never be sure without testing though...</p>\n'}, {'answer_id': 193294, 'author': 'eyelidlessness', 'author_id': 17964, 'author_profile': 'https://Stackoverflow.com/users/17964', 'pm_score': 0, 'selected': False, 'text': "<p>MB's RewriteRule above will fail on paths like <code>/a</code> because it needs to match at least two characters after the slash. Moreover it only matches on top directory URLs.</p>\n\n<pre><code>RewriteRule ^(([^\\/]+\\/)*[^\\/\\.]+)$ http://%{HTTP_HOST}/$1/ [R=301,L]\n</code></pre>\n\n<p>Is the purpose of this to reduce history pollution/false negatives?</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13427/'] |
81,635 | <p>I get an XML file From a web service. Now I want to get one of those elements out of the file.</p>
<p>I think I should go use XPath - any good starter reference?</p>
| [{'answer_id': 81643, 'author': 'Sietse', 'author_id': 6400, 'author_profile': 'https://Stackoverflow.com/users/6400', 'pm_score': 2, 'selected': True, 'text': '<p>Not VB specific, but try this: <a href="http://www.w3schools.com/xsl/xpath_intro.asp" rel="nofollow noreferrer">http://www.w3schools.com/xsl/xpath_intro.asp</a></p>\n'}, {'answer_id': 81647, 'author': 'GHad', 'author_id': 11705, 'author_profile': 'https://Stackoverflow.com/users/11705', 'pm_score': 0, 'selected': False, 'text': '<p>One way would be to only extract the needed informations with an xslt file into a new xml and use this new xml as data basis for further processing</p>\n'}, {'answer_id': 81709, 'author': 'glenatron', 'author_id': 15394, 'author_profile': 'https://Stackoverflow.com/users/15394', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve just been recovering my XPath skills- this <a href="http://www.mulberrytech.com/quickref/" rel="nofollow noreferrer">Xslt and XPath Quick Reference sheet</a> is quite a useful reference - it doesn\'t go into depth but it does list what is available and what you might want to search for more information on.</p>\n\n<p>The w3schools tutorial linked previously isn\'t that great - it takes a long time to not cover a lot of ground - but it is still worth reading.</p>\n'}, {'answer_id': 82374, 'author': 'dummy', 'author_id': 6297, 'author_profile': 'https://Stackoverflow.com/users/6297', 'pm_score': 0, 'selected': False, 'text': '<p>If I need to do some XPath, I just tweak one of these examples.</p>\n\n<ul>\n<li><strong>child::node()</strong> selects all the children of the context node, whatever their node type</li>\n<li><strong>attribute::name</strong> selects the name attribute of the context node</li>\n<li><strong>attribute::*</strong> selects all the attributes of the context node</li>\n<li><strong>descendant::para</strong> selects the para element descendants of the context node</li>\n<li><strong>ancestor::div</strong> selects all <strong>div</strong> ancestors of the context node</li>\n<li><strong>ancestor-or-self::div</strong> selects the <strong>div</strong> ancestors of the context node and, if the context node is a div element, the context node as well</li>\n<li><strong>descendant-or-self::para</strong> selects the <strong>para</strong> element descendants of the context node and, if the context node is a <strong>para</strong> element, the context node as well</li>\n<li><strong>self::para</strong> selects the context node if it is a <strong>para</strong> element, and otherwise selects nothing</li>\n<li><strong>child::chapter/descendant::para</strong> selects the <strong>para</strong> element descendants of the chapter element children of the context node</li>\n<li><strong>child::*/child::para</strong> selects all <strong>para</strong> grandchildren of the context node</li>\n<li><strong>/</strong> selects the document root (which is always the parent of the document element)</li>\n<li><strong>/descendant::para</strong> selects all the <strong>para</strong> elements in the same document as the context node</li>\n<li><strong>/descendant::olist/child::item</strong> selects all the item elements that have an <strong>olist</strong> parent and that are in the same document as the context node</li>\n<li><strong>child::para[position()=1]</strong> selects the first <strong>para</strong> child of the context node</li>\n<li><strong>child::para[position()=last()]</strong> selects the last <strong>para</strong> child of the context node</li>\n<li><strong>child::para[position()=last()-1]</strong> selects the last but one <strong>para</strong> child of the context node</li>\n<li><strong>child::para[position()>1]</strong> selects all the <strong>para</strong> children of the context node other than the first para child of the context node</li>\n<li><strong>following-sibling::chapter[position()=1]</strong> selects the next <strong>chapter</strong> sibling of the context node</li>\n<li><strong>preceding-sibling::chapter[position()=1]</strong> selects the previous <strong>chapter</strong> sibling of the context node</li>\n<li><strong>/descendant::figure[position()=42]</strong> selects the forty-second figure element in the document</li>\n<li><strong>/child::doc/child::chapter[position()=5]/child::section[position()=2]</strong> selects the second section of the fifth <strong>chapter</strong> of the <strong>doc</strong> document element</li>\n<li><strong>child::para[attribute::type="warning"]</strong> selects all <strong>para</strong> children of the context node that have a type attribute with value <strong>warning</strong></li>\n<li><strong>child::para[attribute::type=\'warning\'][position()=5]</strong> selects the fifth <strong>para</strong> child of the context node that has a type attribute with value warning</li>\n<li><strong>child::para[position()=5][attribute::type="warning"]</strong> selects the fifth <strong>para</strong> child of the context node if that child has a type attribute with value <strong>warning</strong></li>\n<li><strong>child::chapter[child::title=\'Introduction\']</strong> selects the chapter children of the context node that have one or more title children with string-value equal to Introduction</li>\n<li><strong>child::chapter[child::title]</strong> selects the <strong>chapter</strong> children of the context node that have one or more title children</li>\n<li><strong>child::*[self::chapter or self::appendix]</strong> selects the <strong>chapter</strong> and <strong>appendix</strong> children of the context node</li>\n<li><strong>child::*[self::chapter or self::appendix][position()=last()]</strong> selects the last <strong>chapter</strong> or <strong>appendix</strong> child of the context node</li>\n</ul>\n\n<p>An in depth documentation can be found <a href="http://www.w3.org/TR/xpath" rel="nofollow noreferrer">here</a>. Also these example are taken from there.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15502/'] |
81,644 | <p>I am using mysql++ in order to connect to a MySQL database to perform a bunch of data queries. Due to the fact that the tables I am reading from are constantly being written to, and that I need a consistent view of the data, I lock the tables first. However, MySQL has no concept of 'NOWAIT' in its lock query, thus if the tables are locked by something else that keeps them locked for a long time, my application sits there waiting. What I want it to do is to be able to return and say something like 'Lock could no be obtained' and try again in a few seconds. My general attempt at this timeout is below.</p>
<p>If I run this after locking the table on the database, I get the message that the timeout is hit, but I don't know how to then get the mysql_query line to terminate. I'd appreciate any help/ideas!</p>
<pre><code>
volatile sig_atomic_t success = 1;
void catch_alarm(int sig) {
cout << "Timeout reached" << endl;
success = 0;
signal(sig,catch_alarm);
}
// connect to db etc.
// *SNIP
signal (SIGALRM, catch_alarm);
alarm(2);
mysql_query(p_connection,"LOCK TABLES XYZ as write");
</code></pre>
| [{'answer_id': 81663, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 0, 'selected': False, 'text': '<p>You could execute the blocking query in a different thread and never being bothered with the timeout. When some data arrives you notify the thread that needs to know about the status of the transaction.</p>\n'}, {'answer_id': 81967, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>If I was writing from scratch I would do that, but this is a server application that we are just doing an upgrade to rather than a large rework.</p>\n'}, {'answer_id': 83695, 'author': 'longneck', 'author_id': 8250, 'author_profile': 'https://Stackoverflow.com/users/8250', 'pm_score': 0, 'selected': False, 'text': '<p>instead of trying to fake transactions with table locks, why not switch to innodb tables where you get actual transactions? just make sure to set the default transaction isolation level to REPEATABLE READ.</p>\n'}, {'answer_id': 94062, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>As I said, it is not so easy to 'switch' or re-architect when this is a live, in production system. I'm slightly frustrated that MySQL provides no methods to check for locks or choose not to hang waiting on a lock.</p>\n"}, {'answer_id': 94540, 'author': 'pestophagous', 'author_id': 10278, 'author_profile': 'https://Stackoverflow.com/users/10278', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t know if this is a good idea in terms of resource usage and "best practices" and "cleanliness" and all the rest... but you have now repeatedly described the handcuffs that bind you in terms of re-architecting a "clean" system... so here goes.....</p>\n\n<p>Could you open a new, separate connection just for sending the LOCK statement? Then close that connection when you catch the timeout alarm? By closing/destroying the connection that was dedicated to the LOCK statement, would not that essentially "cancel" the LOCK statment? I am not certain if such events would occur as I have described/guessed, but maybe it is something to test out.</p>\n'}, {'answer_id': 102263, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>My experience described so far indicates to me that closing a connection in which a query is running causes a seg fault. Therefore dispatching that query into a different connection wouldn't really help, as that would also seg fault.</p>\n"}, {'answer_id': 158725, 'author': 'Danut Enachioiu', 'author_id': 24226, 'author_profile': 'https://Stackoverflow.com/users/24226', 'pm_score': 2, 'selected': False, 'text': '<p>You can implement a "cancel-like" behavior this way:</p>\n\n<p>You execute the query on a separate thread, that keeps running whether or not the timeout occurs. The timeout occurs on the main thread, and sets a variable to "1" marking that it occurred. Then you do whatever you want to do on your main thread. </p>\n\n<p>The query thread, once the query completes, checks if the timeout has occurred. If it hasn\'t, it does the rest of the work it needs to do. If it HAS, it just unlocks the tables it just locked. </p>\n\n<p>I know it sounds a bit wasteful, but the lock-unlock period should be basically instantaneous, and you get as close to the result you want as possible.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
81,656 | <p>For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online.</p>
<p>Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums.</p>
<p>To get this started, since these are the ones I am searching for right now, where are there good online resources for:</p>
<ul>
<li>C89</li>
<li>C99</li>
<li>C11</li>
<li>C++98</li>
<li>C++03</li>
<li>C++11</li>
<li>C++14</li>
<li>C++17</li>
</ul>
| [{'answer_id': 81687, 'author': 'Pieter', 'author_id': 5822, 'author_profile': 'https://Stackoverflow.com/users/5822', 'pm_score': 4, 'selected': False, 'text': '<p>ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).</p>\n\n<p>While they aren\'t finalised however, they can usually be found online, as drafts. Most of the times the final version doesn\'t differ significantly from the last draft, so while not perfect, they\'ll suit just fine.</p>\n\n<ul>\n<li><a href="http://www.justsoftwaresolutions.co.uk/cplusplus/new-cplusplus-draft-and-concurrency-papers.html" rel="noreferrer">C++ 0x draft</a></li>\n</ul>\n'}, {'answer_id': 81748, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 2, 'selected': False, 'text': '<p>The ISO C and C++ standards are bloody expensive. On the other hand, the INCITS republishes them for a lot less. <a href="http://www.techstreet.com/" rel="nofollow noreferrer">http://www.techstreet.com/</a> seems to have the PDF for $30\n(search for INCITS/ISO/IEC 14882:2003).</p>\n\n<p>Hardcopy versions are available, too. Look for the British Standards Institute versions, published by Wiley.</p>\n'}, {'answer_id': 81986, 'author': 'James Hopkin', 'author_id': 11828, 'author_profile': 'https://Stackoverflow.com/users/11828', 'pm_score': 4, 'selected': False, 'text': '<p>You might find the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3225.pdf" rel="noreferrer">draft international standard</a> for C++0x useful.</p>\n'}, {'answer_id': 83504, 'author': 'Anthony Williams', 'author_id': 5597, 'author_profile': 'https://Stackoverflow.com/users/5597', 'pm_score': 3, 'selected': False, 'text': '<p>The C99 and C++03 standards are available in book form from Wiley:</p>\n\n<ul>\n<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470846747" rel="nofollow noreferrer" rel="nofollow noreferrer">C++ Standard on Amazon</a></li>\n<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470845732" rel="nofollow noreferrer" rel="nofollow noreferrer">C Standard on Amazon</a></li>\n</ul>\n\n<p>Plus, as already mentioned, the working draft for future standards is often available from the committee websites:</p>\n\n<ul>\n<li><a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="nofollow noreferrer">C++ committee website</a></li>\n<li><a href="http://www.open-std.org/jtc1/sc22/wg14/" rel="nofollow noreferrer">C committee website</a></li>\n</ul>\n\n<p>The C-201x draft is available as <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1336.pdf" rel="nofollow noreferrer">N1336</a>, and the C++0x draft as <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3225.pdf" rel="nofollow noreferrer">N3225</a>. </p>\n'}, {'answer_id': 83763, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 10, 'selected': True, 'text': '<h3>PDF versions of the standard</h3>\n<p>As of <strike>1st September 2014</strike> March 2022, the best locations by price for the official C and C++ standards documents in PDF seem to be:</p>\n<ul>\n<li><p>C++20 – ISO/IEC 14882:2020: <a href="https://www.csagroup.org/store/product/CSA%20ISO%25100IEC%2014882%3A21/?format=PDF" rel="noreferrer">212 CAD (about $165 US) from csagroup.org</a></p>\n</li>\n<li><p>C++17 – ISO/IEC 14882:2017: <a href="https://www.standards.govt.nz/shop/isoiec-148822017/" rel="noreferrer">$90 NZD (about $65 US) from Standards New Zealand</a></p>\n</li>\n<li><p>C++14 – ISO/IEC 14882:2014: <a href="https://www.standards.govt.nz/shop/isoiec-148822014/" rel="noreferrer">$90 NZD (about $65 US) from Standards New Zealand</a></p>\n</li>\n<li><p>C++11 – ISO/IEC 14882-2011: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC148822012" rel="noreferrer">$60 from ansi.org</a> or <a href="https://www.techstreet.com/standards/incits-iso-iec-14882-2011-2012?product_id=1852925" rel="noreferrer">$60 from Techstreet</a></p>\n</li>\n<li><p>C++03 – INCITS/ISO/IEC 14882:2003: <a href="https://webstore.ansi.org/standards/incits/incitsisoiec148822003" rel="noreferrer">$30 from ansi.org</a></p>\n</li>\n<li><p>C++98 – ISO/IEC 14882:1998: <a href="https://www.standards.govt.nz/shop/asnzs-148821999/" rel="noreferrer">$95 NZD (about $65 US) from Standards New Zealand</a></p>\n</li>\n<li><p>C17/C18 – INCITS/ISO/IEC 9899:2018: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920182019" rel="noreferrer">$116 from INCITS/ANSI</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">N2176 / c17_updated_proposed_fdis.pdf draft from November 2017</a> (Link broken, see <a href="https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">Wayback Machine N2176</a>)</p>\n</li>\n<li><p>C11 – ISO/IEC 9899:2011: <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC989920112012" rel="noreferrer">$60 from ansi.org</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">WG14 draft version N1570</a></p>\n</li>\n<li><p>C99 – INCITS/ISO/IEC 9899-1999(R2005): <a href="https://webstore.ansi.org/Standards/INCITS/INCITSISOIEC98991999R2005" rel="noreferrer">$60 from ansi.org</a> / <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">WG14 draft version N1256</a></p>\n</li>\n<li><p>C90 – ISO/IEC 9899:1990: <a href="https://www.standards.govt.nz/shop/isoiec-98991990/" rel="noreferrer">$90 NZD (about $65 USD) from Standards New Zealand</a></p>\n</li>\n</ul>\n<h3>Non-PDF electronic versions of the standard</h3>\n<p><em><strong>Warning: most copies of standard drafts are published in PDF format, and errors may have been introduced if the text/HTML was transcribed or automatically generated from the PDF.</strong></em></p>\n<ul>\n<li>C89 – Draft version in ANSI text format: (<a href="https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt" rel="noreferrer">https://web.archive.org/web/20161223125339/http://flash-gordon.me.uk/ansi.c.txt</a>)</li>\n<li>C89 – Draft version as HTML document: (<a href="http://port70.net/%7Ensz/c/c89/c89-draft.html" rel="noreferrer">http://port70.net/~nsz/c/c89/c89-draft.html</a>)</li>\n<li>C90 TC1; ISO/IEC 9899 TCOR1, single-page HTML document: (<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc1.htm</a>)</li>\n<li>C90 TC2; ISO/IEC 9899 TCOR2, single-page HTML document: (<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/tc2.htm</a>)</li>\n<li>C99 – Draft version (N1256) as HTML document: (<a href="http://port70.net/%7Ensz/c/c99/n1256.html" rel="noreferrer">http://port70.net/~nsz/c/c99/n1256.html</a>)</li>\n<li>C11 – Draft version (N1570) as HTML document: (<a href="http://port70.net/%7Ensz/c/c11/n1570.html" rel="noreferrer">http://port70.net/~nsz/c/c11/n1570.html</a>)</li>\n<li>C++11 – Working draft (N3337) as plain text document: (<a href="http://port70.net/%7Ensz/c/c%2B%2B/c%2B%2B11_n3337.txt" rel="noreferrer">http://port70.net/~nsz/c/c%2B%2B/c%2B%2B11_n3337.txt</a>)</li>\n</ul>\n<p><em>(The site hosting the plain text version of the C++11 working draft also has some C++14 drafts in this format. But none of them are copies of the final working draft, N4140.)</em></p>\n<h3>Print versions of the standard</h3>\n<p>Print copies of the standards are available from national standards bodies and <a href="https://www.iso.org/home.html" rel="noreferrer">ISO</a> but are very expensive.</p>\n<p>If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of <a href="http://www.catb.org/jargon/html/B/bullschildt.html" rel="noreferrer">Herb Schildt</a>\'s book <a href="http://www.davros.org/c/schildt.html" rel="noreferrer"><em>The Annotated ANSI Standard</em></a> at <a href="https://rads.stackoverflow.com/amzn/click/com/0078819520" rel="noreferrer" rel="nofollow noreferrer">Amazon</a>, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).</p>\n<p>The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):</p>\n<ul>\n<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470846747" rel="noreferrer" rel="nofollow noreferrer">C++03 Standard</a> on Amazon</li>\n<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470845732" rel="noreferrer" rel="nofollow noreferrer">C99 Standard</a> on Amazon</li>\n</ul>\n<h3>Standards committee draft versions (free)</h3>\n<p>The working drafts for future standards are often available from the committee websites:</p>\n<ul>\n<li><a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="noreferrer">C++ committee website</a></li>\n<li><a href="http://www.open-std.org/jtc1/sc22/wg14/" rel="noreferrer">C committee website</a></li>\n</ul>\n<p>If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:</p>\n<h3>For C:</h3>\n<ul>\n<li><p>ANSI X3.159-198 (C89):\nI cannot find a PDF of C89, but it is almost the same as C90. The only major differences are in the boilerplate and section numbering, although there are some slight textual differences</p>\n</li>\n<li><p>ISO/IEC 9899:1990 (C90):\n(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. There is at least one textual difference in section 6.5.7 (previously 3.5.7), where <em>"a list"</em> became <em>"a brace-enclosed list"</em>. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn\'t the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")</p>\n</li>\n<li><p>TC1 for C90: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n423.pdf</a></p>\n</li>\n<li><p>There isn\'t a PDF link for TC2 on the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/wg14_document_log.htm" rel="noreferrer">WG14 website</a>, sadly.</p>\n</li>\n<li><p>ISO/IEC 9899:1999 (C99 incorporating all three Technical Corrigenda):\n<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf</a></p>\n</li>\n<li><p>An earlier version of C99 incorporating only TC1 and TC2:\n<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf</a></p>\n</li>\n<li><p>Working draft for the original (i.e. pre-corrigenda) C99: <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n843.htm</a> (HTML) and <a href="http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf" rel="noreferrer">http://www.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf</a> (PDF).\nNote that there were two later working drafts: N869 and N878, but they seem to have been removed from the WG14 website, so this is the latest one available.</p>\n</li>\n<li><p>List of changes between C89/C90 and C99: <a href="http://port70.net/%7Ensz/c/c89/c9x_changes.html" rel="noreferrer">http://port70.net/~nsz/c/c89/c9x_changes.html</a></p>\n</li>\n<li><p>TC1 for C99 (only the TC, not the standard incorporating it): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32071.PDF</a></p>\n</li>\n<li><p>TC2 for C99 (only the TC, not the standard incorporating it): <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899-1999_cor_2-2004.pdf</a></p>\n</li>\n<li><p>ISO/IEC 9899:2011 (C11):\n<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf</a></p>\n<p>For information on the differences between N1570 and the final, published version of C11, see <a href="https://stackoverflow.com/questions/8631228/latest-changes-in-c11/15737472#15737472">Latest changes in C11</a> and <a href="https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw" rel="noreferrer">https://groups.google.com/g/comp.std.c/c/v5hsWOu5vSw</a></p>\n</li>\n<li><p>ISO/IEC 9899:2011/Cor 1:2012 (C11\'s only technical corrigendum): This can be viewed at <a href="https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en" rel="noreferrer">https://www.iso.org/obp/ui/#iso:std:iso-iec:9899:ed-3:v1:cor:1:v1:en</a> but cannot be downloaded. It is the actual corrigendum, not a draft.</p>\n</li>\n<li><p>ISO/IEC 9899:2018 (C17/C18):\n<a href="https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf" rel="noreferrer">https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf</a> (N2176)</p>\n</li>\n<li><p>C2x work-in-progress - latest working draft as of 7th August 2022 (N3047):\n<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n3047.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n3047.pdf</a></p>\n</li>\n</ul>\n<h3>For C++:</h3>\n<ul>\n<li><p>ISO/IEC 14882:1998 (C++98):\n<a href="http://www.lirmm.fr/%7Educour/Doc-objets/ISO+IEC+14882-1998.pdf" rel="noreferrer">http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf</a></p>\n</li>\n<li><p>ISO/IEC 14882:2003 (C++03):\n<a href="https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf" rel="noreferrer">https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf</a></p>\n</li>\n<li><p>ISO/IEC 14882:2011 (C++11):\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf</a></p>\n</li>\n<li><p>ISO/IEC 14882:2014 (C++14):\n<a href="https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true" rel="noreferrer">https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true</a></p>\n</li>\n<li><p>ISO/IEC 14882:2017 (C++17):\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf</a></p>\n</li>\n<li><p>ISO/IEC 14882:2020 (C++20): <a href="https://isocpp.org/files/papers/N4860.pdf" rel="noreferrer">https://isocpp.org/files/papers/N4860.pdf</a></p>\n</li>\n<li><p>ISO/IEC 14882:2023 (C++23 work-in-progress. Working draft dated March 17 2022): <a href="https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/n4910.pdf" rel="noreferrer">https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/n4910.pdf</a></p>\n</li>\n</ul>\n<p>Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.</p>\n<p>Even though the draft versions might be very close to the final ratified versions of the standards, some of this post\'s editors would strongly advise you to get a copy of the actual documents — especially if you\'re planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.</p>\n<hr />\n<p>It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post\'s editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on <a href="https://webstore.ansi.org" rel="noreferrer">webstore.ansi.org</a> you will find the reasonably priced PDF version.</p>\n<hr />\n<p>The site <a href="https://wg21.link/" rel="noreferrer">https://wg21.link/</a> provides short-URL links to the C++ current working draft and draft standards, and committee papers:</p>\n<ul>\n<li><a href="https://wg21.link/std11" rel="noreferrer">https://wg21.link/std11</a> - C++11</li>\n<li><a href="https://wg21.link/std14" rel="noreferrer">https://wg21.link/std14</a> - C++14</li>\n<li><a href="https://wg21.link/std17" rel="noreferrer">https://wg21.link/std17</a> - C++17</li>\n<li><a href="https://wg21.link/std20" rel="noreferrer">https://wg21.link/std20</a> - C++20</li>\n<li><a href="https://wg21.link/std" rel="noreferrer">https://wg21.link/std</a> - current working draft (as of May 2022 still points to the 2021 version)</li>\n</ul>\n<hr />\n<p>The current draft of the standard is maintained as LaTeX sources on <a href="https://github.com/cplusplus/draft" rel="noreferrer">Github</a>. These sources can be converted to HTML using <a href="https://github.com/Eelis/cxxdraft-htmlgen" rel="noreferrer">cxxdraft-htmlgen</a>. The following sites maintain HTML pages so generated:</p>\n<ul>\n<li>Tim Song - <a href="https://timsong-cpp.github.io/cppwp/" rel="noreferrer">Current working draft</a> - <a href="https://timsong-cpp.github.io/cppwp/n3337/" rel="noreferrer">C++11</a> - <a href="https://timsong-cpp.github.io/cppwp/n4140/" rel="noreferrer">C++14</a> - <a href="https://timsong-cpp.github.io/cppwp/n4659/" rel="noreferrer">C++17</a> - <a href="https://timsong-cpp.github.io/cppwp/n4861/" rel="noreferrer">C++20</a></li>\n<li>Eelis - <a href="http://eel.is/c++draft/" rel="noreferrer">Current working draft</a></li>\n</ul>\n<p><a href="https://github.com/timsong-cpp/cppwp" rel="noreferrer">Tim Song</a> also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.</p>\n<h3>POSIX extensions to the C standard</h3>\n<p>The <a href="https://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> standard (IEEE 1003.1) requires a compliant operating system to include a C compiler. This compiler must in turn be compliant with the C standard, and must also support various extensions defined in the "System Interfaces" section of POSIX (such as the <code>off_t</code> data type, the <code><aio.h></code> header, the <code>clock_gettime()</code> function and the <code>_POSIX_C_SOURCE</code> macro.)</p>\n<p>So if you\'ve tried to look up a particular function, been informed "This function is part of POSIX, not the C standard", and wondered why an operating system standard was mandating compiler features and language extensions... now you know!</p>\n<ul>\n<li><p>POSIX.1-2001: The System Interfaces section can be downloaded as a separate document from <a href="https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf" rel="noreferrer">https://mirror.math.princeton.edu/pub/oldlinux/download/c951.pdf</a>. Section 1.7 states that the relevant version of the C standard is C99.</p>\n<p>The "Shell and Utilities" section (<a href="https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf" rel="noreferrer">https://mirror.math.princeton.edu/pub/oldlinux/download/c952.pdf</a>) mandates not only that a C99-compliant compiler should exist, but that it should be invokable from the command line under the name "c99". One way in which this can be implemented is to place a shell script called "c99" in /usr/bin, which calls gcc with the <code>-std=c99</code> option added to the list of command-line parameters, and blocks any competing standards from being specified.</p>\n<p>POSIX.1-2001 had two technical corrigenda, one dated 2002 and one dated 2004. I don\'t think they\'re incorporated into the documents as linked above. There\'s an online HTML version incorporating the corrigenda at <a href="https://pubs.opengroup.org/onlinepubs/009695399/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/009695399/</a> - but I should add that I\'ve had some trouble with the search box and so using Google to search the site is probably your best bet.</p>\n<p>There is a paywalled link to download the first corrigendum at <a href="https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html" rel="noreferrer">https://standards.ieee.org/standard/1003_1-2001-Cor1-2002.html</a>.</p>\n<p>There is also a paywalled link for the second at <a href="https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html" rel="noreferrer">https://standards.ieee.org/standard/1003_1-2001-Cor2-2004.html</a></p>\n</li>\n</ul>\n<ul>\n<li><p>There is a draft version of POSIX.1-2008 at <a href="http://www.open-std.org/jtc1/sc22/open/n4217.pdf" rel="noreferrer">http://www.open-std.org/jtc1/sc22/open/n4217.pdf</a>.</p>\n<p>POSIX.1-2008 also had two technical corrigenda, the latter of the two being dated 2016. There is an online HTML version of the standard incorporating the corrigenda at <a href="https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/</a> - though, again, I have had situations where the site\'s own search box wasn\'t good for finding information.</p>\n</li>\n<li><p>There is an online HTML version of POSIX.1-2017 at <a href="https://pubs.opengroup.org/onlinepubs/9699919799/" rel="noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799/</a> - though, again, I recommend using Google instead of that site\'s searchbox. According to the <a href="https://www.opengroup.org/austin/" rel="noreferrer">Open Group website</a> "IEEE 1003.1-2017 ... is a revision to the 1003.1-2008 standard to rollup the standard including its two technical corrigenda (as-is)". <a href="https://man7.org/linux/man-pages/man7/standards.7.html" rel="noreferrer">Linux manpages</a> describe it as "technically identical" to POSIX.1-2008 with Technical Corrigenda 1 and 2 applied. This is therefore not a major revision and does not change the value of the <code>_POSIX_C_SOURCE</code> macro.</p>\n</li>\n</ul>\n'}, {'answer_id': 84549, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>C99 is <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">available online</a>. Quoted from <a href="http://www.open-std.org/jtc1/sc22/wg14/www/standards.html#9899" rel="noreferrer">www.open-std.org</a>:</p>\n\n<blockquote>\n <p>The lastest publically available version of the standard is the\n combined C99 + TC1 + TC2 + TC3, <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">WG14 N1256</a>, dated 2007-09-07. This is\n a WG14 working paper, but it reflects the consolidated standard at the\n time of issue.</p>\n</blockquote>\n'}, {'answer_id': 84613, 'author': 'Kris Kumler', 'author_id': 4281, 'author_profile': 'https://Stackoverflow.com/users/4281', 'pm_score': 2, 'selected': False, 'text': '<p>The actual standards documents may not be the most useful. Most compilers do not fully implement the standards and may sometimes actually conflict. So the compiler documentation that you would already have will be more useful. Additionally, the documentation will contain platform-specific remarks and notes on any caveats.</p>\n'}, {'answer_id': 4653479, 'author': 'Martin York', 'author_id': 14065, 'author_profile': 'https://Stackoverflow.com/users/14065', 'pm_score': 9, 'selected': False, 'text': '<p>Online versions of the standard can be found:</p>\n<h3>Working Draft, Standard for Programming Language C++</h3>\n<p><em><strong>The following all draft versions of the standard</strong></em>:</p>\n<p>All the following are freely downloadable<br />\n2022-09-05: <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4917.pdf" rel="nofollow noreferrer">N4917</a><br />\n2022-03-17: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4910.pdf" rel="nofollow noreferrer">N4910</a><br />\n2021-10-22: <a href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4901.pdf" rel="nofollow noreferrer">N4901</a><br />\n2021-06-18: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4892.pdf" rel="nofollow noreferrer">N4892</a><br />\n2021-03-17: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4885.pdf" rel="nofollow noreferrer">N4885</a><br />\n2020-12-15: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4878.pdf" rel="nofollow noreferrer">N4878</a><br />\n2020-10-18: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4868.pdf" rel="nofollow noreferrer">N4868</a><br />\n2020-04-08: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4861.pdf" rel="nofollow noreferrer">N4861</a></p>\n<p><em><strong>This is the C++20 Standard:</strong></em><br />\nThis version requires Authentication<br />\n2020-04-08: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4860.pdf" rel="nofollow noreferrer">N4860</a></p>\n<p><em><strong>The following all draft versions of the standard</strong></em>:<br />\nAll the following are freely downloadable<br />\n(many of these can be found at this <a href="https://github.com/cplusplus/draft/tree/master/papers" rel="nofollow noreferrer">main GitHub link</a>)<br />\n2020-01-14: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4849.pdf" rel="nofollow noreferrer">N4849</a><br />\n2019-11-27: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4842.pdf" rel="nofollow noreferrer">N4842</a><br />\n2019-10-08: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4835.pdf" rel="nofollow noreferrer">N4835</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4835.pdf" rel="nofollow noreferrer">git</a><br />\n2019-08-15: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4830.pdf" rel="nofollow noreferrer">N4830</a> <a href="https://github.com/cplusplus/draft/blob/master/papers//n4830.pdf" rel="nofollow noreferrer">git</a><br />\n2019-06-17: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4820.pdf" rel="nofollow noreferrer">N4820</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4820.pdf" rel="nofollow noreferrer">git</a><br />\n2019-03-15: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4810.pdf" rel="nofollow noreferrer">N4810</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4810.pdf" rel="nofollow noreferrer">git</a><br />\n2019-01-21: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/n4800.pdf" rel="nofollow noreferrer">N4800</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4800.pdf" rel="nofollow noreferrer">git</a><br />\n2018-11-26: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4791.pdf" rel="nofollow noreferrer">N4791</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4791.pdf" rel="nofollow noreferrer">git</a><br />\n2018-10-08: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4778.pdf" rel="nofollow noreferrer">N4778</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4778.pdf" rel="nofollow noreferrer">git</a><br />\n2018-07-07: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4762.pdf" rel="nofollow noreferrer">N4762</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4762.pdf" rel="nofollow noreferrer">git</a><br />\n2018-05-07: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4750.pdf" rel="nofollow noreferrer">N4750</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4750.pdf" rel="nofollow noreferrer">git</a><br />\n2018-04-02: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4741.pdf" rel="nofollow noreferrer">N4741</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4741.pdf" rel="nofollow noreferrer">git</a><br />\n2018-02-12: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4727.pdf" rel="nofollow noreferrer">N4727</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4727.pdf" rel="nofollow noreferrer">git</a><br />\n2017-11-27: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf" rel="nofollow noreferrer">N4713</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4713.pdf" rel="nofollow noreferrer">git</a><br />\n2017-10-16: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4700.pdf" rel="nofollow noreferrer">N4700</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4700.pdf" rel="nofollow noreferrer">git</a><br />\n2017-07-30: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4687.pdf" rel="nofollow noreferrer">N4687</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4687.pdf" rel="nofollow noreferrer">git</a></p>\n<p><em><strong>This is the old C++17 Standard:</strong></em><br />\nThis version requires Authentication<br />\n2017-03-21: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4660.pdf" rel="nofollow noreferrer">N4660</a></p>\n<p><em><strong>The following all draft versions of the standard</strong></em>:<br />\nAll the following are freely downloadable<br />\n2017-03-21: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf" rel="nofollow noreferrer">N4659</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4659.pdf" rel="nofollow noreferrer">git</a><br />\n2017-02-06: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4640.pdf" rel="nofollow noreferrer">N4640</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4640.pdf" rel="nofollow noreferrer">git</a><br />\n2016-11-28: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4618.pdf" rel="nofollow noreferrer">N4618</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4618.pdf" rel="nofollow noreferrer">git</a><br />\n2016-07-12: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf" rel="nofollow noreferrer">N4606</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4606.pdf" rel="nofollow noreferrer">git</a><br />\n2016-05-30: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4594.pdf" rel="nofollow noreferrer">N4594</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4594.pdf" rel="nofollow noreferrer">git</a><br />\n2016-03-19: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4582.pdf" rel="nofollow noreferrer">N4582</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4582.pdf" rel="nofollow noreferrer">git</a><br />\n2015-11-09: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4567.pdf" rel="nofollow noreferrer">N4567</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4567.pdf" rel="nofollow noreferrer">git</a><br />\n2015-05-22: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4527.pdf" rel="nofollow noreferrer">N4527</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4527.pdf" rel="nofollow noreferrer">git</a><br />\n2015-04-10: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4431.pdf" rel="nofollow noreferrer">N4431</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4431.pdf" rel="nofollow noreferrer">git</a><br />\n2014-11-19: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf" rel="nofollow noreferrer">N4296</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4296.pdf" rel="nofollow noreferrer">git</a></p>\n<p><em><strong>This is the old C++14 standard</strong></em>:<br />\nThese version requires Authentication<br />\n2014-10-07: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4140.pdf" rel="nofollow noreferrer">N4140</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf" rel="nofollow noreferrer">git</a> Essentially C++14 with minor errors and typos corrected<br />\n2014-09-02: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n4141.pdf" rel="nofollow noreferrer">N4141</a> <a href="https://github.com/cplusplus/draft/tree/n4141" rel="nofollow noreferrer">git</a> Standard C++14<br />\n2014-03-02: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n3937.pdf" rel="nofollow noreferrer">N3937</a><br />\n2014-03-02: <a href="http://www.open-std.org/jtc1/sc22/wg21/prot/14882fdis/n3936.pdf" rel="nofollow noreferrer">N3936</a> <a href="https://github.com/cplusplus/draft/blob/b7b8ed08ba4c111ad03e13e8524a1b746cb74ec6/papers/N3936.pdf" rel="nofollow noreferrer">git</a></p>\n<p><em><strong>The following all draft versions of the standard</strong></em>:<br />\nAll the following are freely downloadable<br />\n2013-10-13: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf" rel="nofollow noreferrer">N3797</a> <a href="https://github.com/cplusplus/draft/blob/master/papers/N3797.pdf" rel="nofollow noreferrer">git</a><br />\n2013-05-16: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3691.pdf" rel="nofollow noreferrer">N3691</a><br />\n2013-05-15: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf" rel="nofollow noreferrer">N3690</a><br />\n2012-11-02: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf" rel="nofollow noreferrer">N3485</a><br />\n2012-02-28: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf" rel="nofollow noreferrer">N3376</a><br />\n2012-01-16: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="nofollow noreferrer">N3337</a> <a href="https://github.com/cplusplus/draft/tree/n3337" rel="nofollow noreferrer">git</a> Essentially C++11 with minor errors and typos corrected</p>\n<p><em><strong>This is the old C++11 Standard</strong></em>:<br />\nThis version requires Authentication<br />\n2011-04-05: <a href="http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n3291.pdf" rel="nofollow noreferrer">N3291</a></p>\n<p><em><strong>The following all draft versions of the standard</strong></em>:<br />\nAll the following are freely downloadable<br />\n2011-02-28: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2011/n3242.pdf" rel="nofollow noreferrer">N3242</a> (differences from N3291 very minor)<br />\n2010-11-27: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3225.pdf" rel="nofollow noreferrer">N3225</a><br />\n2010-08-21: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3126.pdf" rel="nofollow noreferrer">N3126</a><br />\n2010-03-29: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3090.pdf" rel="nofollow noreferrer">N3090</a><br />\n2010-02-16: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2010/n3035.pdf" rel="nofollow noreferrer">N3035</a><br />\n2009-11-09: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n3000.pdf" rel="nofollow noreferrer">N3000</a><br />\n2009-09-25: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2960.pdf" rel="nofollow noreferrer">N2960</a><br />\n2009-06-22: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2914.pdf" rel="nofollow noreferrer">N2914</a><br />\n2009-03-23: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2857.pdf" rel="nofollow noreferrer">N2857</a><br />\n2008-10-04: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2798.pdf" rel="nofollow noreferrer">N2798</a><br />\n2008-08-25: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2723.pdf" rel="nofollow noreferrer">N2723</a><br />\n2008-06-27: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2691.pdf" rel="nofollow noreferrer">N2691</a><br />\n2008-05-19: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2606.pdf" rel="nofollow noreferrer">N2606</a><br />\n2008-03-17: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2588.pdf" rel="nofollow noreferrer">N2588</a><br />\n2008-02-04: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2521.pdf" rel="nofollow noreferrer">N2521</a><br />\n2007-10-22: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2461.pdf" rel="nofollow noreferrer">N2461</a><br />\n2007-08-06: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2369.pdf" rel="nofollow noreferrer">N2369</a><br />\n2007-06-25: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2315.pdf" rel="nofollow noreferrer">N2315</a><br />\n2007-05-07: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2284.pdf" rel="nofollow noreferrer">N2284</a><br />\n2006-11-03: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2006/n2134.pdf" rel="nofollow noreferrer">N2134</a><br />\n2006-04-21: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2006/n2009.pdf" rel="nofollow noreferrer">N2009</a><br />\n2005-10-19: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1905.pdf" rel="nofollow noreferrer">N1905</a><br />\n2005-04-27: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1804.pdf" rel="nofollow noreferrer">N1804</a></p>\n<p><strong>This is the old C++03 Standard:</strong><br />\nAll the below versions require Authentication<br />\n2004-11-05: <a href="http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1733.pdf" rel="nofollow noreferrer">N1733</a><br />\n2004-07-16: <a href="http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1655.pdf" rel="nofollow noreferrer">N1655</a> Unofficial<br />\n2004-02-07: <a href="http://www.open-std.org/Jtc1/sc22/wg21/prot/14882fdis/n1577.pdf" rel="nofollow noreferrer">N1577</a> C++03 (Or Very Close)<br />\n2001-09-13: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2001/n1316" rel="nofollow noreferrer">N1316</a> Draft Expanded Technical Corrigendum<br />\n1997-00-00: N1117 Draft Expanded Technical Corrigendum</p>\n<p><em><strong>The following all draft versions of the standard</strong></em>:<br />\nAll the following are freely downloadable<br />\n1996-00-00: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/1996/N0836.pdf" rel="nofollow noreferrer">N0836</a> Draft Expanded Technical Corrigendum<br />\n1995-00-00: N0785 Working Paper for Draft Proposed International Standard for Information Systems - Programming Language C++</p>\n<h3>Other Interesting Papers:</h3>\n<p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/" rel="nofollow noreferrer">2022</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/" rel="nofollow noreferrer">2021</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/" rel="nofollow noreferrer">2020</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/" rel="nofollow noreferrer">2019</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/" rel="nofollow noreferrer">2018</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/" rel="nofollow noreferrer">2017</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/" rel="nofollow noreferrer">2016</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/" rel="nofollow noreferrer">2015</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/" rel="nofollow noreferrer">2014</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/" rel="nofollow noreferrer">2013</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/" rel="nofollow noreferrer">2012</a> /\n<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/" rel="nofollow noreferrer">2011</a></p>\n'}, {'answer_id': 10464974, 'author': 'user1055604', 'author_id': 1055604, 'author_profile': 'https://Stackoverflow.com/users/1055604', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Draft Links:</strong></p>\n<p>C++11 (+editorial fixes): N3337 <a href="https://timsong-cpp.github.io/cppwp/n3337/" rel="noreferrer">HTML</a>, <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="noreferrer">PDF</a></p>\n<p>C++14 (+editorial fixes): N4140 <a href="https://timsong-cpp.github.io/cppwp/n4140/" rel="noreferrer">HTML</a>, <a href="https://timsong-cpp.github.io/cppwp/n4140/draft.pdf" rel="noreferrer">PDF</a></p>\n<p>C11 <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">N1570</a> (<a href="http://www.iso-9899.info/n1570.html" rel="noreferrer">text</a>)</p>\n<p>C99 <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">N1256</a></p>\n<blockquote>\n<p><a href="http://clc-wiki.net/wiki/c_standard#Drafts" rel="noreferrer">Drafts</a> of the Standard are circulated for comment prior to ratification and publication.</p>\n<p><a href="http://herbsutter.com/2010/03/03/where-can-you-get-the-iso-c-standard-and-what-does-open-standard-mean/" rel="noreferrer">Note</a> that a working draft is not the standard currently in force, and it is not exactly the published standard</p>\n</blockquote>\n'}, {'answer_id': 18282656, 'author': 'jxh', 'author_id': 315052, 'author_profile': 'https://Stackoverflow.com/users/315052', 'pm_score': 3, 'selected': False, 'text': '<p>The text of a <a href="http://www.bsb.me.uk/ansi-c/ansi-c-one-file" rel="nofollow noreferrer">draft of the ANSI C standard</a> (aka C.89) is available online. This was standardized by the ANSI committee prior to acceptance by the ISO C Standard (C.90), so the numbering of the sections differ (ANSI sections 2 through 4 correspond roughly to ISO sections 5 through 7), although the content is (supposed to be) largely identical. </p>\n'}, {'answer_id': 27359265, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Although not an actual standard, there is an amendment to ISO C (C89/90) called C94/95, or Normative Addendum 1. It was integrated into C99, although some compilers such as <a href="http://clang.llvm.org/docs/UsersManual.html" rel="nofollow">Clang</a> allow you to specifiy <code>-std=c94</code> on the command line. ISO/IEC 9899:1990/Amd 1:1995 can be purchased for a hefty price from <a href="http://infostore.saiglobal.com/store/Details.aspx?DocN=isoc000767513" rel="nofollow"><strong>SAI GLOBAL</strong></a> (PDF or hard copy).</p>\n\n<ul>\n<li><a href="http://clc-wiki.net/wiki/The_C_Standard" rel="nofollow">http://clc-wiki.net/wiki/The_C_Standard</a></li>\n</ul>\n\n<p>A summary of the document can be found <a href="http://www.lysator.liu.se/c/na1.html" rel="nofollow">here</a>.</p>\n\n<blockquote>\n <p>When the (then draft) ANSI C Standard was being considered for\n adoption of an International Standard in 1990, there were several\n objections because it didn\'t address internationalization issues. \n Because the Standard had already been several years in the making, it\n was agreed that a few changes would be made to provide the basis (for\n example, the functions in subclause 7.10.7 were added), and work would\n be carried out separately to provide proper internationalization of\n the Standard. This work has culminated in Normative Addendum 1.</p>\n \n <p>Normative Addendum 1 embodies C\'s reaction to both the limitations and\n promises of international character sets. Digraphs and the \n header were meant to improve the appearance of C programs written in\n national variants of ISO 646 without, e.g., { or } characters. On the\n other end of the spectrum, the facilities connected to and\n extend the old Standard\'s barely adequate basis into a\n complete and consistent set of utilities for handling wide characters\n and multibyte strings.</p>\n \n <p>This document summarizes Normative Addendum 1. It is intended to\n quickly inform readers who are already familiar with the Standard; it\n does not, and cannot, introduce the complex subject matter behind NA1,\n nor can it replace the original document as a reference manual. \n (Nevertheless, it tries to be as accurate as possible, and its author\n would like to hear about any errors or omissions.)</p>\n</blockquote>\n\n<ul>\n<li><a href="http://www.lysator.liu.se/c/na1.html" rel="nofollow">http://www.lysator.liu.se/c/na1.html</a></li>\n</ul>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15514/'] |
81,657 | <p>What is the most efficient, secure way to pipe the contents of a postgresSQL database into a compressed tarfile, then copy to another machine?</p>
<p>This would be used for localhosting development, or backing up to a remote server, using *nix based machines at both ends.</p>
| [{'answer_id': 81679, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.cyberciti.biz/faq/how-to-back-up-a-web-server/" rel="nofollow noreferrer">This page</a> has a complete backup script for a webserver, including the pg_dump output.</p>\n\n<p>Here is the syntax it uses:</p>\n\n<pre><code>BACKUP="/backup/$NOW"\nPFILE="$(hostname).$(date +\'%T\').pg.sql.gz"\nPGSQLUSER="vivek"\nPGDUMP="/usr/bin/pg_dump"\n\n$PGDUMP -x -D -U${PGSQLUSER} | $GZIP -c > ${BACKUP}/${PFILE}\n</code></pre>\n\n<p>After you have gzipped it, you can transfer it to the other server with <a href="http://en.wikipedia.org/wiki/Secure_copy" rel="nofollow noreferrer">scp</a>, <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">rsync</a> or <a href="http://en.wikipedia.org/wiki/Network_file_system" rel="nofollow noreferrer">nfs</a> depending on your network and services.</p>\n'}, {'answer_id': 82210, 'author': 'bortzmeyer', 'author_id': 15625, 'author_profile': 'https://Stackoverflow.com/users/15625', 'pm_score': 1, 'selected': True, 'text': "<p>pg_dump is indeed the proper solution. Be sure to read the man page. In Espo's example, some options are questionable (-x and -D) and may not suit you.</p>\n\n<p>As with every other database manipulation, test a lot!</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15479/'] |
81,671 | <p>I would like to display an RTF document in an SWT (actually Eclipse RCP) application.</p>
<p>I know there is a Swing widget for displaying and editing RTF text, but it is Swing and quite alien in look and feel when used in the otherwise platform (not to mention that to the last of my knowledge it did not display images and had only limited support for formatting)</p>
<p>Other options is to use COM interface on windows, but that works only on the windows platform and requires that an ActiveX RichEdit contol be installed on the customer machine... which can make the deployment of the application quite horrendous...</p>
<p>What are the other options for displaying rich documents inside Eclipse/SWT application?</p>
| [{'answer_id': 81719, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 1, 'selected': False, 'text': "<p>You may use swt.custom.StyledText. That has many features to change the look of the text. But I don't think it can load or save RTF right now.</p>\n\n<p>I once wrote an HTML editor with it, but it is quite difficult, since the StyledText model to add styles to a part of the text is so alien compared to the way HTML/RTF works.</p>\n\n<p>AFAIK you can directly print from this control, which internally creates an RTF representation of the contents. But that's not exactly what you asked for.</p>\n"}, {'answer_id': 165279, 'author': 'BlueVoid', 'author_id': 193278, 'author_profile': 'https://Stackoverflow.com/users/193278', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure of a way to do it without using ActiveX. If you do go this direction you might want to look into the <a href="http://www.alphaworks.ibm.com/tech/swtactivexcontainer?open&S_TACT=106AH21W&S_CMP=AWRSSJAV" rel="nofollow noreferrer">IBM Container for ActiveX Documents</a>, which is supposed to allow better integration of documents.</p>\n'}, {'answer_id': 170079, 'author': 'extraneon', 'author_id': 24582, 'author_profile': 'https://Stackoverflow.com/users/24582', 'pm_score': 1, 'selected': False, 'text': '<p>Why not first read the RTF text into a StyledDocument using the RTFEditorKit and then writing the StyledDocument to a StringWriter using the HTMLEditorKit?</p>\n\n<pre><code>String rtf = "whatever";\nBufferedReader input = new BufferedReader(new StringReader(rtf));\n\nRTFEditorKit rtfKit = new RTFEditorKit();\nStyledDocument doc = (StyledDocument) rtfKit.createDefaultDocument();\nrtfEdtrKt.read( input, doc, 0 );\ninput.close();\n\nHTMLEditorKit htmlKit = new HTMLEditorKit(); \nStringWriter output = new StringWriter();\nhtmlKit.write( output, doc, 0, doc.getLength());\n\nString html = output.toString();\n</code></pre>\n\n<p>And then display the HTML?</p>\n'}, {'answer_id': 269138, 'author': 'Aaron Digulla', 'author_id': 34088, 'author_profile': 'https://Stackoverflow.com/users/34088', 'pm_score': 1, 'selected': False, 'text': '<p>You might want to use the Swing control with the <a href="http://www.eclipsezone.com/eclipse/forums/t45697.html" rel="nofollow noreferrer">AWT/SWT bridge</a>. I used this to embed OpenOffice into an SWT app:</p>\n\n<pre><code>package ooswtviewer;\n\nimport java.awt.Panel;\n\nimport com.sun.star.awt.XView;\nimport com.sun.star.beans.Property;\nimport com.sun.star.beans.UnknownPropertyException;\nimport com.sun.star.beans.XPropertySet;\nimport com.sun.star.comp.beans.Frame;\nimport com.sun.star.comp.beans.NoConnectionException;\nimport com.sun.star.comp.beans.OOoBean;\nimport com.sun.star.comp.beans.OfficeDocument;\nimport com.sun.star.drawing.XDrawView;\nimport com.sun.star.frame.XController;\nimport com.sun.star.frame.XDesktop;\nimport com.sun.star.frame.XFrame;\nimport com.sun.star.frame.XFramesSupplier;\nimport com.sun.star.frame.XLayoutManager;\nimport com.sun.star.frame.XModel;\nimport com.sun.star.lang.WrappedTargetException;\nimport com.sun.star.ui.XUIElement;\nimport com.sun.star.uno.Any;\nimport com.sun.star.uno.UnoRuntime;\nimport com.sun.star.uno.XInterface;\nimport com.sun.star.view.XViewSettingsSupplier;\n\n/**\n * Code based on example from http://www.eclipsezone.com/eclipse/forums/t48966.html\n * \n * @author Aaron digulla\n */\npublic class OOoSwtViewer extends Panel\n{\n private static final String RESOURCE_TOOLBAR_TEXTOBJECTBAR = "private:resource/toolbar/textobjectbar";\n private static final String RESOURCE_TOOLBAR_STANDARDBAR = "private:resource/toolbar/standardbar";\n private static final String RESOURCE_MENUBAR = "private:resource/menubar/menubar";\n\n private static final long serialVersionUID = -1408623115735065822L;\n\n private OOoBean aBean;\n\n public OOoSwtViewer()\n {\n super();\n aBean = new OOoBean();\n setLayout(new java.awt.BorderLayout());\n add(aBean, java.awt.BorderLayout.CENTER);\n\n aBean.setAllBarsVisible (false);\n }\n\n public XPropertySet getXPropertySet ()\n {\n return getXPropertySet (getFrame ());\n }\n\n public XPropertySet getXPropertySet (Object o)\n {\n return (XPropertySet)UnoRuntime.queryInterface (XPropertySet.class, o);\n }\n\n public Frame getFrame ()\n {\n try\n {\n return aBean.getFrame ();\n }\n catch (NoConnectionException e)\n {\n throw new OOException ("Error getting frame from bean", e);\n }\n }\n\n public XLayoutManager getXLayoutManager ()\n {\n try\n {\n return (XLayoutManager)UnoRuntime.queryInterface (XLayoutManager.class, getXPropertySet ().getPropertyValue ("LayoutManager"));\n }\n catch (Exception e)\n {\n throw new OOException ("Error getting LayoutManager from bean\'s properties", e);\n } \n }\n\n public void setMenuBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_MENUBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_MENUBAR);\n }\n\n public void setStandardBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_TOOLBAR_STANDARDBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_TOOLBAR_STANDARDBAR);\n }\n\n public void setTextObjectBarVisible (boolean visible)\n {\n if (visible)\n getXLayoutManager ().showElement (RESOURCE_TOOLBAR_TEXTOBJECTBAR);\n else\n getXLayoutManager ().hideElement (RESOURCE_TOOLBAR_TEXTOBJECTBAR);\n }\n\n\n private Thread loadThread;\n private Exception loadException;\n\n public void setDocument(final String url)\n {\n loadThread = new Thread () {\n public void run() {\n try\n {\n aBean.loadFromURL(url, null);\n aBean.aquireSystemWindow();\n\n setTextObjectBarVisible (false);\n\n// for (XUIElement e: getXLayoutManager ().getElements ())\n// {\n// XInterface i = (XInterface)e.getRealInterface ();\n// System.out.println (e);\n// System.out.println (i);\n// printProperties (getXPropertySet (e));\n// }\n\n /*\n System.out.println ("frame:");\n printProperties (getXPropertySet ());\n\nframe:\nTitle=test - OpenOffice.org Writer \nIndicatorInterception=Any[Type[com.sun.star.task.XStatusIndicator], null]\nLayoutManager=Any[Type[com.sun.star.frame.XLayoutManager], [Proxy:26506390,717ea70;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XLayoutManager]]]\nDispatchRecorderSupplier=Any[Type[com.sun.star.frame.XDispatchRecorderSupplier], null]\nIsHidden=false\n */\n\n XController controller = aBean.getDocument ().getCurrentController ();\n /*\n System.out.println ("controller:");\n printProperties (getXPropertySet (controller));\n\ncontroller:\nIsConstantSpellcheck=true\nIsHideSpellMarks=false\nLineCount=1\nPageCount=1\n */\n\n /*\n System.out.println ("layoutManager:");\n printProperties (getXPropertySet (getXLayoutManager ()));\n\nlayoutManager:\nAutomaticToolbars=true\nHideCurrentUI=false\nLockCount=0\nMenuBarCloser=true\nRefreshContextToolbarVisibility=false\n */\n\n /*\n System.out.println ("document:");\n printProperties (getXPropertySet (aBean.getDocument ()));\n OfficeDocument doc = aBean.getDocument ();\nApplyFormDesignMode=false\nApplyWorkaroundForB6375613=false\nAutomaticControlFocus=false\nBasicLibraries=Any[Type[com.sun.star.script.XLibraryContainer], [Proxy:14806696,73ca178;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.script.XLibraryContainer]]]\nBuildId=680$9310\nCharFontCharSet=1\nCharFontCharSetAsian=1\nCharFontCharSetComplex=1\nCharFontFamily=3\nCharFontFamilyAsian=6\nCharFontFamilyComplex=6\nCharFontName=Times New Roman\nCharFontNameAsian=Arial Unicode MS\nCharFontNameComplex=Tahoma\nCharFontPitch=2\nCharFontPitchAsian=2\nCharFontPitchComplex=2\nCharFontStyleName=\nCharFontStyleNameAsian=\nCharFontStyleNameComplex=\nCharLocale=com.sun.star.lang.Locale@fb6354\nCharacterCount=20\nDialogLibraries=Any[Type[com.sun.star.script.XLibraryContainer], [Proxy:3556929,73a39c0;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.script.XLibraryContainer]]]\nForbiddenCharacters=Any[Type[com.sun.star.i18n.XForbiddenCharacters], [Proxy:11544872,7669148;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.i18n.XForbiddenCharacters]]]\nHasValidSignatures=false\nHideFieldTips=false\nIndexAutoMarkFileURL=\nLockUpdates=false\nParagraphCount=1\nRecordChanges=false\nRedlineDisplayType=2\nRedlineProtectionKey=[B@f593af\nRuntimeUID=10\nShowChanges=true\nTwoDigitYear=1930\nWordCount=5\nWordSeparator=() \n */\n\n// System.out.println ("viewData:");\n// printProperties (getXPropertySet (controller.getFrame ().getContainerWindow ()));\n\n XViewSettingsSupplier settingsSupplier = (XViewSettingsSupplier)UnoRuntime.queryInterface (XViewSettingsSupplier.class, controller);\n// System.out.println ("settingsSupplier:");\n// printProperties (settingsSupplier.getViewSettings ());\n settingsSupplier.getViewSettings ().setPropertyValue ("ShowVertRuler", Boolean.FALSE);\n settingsSupplier.getViewSettings ().setPropertyValue ("ShowHoriRuler", Boolean.FALSE);\n // Switch to Web Layout. This layout mode comes without gray border and the page borders automatically adujst to the frame\n settingsSupplier.getViewSettings ().setPropertyValue ("ShowOnlineLayout", Boolean.TRUE);\n// settingsSupplier.getViewSettings ().setPropertyValue ("ShowTextBoundaries", Boolean.TRUE);\n\n// XView view = (XView)UnoRuntime.queryInterface (XView.class, getFrame ());\n// System.out.println ("drawView="+view);\n// printProperties (getXPropertySet (view));\n\n /*\n XModel model = (XModel)UnoRuntime.queryInterface (XModel.class, doc);\n printProperties ("model", model);\n\n Same as getDocument()\n */\n\n /*\n System.out.println ("Interfaces implemented by aBean.getDocument():");\n for (Class c: OOoInspector.queryInterface (aBean.getDocument ()))\n System.out.println (" "+c.getName ());\n com.sun.star.datatransfer.XTransferable\n com.sun.star.document.XDocumentInfoSupplier\n com.sun.star.document.XDocumentLanguages\n com.sun.star.document.XDocumentSubStorageSupplier\n com.sun.star.document.XEmbeddedScripts\n com.sun.star.document.XEventBroadcaster\n com.sun.star.document.XEventsSupplier\n com.sun.star.document.XLinkTargetSupplier\n com.sun.star.document.XRedlinesSupplier\n com.sun.star.document.XStorageBasedDocument\n com.sun.star.document.XViewDataSupplier\n com.sun.star.drawing.XDrawPageSupplier\n com.sun.star.embed.XVisualObject\n com.sun.star.frame.XLoadable\n com.sun.star.frame.XModel\n com.sun.star.frame.XModel2\n com.sun.star.frame.XModule\n com.sun.star.frame.XStorable\n com.sun.star.frame.XStorable2\n com.sun.star.script.provider.XScriptProviderSupplier\n com.sun.star.style.XAutoStylesSupplier\n com.sun.star.style.XStyleFamiliesSupplier\n com.sun.star.text.XBookmarksSupplier\n com.sun.star.text.XChapterNumberingSupplier\n com.sun.star.text.XDocumentIndexesSupplier\n com.sun.star.text.XEndnotesSupplier\n com.sun.star.text.XFootnotesSupplier\n com.sun.star.text.XLineNumberingProperties\n com.sun.star.text.XNumberingRulesSupplier\n com.sun.star.text.XPagePrintable\n com.sun.star.text.XReferenceMarksSupplier\n com.sun.star.text.XTextDocument\n com.sun.star.text.XTextEmbeddedObjectsSupplier\n com.sun.star.text.XTextFieldsSupplier\n com.sun.star.text.XTextFramesSupplier\n com.sun.star.text.XTextGraphicObjectsSupplier\n com.sun.star.text.XTextSectionsSupplier\n com.sun.star.text.XTextTablesSupplier\n com.sun.star.ui.XUIConfigurationManagerSupplier\n com.sun.star.util.XCloseable\n com.sun.star.util.XCloseBroadcaster\n com.sun.star.util.XLinkUpdate\n com.sun.star.util.XModifiable\n com.sun.star.util.XModifiable2\n com.sun.star.util.XModifyBroadcaster\n com.sun.star.util.XNumberFormatsSupplier\n com.sun.star.util.XRefreshable\n com.sun.star.util.XReplaceable\n com.sun.star.util.XSearchable\n com.sun.star.view.XPrintable\n com.sun.star.view.XPrintJobBroadcaster\n com.sun.star.view.XRenderable\n com.sun.star.xforms.XFormsSupplier\n */\n\n /*\n System.out.println ("Interfaces implemented by controller:");\n for (Class c: OOoInspector.queryInterface (controller))\n System.out.println (" "+c.getName ());\n\n com.sun.star.awt.XUserInputInterception\n com.sun.star.datatransfer.XTransferableSupplier\n com.sun.star.frame.XController\n com.sun.star.frame.XControllerBorder\n com.sun.star.frame.XDispatchInformationProvider\n com.sun.star.frame.XDispatchProvider\n com.sun.star.task.XStatusIndicatorSupplier\n com.sun.star.text.XRubySelection\n com.sun.star.text.XTextViewCursorSupplier\n com.sun.star.ui.XContextMenuInterception\n com.sun.star.view.XControlAccess\n com.sun.star.view.XFormLayerAccess\n com.sun.star.view.XSelectionSupplier\n com.sun.star.view.XViewSettingsSupplier\n */\n\n /*\n System.out.println ("Interfaces implemented by frame:");\n for (Class c: OOoInspector.queryInterface (getFrame ()))\n System.out.println (" "+c.getName ());\n\n com.sun.star.awt.XFocusListener\n com.sun.star.awt.XTopWindowListener\n com.sun.star.awt.XWindowListener\n com.sun.star.document.XActionLockable\n com.sun.star.frame.XComponentLoader\n com.sun.star.frame.XDispatchInformationProvider\n com.sun.star.frame.XDispatchProvider\n com.sun.star.frame.XDispatchProviderInterception\n com.sun.star.frame.XFrame\n com.sun.star.frame.XFramesSupplier\n com.sun.star.task.XStatusIndicatorFactory\n com.sun.star.util.XCloseable\n com.sun.star.util.XCloseBroadcaster\n */\n\n /*\n XFramesSupplier frames = OOoInspector.queryInterface (XFramesSupplier.class, getFrame ());\n printProperties ("frames", frames);\n\n for (int i=0; i<frames.getFrames ().getCount (); i++)\n {\n XFrame frame = (XFrame)frames.getFrames ().getByIndex (i);\n printProperties ("Frame "+i, frame);\n }\n\nframes=[Proxy:16382237,6ace84c;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XFramesSupplier]]\nTitle=test - OpenOffice.org Writer \nIndicatorInterception=Any[Type[com.sun.star.task.XStatusIndicator], null]\nLayoutManager=Any[Type[com.sun.star.frame.XLayoutManager], [Proxy:22149392,76bd794;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.frame.XLayoutManager]]]\nDispatchRecorderSupplier=Any[Type[com.sun.star.frame.XDispatchRecorderSupplier], null]\nIsHidden=false\n */\n XPropertySet p = getXPropertySet (getFrame ());\n Any any = (Any)p.getPropertyValue ("LayoutManager");\n System.out.println (any);\n System.out.println (any.getClass ().getName ());\n XLayoutManager layoutManager = (XLayoutManager)any.getObject ();\n printProperties ("layoutManager", layoutManager);\n\n\n /*\n printProperties ("containerWindow", getFrame ().getContainerWindow ());\n\ncontainerWindow=[Proxy:11970262,6d33e60;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.awt.XWindow]]\nnull\n */\n\n /*\n printProperties ("componentWindow", getFrame ().getComponentWindow ());\n\ncomponentWindow=[Proxy:25380515,8657cc4;msci[0];342169f1a1164ee688893a857f65b3e1,Type[com.sun.star.awt.XWindow]]\nnull\n */\n }\n catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n };\n if (1 == 1)\n loadThread.start ();\n else\n loadThread.run ();\n }\n\n /** closes the bean viewer and tries to terminate OOo.\n */\n public void terminate() throws NoConnectionException {\n setVisible(false);\n XDesktop xDesktop = null;\n xDesktop = aBean.getOOoDesktop();\n aBean.stopOOoConnection();\n if (xDesktop != null)\n xDesktop.terminate();\n }\n\n /** closes the bean viewer, leaves OOo running.\n */\n public void close() {\n setVisible(false);\n aBean.stopOOoConnection();\n }\n\n public void printProperties (String name, Object obj)\n {\n System.out.println (name+"="+obj);\n if (obj != null)\n printProperties (getXPropertySet (obj));\n }\n\n public void printProperties (XPropertySet set)\n {\n if (set == null)\n {\n System.out.println ("null");\n return;\n }\n\n for (Property p: set.getPropertySetInfo ().getProperties ())\n {\n try\n {\n System.out.println (p.Name+"="+set.getPropertyValue (p.Name));\n }\n catch (Exception e)\n {\n throw new OOException ("Error getting value of property "+p.Name, e);\n }\n }\n }\n\n}\n</code></pre>\n\n<p>You can use the control like this:</p>\n\n<pre><code>package ooswtviewer;\n\nimport java.awt.BorderLayout;\nimport java.awt.Frame;\nimport java.awt.Panel;\nimport java.io.File;\n\nimport javax.swing.JRootPane;\n\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.awt.SWT_AWT;\nimport org.eclipse.swt.events.DisposeEvent;\nimport org.eclipse.swt.events.DisposeListener;\nimport org.eclipse.swt.layout.FillLayout;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Display;\nimport org.eclipse.swt.widgets.Shell;\n\n/**\n * Code based on example from http://www.eclipsezone.com/eclipse/forums/t48966.html\n * \n * @author Aaron Digulla\n */\npublic class OOoSwtSnippet {\n public static void main(String[] args) {\n OOoSwtSnippet obj = new OOoSwtSnippet ();\n try\n {\n obj.run (args);\n }\n catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n\n public void run (String[] args) throws Exception\n {\n final Display display = new Display();\n final Shell shell = new Shell(display);\n shell.setLayout(new FillLayout());\n\n Composite composite = new Composite(shell, SWT.NO_BACKGROUND\n | SWT.EMBEDDED);\n\n System.setProperty("sun.awt.noerasebackground", "true");\n\n /* Create and setting up frame */\n Frame frame = SWT_AWT.new_Frame(composite);\n Panel panel = new Panel(new BorderLayout()) {\n public void update(java.awt.Graphics g) {\n paint(g);\n }\n };\n frame.add(panel);\n JRootPane root = new JRootPane();\n panel.add(root);\n java.awt.Container contentPane = root.getContentPane();\n\n shell.setSize(800, 600);\n final OOoSwtViewer viewer = new OOoSwtViewer();\n contentPane.add(viewer);\n\n // viewer.setDocument(NEW_WRITTER_DOCUMENT);\n File document = new File ("test.odt");\n String url = document.getAbsoluteFile ().toURL ().toString ();\n url = "file:///" + url.substring (6);\n System.out.println ("Loading "+url);\n viewer.setDocument(url);\n\n shell.setText ("OOoSwtSnippet");\n shell.open();\n shell.addDisposeListener(new DisposeListener() {\n public void widgetDisposed(DisposeEvent e) {\n try {\n viewer.close();\n } catch (RuntimeException exception) {\n exception.printStackTrace();\n }\n }\n\n });\n while (!shell.isDisposed()) {\n if (!display.readAndDispatch())\n display.sleep();\n }\n display.dispose();\n }\n\n}\n</code></pre>\n\n<p>OOException is a RuntimeException:</p>\n\n<pre><code>package ooswtviewer;\n\n/**\n * Wrapper for all OO exceptions to keep throws clauses in check\n * \n * @author Aaron Digulla\n */\npublic class OOException extends RuntimeException\n{\n\n public OOException ()\n {\n super ();\n }\n\n public OOException (String message, Throwable cause)\n {\n super (message, cause);\n }\n\n public OOException (String message)\n {\n super (message);\n }\n\n public OOException (Throwable cause)\n {\n super (cause);\n }\n\n}\n</code></pre>\n'}, {'answer_id': 1157851, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://sites.google.com/site/anshunjain/eclipse-musings/eclipse-hacks/eclipse-richt-text-editor" rel="nofollow noreferrer">http://sites.google.com/site/anshunjain/eclipse-musings/eclipse-hacks/eclipse-richt-text-editor</a></p>\n'}, {'answer_id': 2294741, 'author': 'Roland Tepp', 'author_id': 1712, 'author_profile': 'https://Stackoverflow.com/users/1712', 'pm_score': 2, 'selected': True, 'text': '<p>Actuall, I\'ve just found another widget that is quite promising atm:</p>\n\n<p><a href="http://onpositive.com/richtext" rel="nofollow noreferrer">http://onpositive.com/richtext</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1712/'] |
81,674 | <p>I am looking for an easy way to check if an object in C# is serializable.</p>
<p>As we know you make an object serializable by either implementing the <em>ISerializable</em> interface or by placing the <em>[Serializable]</em> at the top of the class.</p>
<p>What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an <em>is</em> statement.</p>
<p>Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way.</p>
<pre><code>private static bool IsSerializable(T obj)
{
return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute))));
}
</code></pre>
<p>Or even better just get the type of the object and then use the IsSerializable property on the type:</p>
<pre><code>typeof(T).IsSerializable
</code></pre>
<p>Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.</p>
| [{'answer_id': 81705, 'author': 'Grad van Horck', 'author_id': 12569, 'author_profile': 'https://Stackoverflow.com/users/12569', 'pm_score': 3, 'selected': False, 'text': '<pre><code>Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));\n</code></pre>\n\n<p>Probably involves reflection underwater, but the most simple way?</p>\n'}, {'answer_id': 81718, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 5, 'selected': False, 'text': '<p>You\'re going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that\'s not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don\'t take the graph into account.</p>\n\n<p><em>Sample</em></p>\n\n<pre><code>[Serializable]\npublic class A\n{\n public B B = new B();\n}\n\npublic class B\n{\n public string a = "b";\n}\n\n[Serializable]\npublic class C\n{\n public D D = new D();\n}\n\n[Serializable]\npublic class D\n{\n public string d = "D";\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n\n var a = typeof(A);\n\n var aa = new A();\n\n Console.WriteLine("A: {0}", a.IsSerializable); // true (WRONG!)\n\n var c = typeof(C);\n\n Console.WriteLine("C: {0}", c.IsSerializable); //true\n\n var form = new BinaryFormatter();\n // throws\n form.Serialize(new MemoryStream(), aa);\n }\n}\n</code></pre>\n'}, {'answer_id': 81762, 'author': 'leppie', 'author_id': 15541, 'author_profile': 'https://Stackoverflow.com/users/15541', 'pm_score': 8, 'selected': True, 'text': '<p>You have a lovely property on the <code>Type</code> class called <code>IsSerializable</code>.</p>\n'}, {'answer_id': 81833, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 3, 'selected': False, 'text': "<p>Here's a 3.5 variation that makes it available to all classes using an extension method.</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n if (obj is ISerializable)\n return true;\n return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));\n}\n</code></pre>\n"}, {'answer_id': 82260, 'author': 'Joe', 'author_id': 13087, 'author_profile': 'https://Stackoverflow.com/users/13087', 'pm_score': 3, 'selected': False, 'text': "<p>Use Type.IsSerializable as others have pointed out.</p>\n\n<p>It's probably not worth attempting to reflect and check if all members in the object graph are serializable. </p>\n\n<p>A member could be declared as a serializable type, but in fact be instantiated as a derived type that is not serializable, as in the following contrived example:</p>\n\n<pre><code>[Serializable]\npublic class MyClass\n{\n public Exception TheException; // serializable\n}\n\npublic class MyNonSerializableException : Exception\n{\n...\n}\n\n...\nMyClass myClass = new MyClass();\nmyClass.TheException = new MyNonSerializableException();\n// myClass now has a non-serializable member\n</code></pre>\n\n<p>Therefore, even if you determine that a specific instance of your type is serializable, you can't in general be sure this will be true of all instances.</p>\n"}, {'answer_id': 4037838, 'author': 'Mike_G', 'author_id': 52051, 'author_profile': 'https://Stackoverflow.com/users/52051', 'pm_score': 4, 'selected': False, 'text': '<p>This is an old question, that may need to be updated for .NET 3.5+. Type.IsSerializable can actually return false if the class uses the DataContract attribute. Here is a snippet i use, if it stinks, let me know :)</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n Type t = obj.GetType();\n\n return Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)\n\n}\n</code></pre>\n'}, {'answer_id': 5913032, 'author': 'Eric', 'author_id': 741895, 'author_profile': 'https://Stackoverflow.com/users/741895', 'pm_score': 0, 'selected': False, 'text': '<p>The exception object might be serializable , but using an other exception which is not.\nThis is what I just had with WCF System.ServiceModel.FaultException: FaultException is serializable but ExceptionDetail is not!</p>\n\n<p>So I am using the following:</p>\n\n<pre><code>// Check if the exception is serializable and also the specific ones if generic\nvar exceptionType = ex.GetType();\nvar allSerializable = exceptionType.IsSerializable;\nif (exceptionType.IsGenericType)\n {\n Type[] typeArguments = exceptionType.GetGenericArguments();\n allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) => current & tParam.IsSerializable);\n }\n if (!allSerializable)\n {\n // Create a new Exception for not serializable exceptions!\n ex = new Exception(ex.Message);\n }\n</code></pre>\n'}, {'answer_id': 13054478, 'author': 'sewershingle', 'author_id': 496047, 'author_profile': 'https://Stackoverflow.com/users/496047', 'pm_score': 2, 'selected': False, 'text': '<p>I took the answer on this question and the answer <a href="https://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializable/236698#236698">here</a> and modified it so you get a List of types that aren\'t serializable. That way you can easily know which ones to mark.</p>\n\n<pre><code> private static void NonSerializableTypesOfParentType(Type type, List<string> nonSerializableTypes)\n {\n // base case\n if (type.IsValueType || type == typeof(string)) return;\n\n if (!IsSerializable(type))\n nonSerializableTypes.Add(type.Name);\n\n foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n {\n if (propertyInfo.PropertyType.IsGenericType)\n {\n foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())\n {\n if (genericArgument == type) continue; // base case for circularly referenced properties\n NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);\n }\n }\n else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);\n }\n }\n\n private static bool IsSerializable(Type type)\n {\n return (Attribute.IsDefined(type, typeof(SerializableAttribute)));\n //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));\n }\n</code></pre>\n\n<p>And then you call it...</p>\n\n<pre><code> List<string> nonSerializableTypes = new List<string>();\n NonSerializableTypesOfParentType(aType, nonSerializableTypes);\n</code></pre>\n\n<p>When it runs, nonSerializableTypes will have the list. There may be a better way of doing this than passing in an empty List to the recursive method. Someone correct me if so.</p>\n'}, {'answer_id': 25096555, 'author': 'ElektroStudios', 'author_id': 1248295, 'author_profile': 'https://Stackoverflow.com/users/1248295', 'pm_score': 1, 'selected': False, 'text': '<p>My solution, in VB.NET:</p>\n\n<p>For Objects:</p>\n\n<pre><code>\'\'\' <summary>\n\'\'\' Determines whether an object can be serialized.\n\'\'\' </summary>\n\'\'\' <param name="Object">The object.</param>\n\'\'\' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsObjectSerializable(ByVal [Object] As Object,\n Optional ByVal SerializationFormat As SerializationFormat =\n SerializationFormat.Xml) As Boolean\n\n Dim Serializer As Object\n\n Using fs As New IO.MemoryStream\n\n Select Case SerializationFormat\n\n Case Data.SerializationFormat.Binary\n Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\n\n Case Data.SerializationFormat.Xml\n Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)\n\n Case Else\n Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)\n\n End Select\n\n Try\n Serializer.Serialize(fs, [Object])\n Return True\n\n Catch ex As InvalidOperationException\n Return False\n\n End Try\n\n End Using \' fs As New MemoryStream\n\nEnd Function\n</code></pre>\n\n<p>For Types:</p>\n\n<pre><code>\'\'\' <summary>\n\'\'\' Determines whether a Type can be serialized.\n\'\'\' </summary>\n\'\'\' <typeparam name="T"></typeparam>\n\'\'\' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsTypeSerializable(Of T)() As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n\n\'\'\' <summary>\n\'\'\' Determines whether a Type can be serialized.\n\'\'\' </summary>\n\'\'\' <typeparam name="T"></typeparam>\n\'\'\' <param name="Type">The Type.</param>\n\'\'\' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>\nPrivate Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean\n\n Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231/'] |
81,686 | <p>We have a NET app that gets installed to the Program Files folder.
The app itself writes some files and creates some directories to its app folder.
But when a normal windows user tries to use our application it crashes because that user does not have permission to write to app folder.
Is there any folder in both WinXP and WinVista to which all users have writing permissions by default? All User folder or something like that?</p>
| [{'answer_id': 81738, 'author': 'RickL', 'author_id': 7261, 'author_profile': 'https://Stackoverflow.com/users/7261', 'pm_score': 0, 'selected': False, 'text': "<p>I'm not sure that there is a single path to which all non-administrator users have permission to write to.</p>\n\n<p>I think the correct one would be <code><User>\\Application Data</code></p>\n"}, {'answer_id': 81779, 'author': 'pilif', 'author_id': 5083, 'author_profile': 'https://Stackoverflow.com/users/5083', 'pm_score': 3, 'selected': True, 'text': "<p>There is no such folder.</p>\n\n<p>But you can create one.</p>\n\n<p>There is CSIDL_COMMON_APPDATA which in Vista maps to %ProgramData% (c:\\ProgramData) and in XP maps to c:\\Documents and Settings\\AllUsers\\Application Data</p>\n\n<p>Feel free to create a folder there in your installer and set the ACL so that everyone can write to that folder.</p>\n\n<p>Keep in mind that COMMON_APPDATA was implemented in Version 5 of the common controls library which means that it's available in Windows 2000 and later. In NT4, you can create that folder in your installation directory and in Windows 98 and below it doesn't matter anyways due to these systems not having a permission system anyways.</p>\n\n<p>Here is some sample InnoSetup code to create that folder:</p>\n\n<pre><code>[Dirs]\nName: {code:getDBPath}; Flags: uninsalwaysuninstall; Permissions: authusers-modify\n\n[Code]\n\n\nfunction getDBPath(Param: String): String;\nvar\n Version: TWindowsVersion;\nbegin\n Result := ExpandConstant('{app}\\data');\n GetWindowsVersionEx(Version);\n if (Version.Major >= 5) then begin\n Result := ExpandConstant('{commonappdata}\\myprog');\n end;\nend;\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15528/'] |
81,698 | <p>Are the any task tracking systems with command-line interface? </p>
<p>Here is a list of features I'm interested in:</p>
<ul>
<li>Simple task template<br>
Something like plain-text file with property:type pairs, for example:</li>
</ul>
<blockquote>
<pre><code>description:string
some-property:integer required
</code></pre>
</blockquote>
<ul>
<li>command line interface<br>
for example: </li>
</ul>
<blockquote>
<pre><code>// Creates task
<task tracker>.exe -create {description: "Foo", some-property: 1}
// Search for tasks with description field starting from F
<task tracker>.exe -find { description: "F*" }
</code></pre>
</blockquote>
<ul>
<li><p>XCopy deployment<br>
It should not require to install heavy DBMS</p></li>
<li><p>Multiple users support<br>
So it's not just a to-do list for a single person</p></li>
</ul>
| [{'answer_id': 81758, 'author': 'Peter Hilton', 'author_id': 2670, 'author_profile': 'https://Stackoverflow.com/users/2670', 'pm_score': 3, 'selected': False, 'text': '<p>Interesting idea; the closest thing I have heard of is <a href="http://todotxt.com/" rel="noreferrer">todo.txt</a>.</p>\n\n<p>Alternatively, you could roll your own by just using a database (e.g. sqllite) and SQL. Optionally, write a wrapper script that parses your plain-text file and command-line options, and generates the corresponding SQL.</p>\n'}, {'answer_id': 81782, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://roundup.sourceforge.net/" rel="nofollow noreferrer">http://roundup.sourceforge.net/</a></p>\n'}, {'answer_id': 81799, 'author': 'binOr', 'author_id': 990, 'author_profile': 'https://Stackoverflow.com/users/990', 'pm_score': 0, 'selected': False, 'text': '<p>Fogbugz has a <a href="http://support.fogcreek.com/default.asp?W840" rel="nofollow noreferrer">Command Line Client</a>.</p>\n'}, {'answer_id': 81801, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': "<p>@Peter Hilton,</p>\n\n<p>I'm going to create such system. So I'm wondering whether such system exists. General idea is to keep it as simple as possible: command line utility to manage tasks & simple server wit REST interface. I used dozen different task tracking system and come to conclusion that I don't need fancy UI. It should be like Subversion - you can happily work with command-line based svn.exe</p>\n"}, {'answer_id': 83775, 'author': 'Matt', 'author_id': 15368, 'author_profile': 'https://Stackoverflow.com/users/15368', 'pm_score': 2, 'selected': False, 'text': '<p>Have you seen <a href="http://github.com/schacon/ticgit/wikis" rel="nofollow noreferrer">ticgit</a>. It sounds like it might do just what you guys are after.</p>\n'}, {'answer_id': 211318, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': True, 'text': '<blockquote>\n <p>Ditz is a simple, light-weight distributed issue tracker designed to work\n with distributed version control systems like darcs and git.</p>\n</blockquote>\n\n<p>Ditz: <a href="http://web.archive.org/web/20121212202849/http://gitorious.org/ditz" rel="nofollow noreferrer">http://web.archive.org/web/20121212202849/http://gitorious.org/ditz</a> </p>\n\n<p>Also cloned here: <a href="https://github.com/jashmenn/ditz" rel="nofollow noreferrer">https://github.com/jashmenn/ditz</a></p>\n'}, {'answer_id': 248713, 'author': 'Jasper Bekkers', 'author_id': 31486, 'author_profile': 'https://Stackoverflow.com/users/31486', 'pm_score': 1, 'selected': False, 'text': "<p>I've abused the <code>cal</code> and <code>calendar</code> commandline tools regularly for this type of task.</p>\n"}, {'answer_id': 2334299, 'author': 'Offe', 'author_id': 191304, 'author_profile': 'https://Stackoverflow.com/users/191304', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at <a href="http://pitz.tplus1.com/" rel="nofollow noreferrer">Pitz</a> and <a href="http://bugseverywhere.org/be/show/HomePage" rel="nofollow noreferrer">Bugs Everywhere</a>. </p>\n'}, {'answer_id': 2596785, 'author': 'taltman', 'author_id': 311492, 'author_profile': 'https://Stackoverflow.com/users/311492', 'pm_score': 0, 'selected': False, 'text': '<p>I use <a href="http://www.org-mode.org" rel="nofollow noreferrer">org-mode</a> with emacs in terminal mode (emacs -nw).</p>\n'}, {'answer_id': 3764787, 'author': 'Henrik', 'author_id': 63984, 'author_profile': 'https://Stackoverflow.com/users/63984', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://codespeak.net/ciss/" rel="nofollow noreferrer">ciss</a> issue tracker is a simple commandline tool for managing your ISSUES.txt file.</p>\n'}, {'answer_id': 24465778, 'author': 'neoneye', 'author_id': 78336, 'author_profile': 'https://Stackoverflow.com/users/78336', 'pm_score': 2, 'selected': False, 'text': '<h1>Erlangs Ticket System</h1>\n\n<p>Created by Peter Högfeldt in 1986. This is the ticket system that was used in the Erlang distribution.</p>\n\n<p>Source: <a href="https://joearms.github.io/published/2014-06-25-minimal-viable-program.html" rel="nofollow noreferrer">Joe Armstrong\'s blog</a></p>\n'}, {'answer_id': 54624847, 'author': 'mesibo', 'author_id': 4895359, 'author_profile': 'https://Stackoverflow.com/users/4895359', 'pm_score': 0, 'selected': False, 'text': "<p>We have used a few tools earlier. We now use a GitHub private repository to maintain various developer TBD lists (as .md files) and issue tracking because of the following advantages: </p>\n\n<ul>\n<li>Developers are already using GitHub and they don't need to learn anything new. </li>\n<li>Developers can use whatever tool they are comfortable with to maintain TBD list; command line or graphical editors, GitHub web interface or plenty of mobile clients</li>\n<li>Markdown support</li>\n<li>Reliable backup </li>\n<li>Merging and revision history</li>\n<li>Flexible file organization for different projects and modules </li>\n</ul>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196/'] |
81,716 | <p>I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error:</p>
<p><strong>stdio.h : No such file or directory</strong></p>
<p>The code (hello.c) looks like this:</p>
<pre><code>#include < stdio.h >
void main()
{
printf("\nHello World\n");
}
</code></pre>
<p>I use a batch file to call gcc. The batch file looks like this:</p>
<pre><code>@echo off
set OLDPATH=%PATH%
set path=C:\devtools\MinGW\bin;%PATH%
set LIBRARY_PATH=C:\devtools\MinGW\lib
set C_INCLUDE_PATH=C:\devtools\MinGW\include
gcc.exe hello.c
set path=%OLDPATH%
</code></pre>
<p>I have tried the option <strong>-I</strong> without effect. What do I do wrong?</p>
| [{'answer_id': 81731, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 4, 'selected': True, 'text': '<p>Try changing the first line to:</p>\n\n<pre><code>#include <stdio.h>\n</code></pre>\n\n<p>without the spaces. It is trying to look for a file called " stdio.h " with a space at the beginning and end.</p>\n'}, {'answer_id': 81736, 'author': 'PierreBdR', 'author_id': 7136, 'author_profile': 'https://Stackoverflow.com/users/7136', 'pm_score': 2, 'selected': False, 'text': '<p>You should try to install MinGW in the default install directory (i.e. C:\\MinGW) I read many times it was recommended to avoid problems. There may be a (wrongly) hardcoded path in gcc.</p>\n'}, {'answer_id': 89036, 'author': 'aib', 'author_id': 1088, 'author_profile': 'https://Stackoverflow.com/users/1088', 'pm_score': 0, 'selected': False, 'text': '<p>Also note that main() should return an int:</p>\n\n<pre><code>int main(void)\n</code></pre>\n'}, {'answer_id': 21968019, 'author': 'kaka', 'author_id': 1934048, 'author_profile': 'https://Stackoverflow.com/users/1934048', 'pm_score': -1, 'selected': False, 'text': '<p>You can use</p>\n\n<p>$ sudo apt-get install build-essential</p>\n\n<p>to solve this problem</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3565/'] |
81,723 | <p>I have the concept of <code>NodeType</code>s and <code>Node</code>s. A <code>NodeType</code> is a bunch of meta-data which you can create <code>Node</code> instances from (a lot like the whole Class / Object relationship).</p>
<p>I have various <code>NodeType</code> implementations and various Node implementations. </p>
<p>In my AbstractNodeType (top level for NodeTypes) I have ab abstract <code>createInstance()</code> method that will, once implemented by the subclass, creates the correct Node instance:</p>
<pre><code>public abstract class AbstractNodeType {
// ..
public abstract <T extends AbstractNode> T createInstance();
}
</code></pre>
<p>In my <code>NodeType</code> implementations I implement the method like this:</p>
<pre><code>public class ThingType {
// ..
public Thing createInstance() {
return new Thing(/* .. */);
}
}
// FYI
public class Thing extends AbstractNode { /* .. */ }
</code></pre>
<p>This is all well and good, but <code>public Thing createInstance()</code> creates a warning about type safety. Specifically:</p>
<blockquote>
<p>Type safety: The return type Thing for
createInstance() from the type
ThingType needs unchecked conversion
to conform to T from the type
AbstractNodeType</p>
</blockquote>
<p><strong>What am I doing wrong to cause such a warning?</strong></p>
<p><strong>How can I re-factor my code to fix this?</strong></p>
<p><em><code>@SuppressWarnings("unchecked")</code> is not good, I wish to fix this by coding it correctly, not ignoring the problem!</em></p>
| [{'answer_id': 81742, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 3, 'selected': True, 'text': '<p>You can just replace <code><T extends AbstractNode> T</code> with <code>AbstractNode</code> thanks to the magic of <a href="http://en.wikipedia.org/wiki/Covariant_return_type" rel="nofollow noreferrer">covariant returns</a>. <code>Java 5</code> added support, but it didn\'t receive the pub it deserved.</p>\n'}, {'answer_id': 81796, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 1, 'selected': False, 'text': '<p>Something like that should work:</p>\n\n<pre><code>interface Node{\n}\ninterface NodeType<T extends Node>{\n T createInstance();\n}\nclass Thing implements Node{}\nclass ThingType implements NodeType<Thing>{\n public Thing createInstance() {\n return new Thing();\n }\n}\nclass UberThing extends Thing{}\nclass UberThingType extends ThingType{\n @Override\n public UberThing createInstance() {\n return new UberThing();\n }\n}\n</code></pre>\n'}, {'answer_id': 81825, 'author': 'UlfJack', 'author_id': 15551, 'author_profile': 'https://Stackoverflow.com/users/15551', 'pm_score': 2, 'selected': False, 'text': "<p>Two ways:</p>\n\n<p>(a) Don't use generics. It's probably not necessary in this case. (Although that depends on the code you havn't shown.)</p>\n\n<p>(b) Generify AbstractNodeType as follows:</p>\n\n<pre><code>public abstract class AbstractNodeType<T extends AbstractNode> {\n public abstract T createInstance();\n}\npublic class ThingType<Thing> {\n public Thing createInstance() {\n return new Thing(...);\n }\n}\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1666/'] |
81,727 | <p>While implementing an applicative server and its client-side libraries in C++, I am having trouble finding a clean and reliable way to stop client processes on server shutdown on Windows.</p>
<p>Assuming the server and its clients run under the same user, the requirements are:</p>
<ul>
<li>the solution should work in the following cases:
<ul>
<li>clients may each feature either a console or a gui.</li>
<li>user may be unprivileged.<li>
<li>clients may be or become unresponsive (infinite loop, deadlock).</li>
<li>clients may or may not be children of the server (direct or indirect).</li>
</ul>
<li>unless prevented by a client-side defect, clients shall be allowed the opportunity to exit cleanly (free their ressources, sync some data to disk...) and some reasonable time to do so.</li>
<li>all client return codes shall be made available (if possible) to the server during the shutdown procedure.</li>
<li>server shall wait until all clients are gone.</li>
</ul>
<hr>
<p>As of this edit, the majority of the answers below advocate the use of a shared memory (or another IPC mechanism) between the server and its clients to convey shutdown orders and client status. These solutions would work, but require that clients successfully initialize the library.</p>
<p>What I did not say, is that the server is also used to start the clients and in some cases other programs/scripts which don't use the client library at all. A solution that did not rely on a graceful communication between server and clients would be nicer (if possible).</p>
<p>Some time ago, I stumbled upon a C snippet (in the MSDN I believe) that did the following:</p>
<ol>
<li>start a thread via CreateRemoteThread in the process to shutdown.</li>
<li>had that thread directly call ExitProcess.</li>
</ol>
<p>Unfortunately now that I'm looking for it, I'm unable to find it and the search results seem to imply that this trick does not work anymore on Vista. Any expert input on this ?</p>
| [{'answer_id': 81812, 'author': 'Asaf Bartov', 'author_id': 7483, 'author_profile': 'https://Stackoverflow.com/users/7483', 'pm_score': 1, 'selected': False, 'text': "<p>You want some sort of IPC between clients and servers. If all clients were children, I think pipes would have been easiest; since they're not, I guess a server-operated shared-memory segment can be used to register clients, issue the shutdown command, and collect return codes posted there by clients successfully shutting down.</p>\n\n<p>In this shared-memory area, clients put their process IDs, so that the server can forcefully kill any unresponsive clients (modulo server privileges), using TerminateProcess().</p>\n"}, {'answer_id': 81826, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 0, 'selected': False, 'text': "<p>That's a very general question, and there are some inconsistencies.</p>\n\n<p>While it is a not 100% rule, most console applications run to completion, whereas GUI applications run until the user terminates them (And services run until stopped via the SCM). Hence, it's easier to request a GUI to close. You send them the equivalent of Alt-F4. But for a console program, you have to send them the equivalent of Ctrl-C and hope they handle it. In both cases, you simply wait. If the process sticks around, you then shoot it down (TerminateProcess) and pray that the damage is limited. But your HDD can fill up with temporary files.</p>\n\n<p>GUI application in general do not have exit codes - where would they go? And a console process that is forcefully terminated by definition does not exit, so it has no exit code. So, in a server shutdown scenario, don't expect exit codes.</p>\n\n<p>If you've got a debugger attached, you generally can't shutdown the process from another application. That would make it impossible for debuggers to debug exit code!</p>\n"}, {'answer_id': 82770, 'author': 'titanae', 'author_id': 2387, 'author_profile': 'https://Stackoverflow.com/users/2387', 'pm_score': 2, 'selected': False, 'text': '<p>If you use thread, a simple solution is to use a named system event, the thread sleeps on the event waiting for it to be signaled, the control application can signal the event when it wants the client applications to quit.</p>\n\n<p>For the UI application it (the thread) can post a message to the main window, WM_ CLOSE or QUIT I forget which, in the console application it can issue a CTRL-C or if the main console code loops it can check some exit condition set by the thread. </p>\n\n<p>Either way rather than finding the client applications an telling them to quit, use the OS to signal they should quit. The sleeping thread will use virtually no CPU footprint provided it uses WaitForSingleObject to sleep on.</p>\n'}, {'answer_id': 82794, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>If you are willing to go the IPC route, make the normal communication between client and server bi-directional to let the server ask the clients to shut down. Or, failing that, have the clients poll. Or as the last resort, the clients should be instructed to exit when the make a request to server. You can let the library user register an exit callback, but the best way I know of is to simply call "exit" in the client library when the client is told to shut down. If the client gets stuck in shutdown code, the server needs to be able to work around it by ignoring that client\'s data structures and connection.</p>\n'}, {'answer_id': 390464, 'author': 'Jason S', 'author_id': 44330, 'author_profile': 'https://Stackoverflow.com/users/44330', 'pm_score': 1, 'selected': False, 'text': '<p>Use PostMessage or a named event.</p>\n\n<p>Re: PostMessage -- applications other than GUIs, as well as threads other than the GUI thread, can have message loops and it\'s very useful for stuff like this. (In fact COM uses message loops under the hood.) I\'ve done it before with ATL but am a little rusty with that.</p>\n\n<p>If you want to be robust to malicious attacks from "bad" processes, include a private key shared by client/server as one of the parameters in the message.</p>\n\n<p>The named event approach is probably simpler; use CreateEvent with a name that is a secret shared by the client/server, and have the appropriate app check the status of the event (e.g. WaitForSingleObject with a timeout of 0) within its main loop to determine whether to shut down.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11892/'] |
81,730 | <p>In .NET, after this code, what mechanism stops the <code>Thread</code> object from being garbage collected?</p>
<pre><code>new Thread(Foo).Start();
GC.Collect();
</code></pre>
<p>Yes, it's safe to assume <strong>something</strong> has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me <code>System.Threading</code>, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).</p>
| [{'answer_id': 81739, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 0, 'selected': False, 'text': "<p>Well, it's safe to assume that if a thread is running somewhere that something has a reference to it so wouldn't that be enough to stop the garbage collection?</p>\n"}, {'answer_id': 81755, 'author': 'Grad van Horck', 'author_id': 12569, 'author_profile': 'https://Stackoverflow.com/users/12569', 'pm_score': -1, 'selected': False, 'text': '<p>Assign the new Thread to a local field?</p>\n\n<pre><code>class YourClass\n{\n Thread thread;\n\n void Start()\n {\n thread = new Thread(Foo);\n thread.Start();\n GC.Collect();\n }\n}\n</code></pre>\n\n<p>Garbage Collection collects everyting that is not references, so in your code there is no field/variable referencing to the thread, so it will be collected.</p>\n'}, {'answer_id': 81763, 'author': 'EricSchaefer', 'author_id': 8976, 'author_profile': 'https://Stackoverflow.com/users/8976', 'pm_score': 5, 'selected': True, 'text': '<p>The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference.</p>\n'}, {'answer_id': 81805, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': 2, 'selected': False, 'text': "<p>It's a hard-wired feature of garbage collector. Running threads are not collected.</p>\n"}, {'answer_id': 100763, 'author': 'Damien_The_Unbeliever', 'author_id': 15498, 'author_profile': 'https://Stackoverflow.com/users/15498', 'pm_score': 0, 'selected': False, 'text': "<p>Important point to note though - if your thread is marked with IsBackground=True, it won't prevent the whole process from exiting</p>\n"}, {'answer_id': 100850, 'author': 'Ilya Ryzhenkov', 'author_id': 18575, 'author_profile': 'https://Stackoverflow.com/users/18575', 'pm_score': 3, 'selected': False, 'text': '<p>It depends on whether the thread is running or not. If you just created Thread object and didn\'t start it, it is an ordinary managed object, i.e. eligible for GC. As soon as you start thread, or when you obtain Thread object for already running thread (GetCurrentThread) it is a bit different. The "exposed object", managed Thread, is now hold on strong reference within CLR, so you always get the same instance. When thread terminates, this strong reference is released, and the managed object will be collected as soon as you don\'t have any other references to (now dead) Thread.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11236/'] |
81,732 | <p>I've got a virtual machine running on a server that I can't stop or reboot - I can't log onto it anymore and I can't stop it using the VMware server console. There are other VM's running so rebooting the host is out of the question. Is there any other way of forcing one machine to stop?</p>
| [{'answer_id': 81743, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 5, 'selected': True, 'text': '<p>If you are using Windows, the virtual machine should have it\'s own process that is visible in task manager. Use sysinternals <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">Process Explorer</a> to find the right one and then kill it from there.</p>\n'}, {'answer_id': 81761, 'author': 'Ian', 'author_id': 4396, 'author_profile': 'https://Stackoverflow.com/users/4396', 'pm_score': 4, 'selected': False, 'text': "<p>If you're on linux then you can grab the guest processes with </p>\n\n<pre><code>ps axuw | grep vmware-vmx\n</code></pre>\n\n<p>As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD</p>\n"}, {'answer_id': 81993, 'author': 'Rikalous', 'author_id': 4271, 'author_profile': 'https://Stackoverflow.com/users/4271', 'pm_score': 2, 'selected': False, 'text': "<p>Here's what I did based on </p>\n\n<p>a) @Espo 's comments and<br>\nb) the fact that I only had Windows Task Manager to play with....</p>\n\n<p>I logged onto the host machine, opened Task Manager and used the view menu to add the PID column to the Processes tab.</p>\n\n<p>I wrote down (yes, with paper and a pen) the PID's for each and every instance of the vmware-wmx.exe process that was running on the box. </p>\n\n<p>Using the VMWare console, I suspended the errant virtual machine.</p>\n\n<p>When I resumed it, I could then identify the vmware-vmx process that corresponded to my machine and could kill it.</p>\n\n<p>There doesn't seem to have been any ill effects so far.</p>\n"}, {'answer_id': 7330794, 'author': 'Daniel Tallentire', 'author_id': 502968, 'author_profile': 'https://Stackoverflow.com/users/502968', 'pm_score': 2, 'selected': False, 'text': '<p>Similar, but using WMIC command line to obtain the process ID and path:</p>\n\n<pre><code>WMIC /OUTPUT:C:\\ProcessList.txt PROCESS get Caption,Commandline,Processid\n</code></pre>\n\n<p>This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.</p>\n\n<p>Thanks to <a href="http://windowsxp.mvps.org/listproc.htm" rel="nofollow">http://windowsxp.mvps.org/listproc.htm</a> for the correct command line parameters.</p>\n'}, {'answer_id': 7355916, 'author': 'saschabeaumont', 'author_id': 592, 'author_profile': 'https://Stackoverflow.com/users/592', 'pm_score': 2, 'selected': False, 'text': '<p>For ESXi 5, you\'ll first want to enable ssh via the vSphere console and then login and use the following command to find the process ID</p>\n\n<pre><code>ps -c | grep -i "machine name"\n</code></pre>\n\n<p>You can then find the process ID and end the process using <code>kill</code></p>\n'}, {'answer_id': 11508733, 'author': 'EJ2020', 'author_id': 1529528, 'author_profile': 'https://Stackoverflow.com/users/1529528', 'pm_score': 3, 'selected': False, 'text': '<p>In some cases you may not be able to suspend, or for that matter take any of the "Power" actions on the VM. You may also already have multiple VMs up and running. Use this process to identify the correct PID to kill.</p>\n\n<p>On Windows 7 - Open Task Manager - Look for processes with the name, "vmware-vmx.exe", note the PIDs.</p>\n\n<p>Switch to the Performance tab and start the "Resource Monitor". Expand the "Disk Activity" panel. Sort the "File" column. Look for the appropriate vmdk file for the VM you want to kill. The "Image" column will have the "vmware-vmx" process listed. Note the PID.</p>\n\n<p>Switch back to the "Processes" tab and kill the PID.</p>\n'}, {'answer_id': 18319578, 'author': 'spuder', 'author_id': 1626687, 'author_profile': 'https://Stackoverflow.com/users/1626687', 'pm_score': 2, 'selected': False, 'text': '<p>For VmWare fusion, hold the <kbd>alt</kbd> key while you click \'restart virtual machine\' </p>\n\n<p><a href="http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1006215" rel="nofollow">http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1006215</a></p>\n'}, {'answer_id': 18872792, 'author': 'Jocelyn', 'author_id': 1926197, 'author_profile': 'https://Stackoverflow.com/users/1926197', 'pm_score': 2, 'selected': False, 'text': '<p>see the following from VMware\'s webpage</p>\n\n<p>Powering off a virtual machine on an ESXi host (1014165)\nSymptoms</p>\n\n<p>You are experiencing these issues:</p>\n\n<pre><code>You cannot power off an ESXi hosted virtual machine.\nA virtual machine is not responsive and cannot be stopped or killed.\n</code></pre>\n\n<p><a href="http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1014165" rel="nofollow">http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1014165</a></p>\n\n<p>"Using the ESXi 5.x esxcli command to power off a virtual machine</p>\n\n<p>The esxcli command can be used locally or remotely to power off a virtual machine running on ESXi 5.x. For more information, see the esxcli vm Commands section of the vSphere Command-Line Interface Reference.</p>\n\n<pre><code>Open a console session where the esxcli tool is available, either in the ESXi Shell, the vSphere Management Assistant (vMA), or the location where the vSphere Command-Line Interface (vCLI) is installed.\n\nGet a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:\n\nesxcli vm process list\n\nPower off one of the virtual machines from the list using this command:\n\nesxcli vm process kill --type=[soft,hard,force] --world-id=WorldNumber\n\nNotes:\nThree power-off methods are available. Soft is the most graceful, hard performs an immediate shutdown, and force should be used as a last resort.\nAlternate power off command syntax is: esxcli vm process kill -t [soft,hard,force] -w WorldNumber\n\nRepeat Step 2 and validate that the virtual machine is no longer running.\n</code></pre>\n\n<p>For ESXi 4.1:</p>\n\n<pre><code>Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file, using this command:\n\nesxcli vms vm list\n\nPower off one of the virtual machines from the list using this command:\n\nesxcli vms vm kill --type=[soft,hard,force] --world-id=WorldNumber"\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4271/'] |
81,768 | <p>I have a Yahoo map with lots of markers (~500). The map performs well enough until I close the page, at which point it pauses (in Firefox) and brings up a "Stop running this script?" dialog (in IE7). If given long enough the script does complete its work.</p>
<p>Is there anything I can do to reduce this delay?</p>
<p>This stripped down code exhibits the problem:</p>
<pre><code><script type="text/javascript">
var map = new YMap(document.getElementById('map'));
map.drawZoomAndCenter("Algeria", 17);
for (var i = 0; i < 500; i += 1) {
var geoPoint = new YGeoPoint((Math.random()-0.5)*180.0, (Math.random()-0.5)*360.0);
var marker = new YMarker(geoPoint);
map.addOverlay(marker);
}
</script>
</code></pre>
<p>I'm aware of some memory leaks with the event handlers if you're dynamically adding and removing markers, but these are static (though the problem may be related). Oh, and I <em>know</em> this many markers on a map may not be the best way to convey the data, but that's not the answer I'm looking for ;)</p>
<p><strong>Edit:</strong> Following a suggestion below I've tried:</p>
<pre><code>window.onbeforeunload = function() {
map.removeMarkersAll();
}
</code></pre>
<p>and </p>
<pre><code>window.onbeforeunload = function() {
mapElement = document.getElementById('map');
mapElement.parentNode.removeChild(mapElement);
}
</code></pre>
<p>but neither worked :(</p>
| [{'answer_id': 83328, 'author': 'Diodeus - James MacFarlane', 'author_id': 12579, 'author_profile': 'https://Stackoverflow.com/users/12579', 'pm_score': 0, 'selected': False, 'text': '<p>You could try removing all the markers, or even removing the map from the DOM using the "onbeforeunload" event.</p>\n'}, {'answer_id': 221162, 'author': 'Joshi Spawnbrood', 'author_id': 15392, 'author_profile': 'https://Stackoverflow.com/users/15392', 'pm_score': 0, 'selected': False, 'text': "<p>Are you sure nothing is tryin to access the map , when you close the window?</p>\n\n<p>I'd do this type of test:</p>\n\n<p>have a wrapper to reach the map itself, and, on unload, have the wrapper block access to map itself.</p>\n"}, {'answer_id': 364640, 'author': 'Kornel', 'author_id': 27009, 'author_profile': 'https://Stackoverflow.com/users/27009', 'pm_score': 1, 'selected': False, 'text': "<p>Use Javascript profiler and see which function is slow. Then you'll have better idea how to make a workaround or at least how to remove expensive cleanup (and let it leak in IE6).</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4914/'] |
81,770 | <p>I have not seen much support for Grails to develop facebook apps.I was just wondering if people around are developing facebook apps on grails </p>
| [{'answer_id': 105903, 'author': 'mbrevoort', 'author_id': 18228, 'author_profile': 'https://Stackoverflow.com/users/18228', 'pm_score': 3, 'selected': True, 'text': '<p>Jozef Dransfield: \n<a href="http://www.grassr.com/wordpress/?cat=8" rel="nofollow noreferrer">http://www.grassr.com/wordpress/?cat=8</a></p>\n'}, {'answer_id': 2043753, 'author': 'hendrixski', 'author_id': 24920, 'author_profile': 'https://Stackoverflow.com/users/24920', 'pm_score': 0, 'selected': False, 'text': "<p>I helped out a startup in San Francisco that are using Grails with facebook apps.\nSo yes, it's happening. There is even a grails plugin for facebook integration (at the time I'm writing this is woefully incomplete, but looks like it's having work done so check up on it again soon).</p>\n"}, {'answer_id': 3709642, 'author': 'Danomighty', 'author_id': 280434, 'author_profile': 'https://Stackoverflow.com/users/280434', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m deep into Facebook integration from the social networking site ESMZone.com. I originally started using the Grails <a href="http://www.grails.org/plugin/facebook-connect" rel="nofollow noreferrer">facebook-connect plugin</a> and had good success at Facebook sign-on integration with the Grails jScurity plugin. However, as I attempted to implement other features, particularly Friend Invitations, I found that the facebook-connect plugin uses an old facebook SDK that was not compatible with the newer Javascript SDK. Documentation and examples using this newer SDK were readily available in searches unlike for the older API.</p>\n\n<p>I switched to the Grails <a href="http://www.grails.org/plugin/facebook-graph" rel="nofollow noreferrer">facebook-graph plugin</a> and was able to work seemlessly with the Javascript API and get friend invitation working.</p>\n'}, {'answer_id': 5085797, 'author': 'lbroudoux', 'author_id': 629338, 'author_profile': 'https://Stackoverflow.com/users/629338', 'pm_score': 1, 'selected': False, 'text': '<p>I have worked last weeks on a use-case concerning only server-side integration (no facebook connect style application). See some of my thoughts here : <a href="http://lbroudoux.wordpress.com/2011/02/23/integrating-facebook-from-a-grails-app/" rel="nofollow">http://lbroudoux.wordpress.com/2011/02/23/integrating-facebook-from-a-grails-app/</a>. Solution is actually implemented on Trailplans.com application.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15476/'] |
81,784 | <p>How do you usually go about <strong>separating your codebase and associated unit tests</strong>? I know people who create a separate project for unit tests, which I personally find confusing and difficult to maintain. On the other hand, if you mix up code and its tests in a single project, you end up with binaries related to your unit test framework (be it NUnit, MbUnit or whatever else) and your own binaries side by side.</p>
<p>This is fine for debugging, but once I build a <strong>release version</strong>, I really do not want my code to <strong>reference the unit testing framework</strong> any more.</p>
<p>One solution I found is to enclose all your unit tests within #if DEBUG -- #endif directives: when no code references an unit testing assembly, the compiler is clever enough to omit the reference in the compiled code.</p>
<p>Are there any other (possibly more comfortable) options to achieve a similar goal?</p>
| [{'answer_id': 81790, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': 6, 'selected': True, 'text': '<p>I definitely advocate separating your tests out to a separate project. It\'s the only way to go in my opinion.</p>\n\n<p>Yes, as <a href="https://stackoverflow.com/users/6369/garry-shutler">Gary</a> says, it also forces you to test behavior through public methods rather than playing about with the innards of your classes</p>\n'}, {'answer_id': 81794, 'author': 'Chris Canal', 'author_id': 5802, 'author_profile': 'https://Stackoverflow.com/users/5802', 'pm_score': 1, 'selected': False, 'text': "<p>I've always keep my unit tests in a seperate project so it compiles to it's own assembly.</p>\n"}, {'answer_id': 81814, 'author': 'Anthony', 'author_id': 5599, 'author_profile': 'https://Stackoverflow.com/users/5599', 'pm_score': 1, 'selected': False, 'text': '<p>For each project there is a corresponding .Test project that contains tests on it.</p>\n\n<p>E.g. for the assembly called, say "Acme.BillingSystem.Utils", there would be a test assembly called "Acme.BillingSystem.Utils.Test".</p>\n\n<p>Exclude it from the shipping version of your product by not shipping that dll.</p>\n'}, {'answer_id': 81854, 'author': 'Rasmus Faber', 'author_id': 5542, 'author_profile': 'https://Stackoverflow.com/users/5542', 'pm_score': 2, 'selected': False, 'text': '<p>I would recommend a separate project for unit tests (and yet more projects for integration tests, functional tests etc.). I have tried mixing code and tests in the same project and found it much less maintainable than separating them into separate projects.</p>\n\n<p>Maintaining parallel namespaces and using a sensible naming convention for tests (eg. MyClass and MyClassTest) will help you keeping the codebase maintainable.</p>\n'}, {'answer_id': 81880, 'author': 'Rikalous', 'author_id': 4271, 'author_profile': 'https://Stackoverflow.com/users/4271', 'pm_score': 3, 'selected': False, 'text': '<p>The .Net framework after v2 has a useful feature where you can mark an assembly with the InternalsVisibleTo attribute that allows the assembly to be accessed by another.<br>\nA sort of assembly tunnelling feature.</p>\n'}, {'answer_id': 81881, 'author': 'Morten Christiansen', 'author_id': 4055, 'author_profile': 'https://Stackoverflow.com/users/4055', 'pm_score': 4, 'selected': False, 'text': '<p>As the others point out, a seperate test project (for each normal project) is a good way to do it. I usually mirror the namespaces and create a test class for each normal class with \'test\' appended to the name. This is supported directly in the IDE if you have Visual Studio Team System which can automatically generate test classes and methods in another project.</p>\n\n<p>One thing to remember if you want to test classes and methods with the \'internal\' accessor is to add the following line to the AssemblyInfo.cs file for each project to be tested:</p>\n\n<pre><code>[assembly: InternalsVisibleTo("UnitTestProjectName")]\n</code></pre>\n'}, {'answer_id': 81922, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 0, 'selected': False, 'text': '<p>I definitely agree with everyone else that you should separate the tests from your production code. If you insist on not, however, you should define a conditional comiplation constant called TEST, and wrap all of your unit test classes with a </p>\n\n<pre><code>#if TEST\n#endif\n</code></pre>\n\n<p>first to ensure that the test code does not compile in a production scenario. Once that is done, you should either be able to exclude the test dlls from your production deployment, or even better (but higher maintenance), create an NAnt or MSBuild for production that compiles without the references to the test dlls.</p>\n'}, {'answer_id': 81937, 'author': 'tsilb', 'author_id': 11112, 'author_profile': 'https://Stackoverflow.com/users/11112', 'pm_score': 2, 'selected': False, 'text': "<p>As long as your tests are in a seperate project, the tests can reference the codebase, but the codebase never has to reference the tests. I have to ask, what's confusing about maintaining two projects? You can keep them in the same solution for organization.</p>\n\n<p>The complicated part, of course, is when the business has 55 projects in the solution and 60% of them are tests. Count yourself lucky.</p>\n"}, {'answer_id': 82126, 'author': 'Hamish Smith', 'author_id': 15572, 'author_profile': 'https://Stackoverflow.com/users/15572', 'pm_score': 0, 'selected': False, 'text': "<p>I always create a separate Acme.Stuff.Test project that is compiled separately.</p>\n\n<p>The converse argument is: Why do you want to take the tests out? Why not deliver the test? If you deliver the tests along with a test runner you have some level of acceptance test and self test delivered with the product. </p>\n\n<p>I've heard this argument a few times and thought about it but I personally still keep tests in a separate project.</p>\n"}, {'answer_id': 82196, 'author': 'Niklas Winde', 'author_id': 9077, 'author_profile': 'https://Stackoverflow.com/users/9077', 'pm_score': 2, 'selected': False, 'text': "<p>I put the tests in a separate project but in the same solution. Granted, in big solutions there might be a lot of projects but the solution explorer is good enough on separating them and if you give everything reasonable names I don't really think it's an issue.</p>\n"}, {'answer_id': 121090, 'author': 'user21114', 'author_id': 21114, 'author_profile': 'https://Stackoverflow.com/users/21114', 'pm_score': 3, 'selected': False, 'text': '<p>Yet another alternative to using compiler directives within a file or creating a separate project is merely to create additional .cs files in your project.</p>\n\n<p>With some magic in the project file itself, you can dictate that:</p>\n\n<ol>\n<li>nunit.framework DLLs are only referenced in a debug build, and</li>\n<li>your test files are only included in debug builds</li>\n</ol>\n\n<p>Example .csproj excerpt:</p>\n\n<pre><code><Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">\n\n ...\n\n <Reference Include="nunit.framework" Condition=" \'$(Configuration)\'==\'Debug\' ">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>..\\..\\debug\\nunit.framework.dll</HintPath>\n </Reference>\n\n ...\n\n <Compile Include="Test\\ClassTest.cs" Condition=" \'$(Configuration)\'==\'Debug\' " />\n\n ...\n</Project>\n</code></pre>\n'}, {'answer_id': 744230, 'author': 'Kenneth Cochran', 'author_id': 71200, 'author_profile': 'https://Stackoverflow.com/users/71200', 'pm_score': 2, 'selected': False, 'text': '<p>One thing yet to be considered is versions of VisualStudio prior to 2005 did not allow EXE assembly projects to be referenced from other projects. So if you are working on a legacy project in VS.NET your options would be:</p>\n\n<ul>\n<li>Put unit tests in the same project and use conditional compilation to exclude them from release builds.</li>\n<li>Move everything to dll assemblies so your exe is just an entry point.</li>\n<li>Circumvent the IDE by hacking the project file in a text editor.</li>\n</ul>\n\n<p>Of the three conditional compilation is the least error prone.</p>\n'}, {'answer_id': 1098713, 'author': 'mbowles', 'author_id': 1112, 'author_profile': 'https://Stackoverflow.com/users/1112', 'pm_score': 1, 'selected': False, 'text': '<p>If the <strong>#if(DEBUG)</strong> tag allows for a clean "release" version, why would you need a separate project for tests. The nunit LibarryA/B example (yeah, I know its a example) does this. Currently wrestling with the scenario. Had been using a separate project, but this seems to possibly allow for some productivity improvements. Still hummin and hawin.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15497/'] |
81,786 | <p>I'd like to add a method <code>AddDefaultNamespace()</code> to the String class in Java so that I can type <code>"myString".AddDefaultNamespace()</code> instead of <code>DEFAULTNAMESPACE + "myString"</code>, to obtain something like <code>"MyDefaultNameSpace.myString"</code>. I don't want to add another derived class either (<code>PrefixedString</code> for example).</p>
<p>Maybe the approach is not good for you but I personally hate using <code>+</code>. But, anyway, is it possible to add new methods to the String class in Java?</p>
<p>Thanks and regards.</p>
| [{'answer_id': 81803, 'author': 'GustyWind', 'author_id': 11114, 'author_profile': 'https://Stackoverflow.com/users/11114', 'pm_score': 7, 'selected': True, 'text': '<p><code>String</code> is a final class which means it cannot be extended to work on your own implementation.</p>\n'}, {'answer_id': 81817, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 3, 'selected': False, 'text': "<p>It is not possible, since String is a final class in Java. </p>\n\n<p>You could use a helper method all the time you want to prefix something. If you don't like that you could look into Groovy or Scala, JRuby or JPython both are languages for the JVM compatible with Java and which allow such extensions.</p>\n"}, {'answer_id': 81835, 'author': 'Sietse', 'author_id': 6400, 'author_profile': 'https://Stackoverflow.com/users/6400', 'pm_score': 2, 'selected': False, 'text': "<p>Not possible, and that's a good thing. A String is a String. It's behaviour is defined, deviating from it would be evil. Also, it's marked final, meaning you couldn't subclass it even if you wanted to.</p>\n"}, {'answer_id': 81837, 'author': 'm_pGladiator', 'author_id': 446104, 'author_profile': 'https://Stackoverflow.com/users/446104', 'pm_score': 1, 'selected': False, 'text': '<p>Better use StringBuilder, which has method append() and does the job you want. The String class is final and can not be extended.</p>\n'}, {'answer_id': 81871, 'author': 'Carl-Johan', 'author_id': 15406, 'author_profile': 'https://Stackoverflow.com/users/15406', 'pm_score': 2, 'selected': False, 'text': '<p>The class declaration says it all pretty much,as you cannot inherit it becouse it\'s final.\nYou can ofcourse implement your own string-class, but that is probaby just a hassle.</p>\n\n<pre><code>public final class String\n</code></pre>\n\n<p>C# (.net 3.5) have the functionality to use extender metods but sadly java does not. There is some java extension called nice <a href="http://nice.sourceforge.net/" rel="nofollow noreferrer">http://nice.sourceforge.net/</a> though that seems to add the same functionality to java.</p>\n\n<p>Here is how you would write your example in the Nice language (an extension of\nJava):</p>\n\n<pre><code>private String someMethod(String s)\n{\n return s.substring(0,1);\n\n}\n\nvoid main(String[] args)\n{\n String s1 = "hello";\n String s2 = s1.someMethod();\n System.out.println(s2);\n\n}\n</code></pre>\n\n<p>You can find more about Nice at <a href="http://nice.sf.net" rel="nofollow noreferrer">http://nice.sf.net</a> </p>\n'}, {'answer_id': 81889, 'author': 'Martin Spamer', 'author_id': 15527, 'author_profile': 'https://Stackoverflow.com/users/15527', 'pm_score': 0, 'selected': False, 'text': '<p>The Java String class is a final, making it immutable. This is for efficiency reasons and that it would be extremely difficult to logically extend without error; the implementers have therefore chosen to make it a final class meaning it cannot be extended with inheritance.</p>\n\n<p>The functionality you wish your class to support is not properly part of the regular responsibilities of a String as per the <a href="http://www.oodesign.com/single-responsibility-principle.html" rel="nofollow noreferrer">single responsibility principle</a>, a namespace it is a different abstraction, it is more specialised. You should therefore define a new class, which includes String a member and supports the methods you need to provide the namespace management you require.</p>\n\n<p>Do not be afraid to add abstractions (classes) these are the essence of good OO design.</p>\n\n<p>Try using a <a href="http://en.wikipedia.org/wiki/Class-Responsibility-Collaboration_card" rel="nofollow noreferrer">class responsibility collaboration (CRC) card</a> to clarify the abstraction you need. </p>\n'}, {'answer_id': 81891, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>You can create your own version of String class and add a method :-)</p>\n'}, {'answer_id': 81917, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': -1, 'selected': False, 'text': '<p>Actually , you can modify the String class . If you edit the String.java file located in src.zip , and then rebuild the rt.jar , the String class will have more methods added by you . The downside is that that code will only work on your computer , or if you provide your String.class , and place it in the classpath before the default one .</p>\n'}, {'answer_id': 81946, 'author': 'MB.', 'author_id': 11961, 'author_profile': 'https://Stackoverflow.com/users/11961', 'pm_score': 2, 'selected': False, 'text': '<p>As everybody else has said, no you can\'t subclass String because it\'s final. But might something like the following help?</p>\n\n<pre><code>public final class NamespaceUtil {\n\n // private constructor cos this class only has a static method.\n private NamespaceUtil() {}\n\n public static String getDefaultNamespacedString(\n final String afterDotString) {\n return DEFAULT_NAMESPACE + "." + afterDotString;\n }\n\n}\n</code></pre>\n\n<p>or maybe:</p>\n\n<pre><code>public final class NamespacedStringFactory {\n\n private final String namespace;\n\n public NamespacedStringFactory(final String namespace) {\n this.namespace = namespace;\n }\n\n public String getNamespacedString(final String afterDotString) {\n return namespace + "." + afterDotString;\n }\n\n}\n</code></pre>\n'}, {'answer_id': 83552, 'author': 'Alex Miller', 'author_id': 7671, 'author_profile': 'https://Stackoverflow.com/users/7671', 'pm_score': 4, 'selected': False, 'text': "<p>As everyone else has noted, you are not allowed to extend String (due to final). However, if you are feeling really wild, you can modify String itself, place it in a jar, and prepend the bootclasspath with -Xbootclasspath/p:myString.jar to actually replace the built-in String class.</p>\n\n<p>For reasons I won't go into, I've actually done this before. You might be interested to know that even though you can replace the class, the intrinsic importance of String in every facet of Java means that it is use throughout the startup of the JVM and some changes will simply break the JVM. Adding new methods or constructors seems to be no problem. Adding new fields is very dicey - in particular adding Objects or arrays seems to break things although adding primitive fields seems to work. </p>\n"}, {'answer_id': 2077551, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>All is said by the other contributors before. You can not extend String directly because it is final.</p>\n\n<p>If you would use Scala, you can use implicit conversions like this:</p>\n\n<pre><code>object Snippet {\n class MyString(s:String) {\n def addDefaultNamespace = println("AddDefaultNamespace called")\n }\n implicit def wrapIt(s:String) = new MyString(s)\n\n /** test driver */\n def main(args:Array[String]):Unit = {\n "any java.io.String".addDefaultNamespace // !!! THAT is IT! OR?\n }\n</code></pre>\n'}, {'answer_id': 6806424, 'author': 'Aldo Barreras', 'author_id': 860157, 'author_profile': 'https://Stackoverflow.com/users/860157', 'pm_score': 5, 'selected': False, 'text': '<p>Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.</p>\n\n<pre><code>class MyString{\n public String str;\n public MyString(String str){\n this.str = str;\n }\n // Your methods.\n}\n</code></pre>\n\n<p>Then it\'s quite simple, you make your String as such:</p>\n\n<pre><code>MyString StringOne = new MyString("Stringy stuff");\n</code></pre>\n\n<p>and when you need to call a method in the String library, simple do so like this:</p>\n\n<pre><code>StringOne.str.equals("");\n</code></pre>\n\n<p>or something similar, and there you have it...extending of the String class.</p>\n'}, {'answer_id': 37406295, 'author': 'Drunken Daddy', 'author_id': 2067264, 'author_profile': 'https://Stackoverflow.com/users/2067264', 'pm_score': 2, 'selected': False, 'text': '<p>People searching with keywords "add method to built in class" might end up here. If you\'re looking to add method to a non final class such as HashMap, you can do something like this. </p>\n\n<pre><code>public class ObjectMap extends HashMap<String, Object> {\n\n public Map<String, Object> map;\n\n public ObjectMap(Map<String, Object> map){\n this.map = map;\n }\n\n public int getInt(String K) {\n return Integer.valueOf(map.get(K).toString());\n }\n\n public String getString(String K) {\n return String.valueOf(map.get(K));\n }\n\n public boolean getBoolean(String K) {\n return Boolean.valueOf(map.get(K).toString());\n }\n\n @SuppressWarnings("unchecked")\n public List<String> getListOfStrings(String K) {\n return (List<String>) map.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Integer> getListOfIntegers(String K) {\n return (List<Integer>) map.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Map<String, String>> getListOfMapString(String K) {\n return (List<Map<String, String>>) map.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Map<String, Object>> getListOfMapObject(String K) {\n return (List<Map<String, Object>>) map.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public Map<String, Object> getMapOfObjects(String K) {\n return (Map<String, Object>) map.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public Map<String, String> getMapOfStrings(String K) {\n return (Map<String, String>) map.get(K);\n }\n}\n</code></pre>\n\n<p>Now define a new Instance of this class as:</p>\n\n<pre><code>ObjectMap objectMap = new ObjectMap(new HashMap<String, Object>();\n</code></pre>\n\n<p>Now you can access all the method of the built-in Map class, and also the newly implemented methods.</p>\n\n<pre><code>objectMap.getInt("KEY");\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>In the above code, for accessing the built-in methods of map class, you\'d have to use </p>\n\n<pre><code>objectMap.map.get("KEY");\n</code></pre>\n\n<p>Here\'s an even better solution:</p>\n\n<pre><code>public class ObjectMap extends HashMap<String, Object> {\n\n public ObjectMap() {\n\n }\n\n public ObjectMap(Map<String, Object> map){\n this.putAll(map);\n }\n\n public int getInt(String K) {\n return Integer.valueOf(this.get(K).toString());\n }\n\n public String getString(String K) {\n return String.valueOf(this.get(K));\n }\n\n public boolean getBoolean(String K) {\n return Boolean.valueOf(this.get(K).toString());\n }\n\n @SuppressWarnings("unchecked")\n public List<String> getListOfStrings(String K) {\n return (List<String>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Integer> getListOfIntegers(String K) {\n return (List<Integer>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Map<String, String>> getListOfMapString(String K) {\n return (List<Map<String, String>>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public List<Map<String, Object>> getListOfMapObject(String K) {\n return (List<Map<String, Object>>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public Map<String, Object> getMapOfObjects(String K) {\n return (Map<String, Object>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public Map<String, String> getMapOfStrings(String K) {\n return (Map<String, String>) this.get(K);\n }\n\n @SuppressWarnings("unchecked")\n public boolean getBooleanForInt(String K) {\n return Integer.valueOf(this.get(K).toString()) == 1 ? true : false;\n }\n}\n</code></pre>\n\n<p>Now you don\'t have to call</p>\n\n<pre><code>objectMap.map.get("KEY");\n</code></pre>\n\n<p>simply call</p>\n\n<pre><code>objectMap.get("KEY");\n</code></pre>\n'}, {'answer_id': 45282404, 'author': 'Vpn_talent', 'author_id': 6011941, 'author_profile': 'https://Stackoverflow.com/users/6011941', 'pm_score': 1, 'selected': False, 'text': '<p>No You Cannot Modify String Class in java. Because It\'s final class. and every method present in final class by default will be final.</p>\n\n<p>The absolutely most important reason that String is immutable or final is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.</p>\n\n<p>Had String been mutable or not final, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"</p>\n'}, {'answer_id': 50412907, 'author': 'PaulB', 'author_id': 5335776, 'author_profile': 'https://Stackoverflow.com/users/5335776', 'pm_score': 2, 'selected': False, 'text': '<p><strong>YES!</strong></p>\n\n<p>Based on your requirements (add a different namespace to a String and not use a derived class) you could use project Lombok to do just that and use functionality on a String like so:</p>\n\n<pre><code>String i = "This is my String";\ni.numberOfCapitalCharacters(); // = 2\n</code></pre>\n\n<p>Using Gradle and IntelliJ idea follow the steps below:</p>\n\n<ol>\n<li>Download the lombok plugin from intelliJ plugins repository.</li>\n<li>add lombok to dependencies in gradle like so: <code>compileOnly \'org.projectlombok:lombok:1.16.20\'</code></li>\n<li>go to <code>"Settings > Build > Compiler > Annotation Processors"</code> and enable annotation processing</li>\n<li><p>create a class with your extension functions and add a static method like this: </p>\n\n<pre><code>public class Extension {\n public static String appendSize(String i){\n return i + " " + i.length();\n }\n}\n</code></pre></li>\n<li><p>annotate the class where you want to use your method like this:</p>\n\n<pre><code>import lombok.experimental.ExtensionMethod;\n\n@ExtensionMethod({Extension.class})\npublic class Main {\n public static void main(String[] args) {\n String i = "This is a String!";\n System.out.println(i.appendSize());\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Now you can use the method <code>.appendSize()</code> on any string in any class as long as you have annotated it and the produced result for the above example</p>\n\n<blockquote>\n <p>This is a String!</p>\n</blockquote>\n\n<p>would be: </p>\n\n<blockquote>\n <p>This is a String! 17</p>\n</blockquote>\n'}, {'answer_id': 74656039, 'author': 'Ogün', 'author_id': 10480017, 'author_profile': 'https://Stackoverflow.com/users/10480017', 'pm_score': 0, 'selected': False, 'text': '<p>You can do this easily with Kotlin. You can run both the kotlin code from within the java and the java code from the kotlin.</p>\n<p>Difficult jobs that you can do with Java can be done more easily with Kotlin. I recommend every java developer to learn kotlin.</p>\n<p>Referance: <a href="https://kotlinlang.org/docs/java-to-kotlin-interop.html" rel="nofollow noreferrer">https://kotlinlang.org/docs/java-to-kotlin-interop.html</a></p>\n<p>Example:</p>\n<p>Kotlin StringUtil.kt File</p>\n<pre><code>@file:JvmName("StringUtil")\npackage com.example\n\nfun main() {\nval x: String = "xxx"\nprintln(x.customMethod())\n}\n\nfun String.customMethod(): String = this + " ZZZZ"\n</code></pre>\n<p>Java Code:</p>\n<pre><code>package com.example;\n\npublic class AppStringCustomMethod {\n\npublic static void main(String[] args) {\n String kotlinResponse = StringUtil.customMethod("ffff");\n System.out.println(kotlinResponse);\n}\n}\n</code></pre>\n<p>output:</p>\n<p>ffff ZZZZ</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15546/'] |
81,788 | <p>I couldn't find a decent ThreadPool implementation for Ruby, so I wrote mine (based partly on code from here: <a href="http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276" rel="nofollow noreferrer">http://web.archive.org/web/20081204101031/http://snippets.dzone.com:80/posts/show/3276</a> , but changed to wait/signal and other implementation for ThreadPool shutdown. However after some time of running (having 100 threads and handling about 1300 tasks), it dies with deadlock on line 25 - it waits for a new job there. Any ideas, why it might happen?</p>
<pre><code>require 'thread'
begin
require 'fastthread'
rescue LoadError
$stderr.puts "Using the ruby-core thread implementation"
end
class ThreadPool
class Worker
def initialize(callback)
@mutex = Mutex.new
@cv = ConditionVariable.new
@callback = callback
@mutex.synchronize {@running = true}
@thread = Thread.new do
while @mutex.synchronize {@running}
block = get_block
if block
block.call
reset_block
# Signal the ThreadPool that this worker is ready for another job
@callback.signal
else
# Wait for a new job
@mutex.synchronize {@cv.wait(@mutex)} # <=== Is this line 25?
end
end
end
end
def name
@thread.inspect
end
def get_block
@mutex.synchronize {@block}
end
def set_block(block)
@mutex.synchronize do
raise RuntimeError, "Thread already busy." if @block
@block = block
# Signal the thread in this class, that there's a job to be done
@cv.signal
end
end
def reset_block
@mutex.synchronize {@block = nil}
end
def busy?
@mutex.synchronize {[email protected]?}
end
def stop
@mutex.synchronize {@running = false}
# Signal the thread not to wait for a new job
@cv.signal
@thread.join
end
end
attr_accessor :max_size
def initialize(max_size = 10)
@max_size = max_size
@workers = []
@mutex = Mutex.new
@cv = ConditionVariable.new
end
def size
@mutex.synchronize {@workers.size}
end
def busy?
@mutex.synchronize {@workers.any? {|w| w.busy?}}
end
def shutdown
@mutex.synchronize {@workers.each {|w| w.stop}}
end
alias :join :shutdown
def process(block=nil,&blk)
block = blk if block_given?
while true
@mutex.synchronize do
worker = get_worker
if worker
return worker.set_block(block)
else
# Wait for a free worker
@cv.wait(@mutex)
end
end
end
end
# Used by workers to report ready status
def signal
@cv.signal
end
private
def get_worker
free_worker || create_worker
end
def free_worker
@workers.each {|w| return w unless w.busy?}; nil
end
def create_worker
return nil if @workers.size >= @max_size
worker = Worker.new(self)
@workers << worker
worker
end
end
</code></pre>
| [{'answer_id': 82034, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 1, 'selected': False, 'text': "<p>I'm slightly biased here, but I would suggest modelling this in some process language and model check it. Freely available tools are, for example, the mCRL2 toolset (using a ACP-based language), the Mobility Workbench (pi-calculus) and Spin (PROMELA).</p>\n\n<p>Otherwise I would suggest removing every bit of code that is not essential to the problem and finding a minimal case where the deadlock occurs. I doubt that it the 100 threads and 1300 tasks are essential to get a deadlock. With a smaller case you can probably just add some debug prints which provide enough information the solve the problem.</p>\n"}, {'answer_id': 82061, 'author': 'PierreBdR', 'author_id': 7136, 'author_profile': 'https://Stackoverflow.com/users/7136', 'pm_score': 1, 'selected': False, 'text': "<p>Ok, the problem seems to be in your ThreadPool#signal method. What may happen is:</p>\n\n<p>1 - All your worker are busy and you try to process a new job</p>\n\n<p>2 - line 90 gets a nil worker</p>\n\n<p>3 - a worker get freed and signals it, but the signal is lost as the ThreadPool is not waiting for it</p>\n\n<p>4 - you fall on line 95, waiting even though there is a free worker.</p>\n\n<p>The error here is that you can signal a free worker even when nobody is listening. This ThreadPool#signal method should be:</p>\n\n<pre><code>def signal\n @mutex.synchronize { @cv.signal }\nend\n</code></pre>\n\n<p>And the problem is the same in the Worker object. What might happen is:</p>\n\n<p>1 - The Worker just completed a job</p>\n\n<p>2 - It checks (line 17) if there is a job waiting: there isn't</p>\n\n<p>3 - The thread pool send a new job and signals it ... but the signal is lost</p>\n\n<p>4 - The worker wait for a signal, even though it is marked as busy</p>\n\n<p>You should put your initialize method as:</p>\n\n<pre><code>def initialize(callback)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @callback = callback\n @mutex.synchronize {@running = true}\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n # Signal the ThreadPool that this worker is ready for another job\n @callback.signal\n else\n # Wait for a new job\n @cv.wait(@mutex)\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>Next, the Worker#get_block and Worker#reset_block methods should not be synchronized anymore. That way, you cannot have a block assigned to a worker between the test for a block and the wait for a signal.</p>\n"}, {'answer_id': 82777, 'author': 'PierreBdR', 'author_id': 7136, 'author_profile': 'https://Stackoverflow.com/users/7136', 'pm_score': 5, 'selected': True, 'text': '<p>Ok, so the main problem with the implementation is: how to make sure no signal is lost and avoid dead locks ?</p>\n\n<p>In my experience, this is REALLY hard to achieve with condition variables and mutex, but easy with semaphores. It so happens that ruby implement an object called Queue (or SizedQueue) that should solve the problem. Here is my suggested implementation:</p>\n\n<pre><code>require \'thread\'\nbegin\n require \'fasttread\'\nrescue LoadError\n $stderr.puts "Using the ruby-core thread implementation"\nend\n\nclass ThreadPool\n class Worker\n def initialize(thread_queue)\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @queue = thread_queue\n @running = true\n @thread = Thread.new do\n @mutex.synchronize do\n while @running\n @cv.wait(@mutex)\n block = get_block\n if block\n @mutex.unlock\n block.call\n @mutex.lock\n reset_block\n end\n @queue << self\n end\n end\n end\n end\n\n def name\n @thread.inspect\n end\n\n def get_block\n @block\n end\n\n def set_block(block)\n @mutex.synchronize do\n raise RuntimeError, "Thread already busy." if @block\n @block = block\n # Signal the thread in this class, that there\'s a job to be done\n @cv.signal\n end\n end\n\n def reset_block\n @block = nil\n end\n\n def busy?\n @mutex.synchronize { [email protected]? }\n end\n\n def stop\n @mutex.synchronize do\n @running = false\n @cv.signal\n end\n @thread.join\n end\n end\n\n attr_accessor :max_size\n\n def initialize(max_size = 10)\n @max_size = max_size\n @queue = Queue.new\n @workers = []\n end\n\n def size\n @workers.size\n end\n\n def busy?\n @queue.size < @workers.size\n end\n\n def shutdown\n @workers.each { |w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block=nil,&blk)\n block = blk if block_given?\n worker = get_worker\n worker.set_block(block)\n end\n\n private\n\n def get_worker\n if [email protected]? or @workers.size == @max_size\n return @queue.pop\n else\n worker = Worker.new(@queue)\n @workers << worker\n worker\n end\n end\n\nend\n</code></pre>\n\n<p>And here is a simple test code:</p>\n\n<pre><code>tp = ThreadPool.new 500\n(1..1000).each { |i| tp.process { (2..10).inject(1) { |memo,val| sleep(0.1); memo*val }; print "Computation #{i} done. Nb of tasks: #{tp.size}\\n" } }\ntp.shutdown\n</code></pre>\n'}, {'answer_id': 2063180, 'author': 'Filipe Miguel Fonseca', 'author_id': 112744, 'author_profile': 'https://Stackoverflow.com/users/112744', 'pm_score': 3, 'selected': False, 'text': '<p>You can try the <a href="http://gemcutter.org/gems/work_queue" rel="nofollow noreferrer">work_queue</a> gem, designed to coordinate work between a producer and a pool of worker threads.</p>\n'}, {'answer_id': 51769759, 'author': 'bking', 'author_id': 7915982, 'author_profile': 'https://Stackoverflow.com/users/7915982', 'pm_score': 1, 'selected': False, 'text': '<p>Top commenter\'s code has helped out so much over the years. Here it is updated for ruby 2.x and improved with thread identification. How is that an improvement? When each thread has an ID, you can compose ThreadPool with an array which stores arbitrary information. Some ideas:</p>\n\n<ul>\n<li>No array: typical ThreadPool usage. Even with the GIL it makes threading dead easy to code and very useful for high-latency applications like high-volume web crawling,</li>\n<li>ThreadPool and Array sized to number of CPUs: easy to fork processes to use all CPUs,</li>\n<li>ThreadPool and Array sized to number of resources: e.g., each array element represents one processor across a pool of instances, so if you have 10 instances each with 4 CPUs, the TP can manage work across 40 subprocesses.</li>\n</ul>\n\n<p>With these last two, rather than thinking about threads doing work think about the ThreadPool managing subprocesses that are doing the work. The management task is lightweight and when combined with subprocesses, who cares about the GIL. </p>\n\n<p>With this class, you can code up a cluster based MapReduce in about a hundred lines of code! This code is beautifully short although it can be a bit of a mind-bend to fully grok. Hope it helps.</p>\n\n<pre><code># Usage:\n#\n# Thread.abort_on_exception = true # help localize errors while debugging\n# pool = ThreadPool.new(thread_pool_size)\n# 50.times {|i|\n# pool.process { ... }\n# or\n# pool.process {|id| ... } # worker identifies itself as id\n# }\n# pool.shutdown()\n\nclass ThreadPool\n\n require \'thread\'\n\n class ThreadPoolWorker\n\n attr_accessor :id\n\n def initialize(thread_queue, id)\n @id = id # worker id is exposed thru tp.process {|id| ... }\n @mutex = Mutex.new\n @cv = ConditionVariable.new\n @idle_queue = thread_queue\n @running = true\n @block = nil\n @thread = Thread.new {\n @mutex.synchronize {\n while @running\n @cv.wait(@mutex) # block until there is work to do\n if @block\n @mutex.unlock\n begin\n @block.call(@id)\n ensure\n @mutex.lock\n end\n @block = nil\n end\n @idle_queue << self\n end\n }\n }\n end\n\n def set_block(block)\n @mutex.synchronize {\n raise RuntimeError, "Thread is busy." if @block\n @block = block\n @cv.signal # notify thread in this class, there is work to be done\n }\n end\n\n def busy?\n @mutex.synchronize { ! @block.nil? }\n end\n\n def stop\n @mutex.synchronize {\n @running = false\n @cv.signal\n }\n @thread.join\n end\n\n def name\n @thread.inspect\n end\n end\n\n\n attr_accessor :max_size, :queue\n\n def initialize(max_size = 10)\n @process_mutex = Mutex.new\n @max_size = max_size\n @queue = Queue.new # of idle workers\n @workers = [] # array to hold workers\n\n # construct workers\n @max_size.times {|i| @workers << ThreadPoolWorker.new(@queue, i) }\n\n # queue up workers (workers in queue are idle and available to\n # work). queue blocks if no workers are available.\n @max_size.times {|i| @queue << @workers[i] }\n\n sleep 1 # important to give threads a chance to initialize\n end\n\n def size\n @workers.size\n end\n\n def idle\n @queue.size\n end\n\n # are any threads idle\n\n def busy?\n # @queue.size < @workers.size\n @queue.size == 0 && @workers.size == @max_size\n end\n\n # block until all threads finish\n\n def shutdown\n @workers.each {|w| w.stop }\n @workers = []\n end\n\n alias :join :shutdown\n\n def process(block = nil, &blk)\n @process_mutex.synchronize {\n block = blk if block_given?\n worker = @queue.pop # assign to next worker; block until one is ready\n worker.set_block(block) # give code block to worker and tell it to start\n }\n end\n\n\nend\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12695/'] |
81,830 | <p>Grails vs Rails. Which has better support? And which one is a better choice to develop medium size apps with? Most importantly which one has more plug-ins?</p>
| [{'answer_id': 81845, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 1, 'selected': False, 'text': "<p>Rails is more mainstream, but less flexible. Grails is still changing rapidly, doesn't have the same developer ecosystem, and the documentation isn't nearly as mature, but it will work in some situations Rails won't.</p>\n"}, {'answer_id': 81860, 'author': 'Scott Anderson', 'author_id': 15559, 'author_profile': 'https://Stackoverflow.com/users/15559', 'pm_score': 4, 'selected': False, 'text': '<p>I guess if you are a Java developer and want to have access to all the existing enterprise Java libraries and functionality... go with Grails. </p>\n'}, {'answer_id': 82055, 'author': 'tomafro', 'author_id': 7126, 'author_profile': 'https://Stackoverflow.com/users/7126', 'pm_score': 3, 'selected': False, 'text': "<p>Rails is more mature, has more plugins, has a bigger userbase, has better documentation and support available. It can also run on JRuby giving access to Java libraries if you require.</p>\n\n<p>Grails has some interesting qualities, but can't claim to be up there with rails just yet. However, if you're predominantly a Java or groovy developer you may prefer it. Otherwise though, I'd suggest using Rails for medium sized projects right now.</p>\n"}, {'answer_id': 82634, 'author': 'Ed.T', 'author_id': 3014, 'author_profile': 'https://Stackoverflow.com/users/3014', 'pm_score': 3, 'selected': False, 'text': "<p>It depends on your skills with Ruby and/or Groovy, whether you have legacy Java systems to deal with, and where you want to deploy your applications. </p>\n\n<p>I was initially thrilled with Rails. At the time, there wasn't an option of deploying on the application servers at work since work is all Java. This has changed. I couldn't abandon the Java infrastructure and applications already in place and switch to Ruby, even though I thought Rails was awesome. Grails works because we can mix and match Groovy with the existing Java solutions.</p>\n\n<p>Outside of work, Ruby is easier to find hosting for at the low end of the price spectrum. Because Grails uses a lot of existing Java projects the .war files, even for a small app, tend to be large. If you have a dedicated server this isn't a problem but trying to run on shared hosting with 128 MB RAM doesn't work.</p>\n\n<p>2008 is the year of Groovy and Grails books but there are still many more Rails resources available.</p>\n\n<p>Based on your specific criteria, Rails may be a better framework to learn. If you have any Java knowledge, or baggage ;-), you should look at Grails.</p>\n"}, {'answer_id': 82658, 'author': 'Marcin Gil', 'author_id': 5731, 'author_profile': 'https://Stackoverflow.com/users/5731', 'pm_score': 2, 'selected': False, 'text': '<p>May I suggest <a href="http://merbivore.com" rel="nofollow noreferrer">Merb</a>? It is rack-based, modular, ORM-agnostic, built for speed from ground up by Ezra Zygmuntowicz. It is starting to gain some heat now...</p>\n'}, {'answer_id': 90671, 'author': 'Chii', 'author_id': 17335, 'author_profile': 'https://Stackoverflow.com/users/17335', 'pm_score': 3, 'selected': False, 'text': "<p>I say grails since there are so many java libraries out there. But I am a bit biased due to the fact that I come from a java background. </p>\n\n<p>If the app isn't going to be big, either suffices - and the choice ought to depend on existing infrastructure. Say if you already have a java servlet container server running, you might as well stick with grails instead of provisioning another server for rails.</p>\n"}, {'answer_id': 92683, 'author': 'Rollo Tomazzi', 'author_id': 11477, 'author_profile': 'https://Stackoverflow.com/users/11477', 'pm_score': 6, 'selected': True, 'text': '<p>One other thing worth mentioning: the design philosophy of both framework is somewhat different when it comes to the model. Grails is more "domain-oriented" while Rails is more "database-oriented".<br>\nIn Rails, you essentially start by defining your tables (with field names and their specifics). Then ActiveRecord will map them to Ruby classes or models.<br>\nIn Grails, it\'s the reverse: you start by defining your models (Groovy classes) and when you hit run, GORM (Grails ActiveRecord equivalent) will create the related database and tables (or update them). Which may also be why you don\'t have the concept of \'migrations\' in Grails (although I think it will come in some future release).<br>\nI don\'t know if one is better than the other. I guess it depends on your context.</p>\n\n<p>This being said, I\'m still myself wondering which one to choose. As Tom was saying, if you\'re dependent on Java you can still go for JRuby - so Java reuse shouldn\'t be your sole criterion.</p>\n'}, {'answer_id': 96531, 'author': 'Peter Kahn', 'author_id': 9950, 'author_profile': 'https://Stackoverflow.com/users/9950', 'pm_score': 0, 'selected': False, 'text': "<p>I have used turbogears and rails a little bit. Before using rails, I tried using grails because I was using groovy for my scripting. Grails was a difficult experience. </p>\n\n<p>The groovy call stack is difficult to read for a small program, but when you add in several heavy weight frameworks a simple error can yield 100s of lines. Unlike rails the grails version that I was using didn't have tools to help me determine what was mine and what belonged to the framework.</p>\n\n<p>I eventually switched to using the Google Web toolkit since I really didn't need the database.</p>\n\n<p>I think Grails and Groovy hold promise, but the user experience of working with them is cumbersome at present (present being last spring).</p>\n"}, {'answer_id': 288570, 'author': 'hendrixski', 'author_id': 24920, 'author_profile': 'https://Stackoverflow.com/users/24920', 'pm_score': 2, 'selected': False, 'text': "<p>Seeing as how the guys who make Grails just got bought out by Spring source yesterday, I would say Grails.</p>\n\n<p>Also, since Groovy is a superset of Java, you can dive right in just using the Java you know without having to learn Ruby. Now, you'll learn a lot of dynamic stuff too and eventually write Groovy code instead of Java code, but it lowers the barrier to entry.</p>\n\n<p>Grails all the way!</p>\n"}, {'answer_id': 391304, 'author': 'Karsten Silz', 'author_id': 3574, 'author_profile': 'https://Stackoverflow.com/users/3574', 'pm_score': 2, 'selected': False, 'text': "<p>I would go with Grails since I like its approach (specify your domain classes and have Grails generate everything else) better than the Rails one (build database tables and have Rails generate everything else). If you're a Java developer, you'll also like that Java code is valid Groovy code, and a Groovy class is a Java class so the integration is seamless both ways.</p>\n"}, {'answer_id': 1194141, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>As a Grails developer coming from Java, I loved it from the very first time. </p>\n\n<p>Now, I'm starting to dig into Rails and having problems with gem. While MySQL connection setup with Grails was pretty straightforward, I'm still struggling to make it work with Rails. </p>\n\n<p>The command <code>gem install mysql</code> is not working, apparently because I don't have XCode intalled.</p>\n\n<p>If it weren't for its memory consumption issue, I'd say Grails is perfect.</p>\n"}, {'answer_id': 4449542, 'author': 'oceanician', 'author_id': 494690, 'author_profile': 'https://Stackoverflow.com/users/494690', 'pm_score': 0, 'selected': False, 'text': "<p>I think it depends on the environment you're working in to some extent.</p>\n\n<p>Grails seems to have more corporate level acceptance.</p>\n\n<p>Rails has the Koolaid-vibe, and is very acceptable for start-ups with no legacy systems.</p>\n\n<p>Personally I'm using both. Though only really just starting out in the Grails world - I like that authentication/authorisation is easier in Grails-one simple plugin; Shiro. I like that Rails isn't dependant on JVM, and doesn't take a minute or so to startup.</p>\n\n<p>I find setting up BDD/Cucumber within Rails was far easier, but that could just be because that's what I'm comfortable with! There's definitely efforts in the Grails world (cuke4duke etc) to make this easier-and an active community developing Grails.</p>\n\n<p>Just my 2p·</p>\n\n<p>Try both :)</p>\n"}, {'answer_id': 8720224, 'author': 'ibaralf', 'author_id': 609043, 'author_profile': 'https://Stackoverflow.com/users/609043', 'pm_score': 3, 'selected': False, 'text': '<p>I used rails before and liked it quite a bit. However, my current company had a lot of legacy java code and therefore the natural choice was grails. </p>\n\n<p>When I started with rails, very few sites were using it and documentation was atrocious. There was railscast that was great and railsforum.com, but anything out of the ordinary, you\'re on your own. Deploying it was a nightmare, and using mongrel-clusters was not really production ready. This is very different now as everybody can see, much more mature and deployed everywhere.</p>\n\n<p>Over a year back, I had to learn grails due to reason I cited above. Transitioning to grails was very easy, since it is very similar to Rails. Again, it was very similar to the early stages of rails, with one huge difference. Because you can easily import java code, grails users can use almost all the production tested java libraries available out there. I\'ve been able to successfully integrate our legacy java projects into grails projects and very little tweaking are needed. You will also notice that plugin development has been rapid, mainly because developers are just writing grails "hooks" but the underlying code are the old java libraries. Deploying grails is also just deploying a WAR file.</p>\n\n<p>Another thing you have to look at is IDE. If you\'re comfortable with eclipse, then eclipse-STS for grails gives you all the bells and whistles. I still see a lot of rails developers use textmate, though rubymine has made great strides (the early version of rubymine used to grind my ubuntu to a halt).</p>\n\n<p>The bottom line, both are great MVC frameworks. RoR is much more mature and has a lot more developers. Grails is where RoR was 3-4 years ago, but I see the progress a lot more faster. Hope this helps.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15476/'] |
81,862 | <p>I'd like to encourage our users of our RCP application to send the problem details to our support department. To this end, I've added a "Contact support" widget to our standard error dialogue.</p>
<p>I've managed to use URI headers to send a stacktrace using Java 6's JDIC call: <a href="http://java.sun.com/javase/6/docs/api/java/net/URI.html" rel="nofollow noreferrer"><code>Desktop.getDesktop().mail(java.net.URI)</code></a>. This will fire up the user's mail client, ready for them to add their comments, and hit send. </p>
<p>I like firing up the email client, because it's what the user is used to, it tells support a whole lot about the user (sigs, contact details etc) and I don't really want <a href="http://www.catb.org/~esr/jargon/html/Z/Zawinskis-Law.html" rel="nofollow noreferrer">to ship with Java Mail</a>.</p>
<p>What I'd like to do is attach the log file and the stacktrace as a file, so there is no maximum length requirement, and the user sees a nice clean looking email, and the support department has a lot more information to work with.</p>
<p>Can I do this with the approach I'm taking? Or is there a better way?</p>
<p><strong>Edit</strong>:
I'm in an OSGi context, so bundling JDIC would be necessary. If possible, I'd like to ship with as few dependencies as possible, and bundling up the JDIC for multiple platforms does not sound fun, especially for such a small feature.</p>
<p>JavaMail may be suitable, but for the fact that this will be on desktops of our corporate clients. The <strong>setup/discovery of configuration</strong> would have to be transparent, automatic and reliable. Regarding JavaMail, configuration seems to be manual only. Is this the case?</p>
<p>The answer I like most is using the <code>Desktop.open()</code> for an *.eml file. Unfortunately <strong>Outlook Express (rather than Outlook) opens eml files</strong>. I have no idea if this is usual or default to have Windows configured for to open EML files like this. Is this usual? Or is there another text based format that a) is easy to generate, b) opens by default in the same email client as users would be using already?</p>
| [{'answer_id': 81882, 'author': 'tim_yates', 'author_id': 6509, 'author_profile': 'https://Stackoverflow.com/users/6509', 'pm_score': 0, 'selected': False, 'text': '<p>Using that method, you can set the subject line and body text with a URI like</p>\n\n<pre><code>mailto:[email protected]?SUBJECT=Support mail&BODY=This is a support mail\n</code></pre>\n\n<p>However, the length of the subject and body text will <a href="http://forums.java.net/jive/thread.jspa?messageID=204302&tstart=0" rel="nofollow noreferrer">have some limitation</a></p>\n\n<p>There is no way I can think of to attatch a file using this method or something similar (without adding javamail to your app)</p>\n'}, {'answer_id': 81988, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 3, 'selected': True, 'text': '<p>You could save a temporary .eml file, and Desktop.getDesktop().open(emlFile)<br>\n<strong>Edit:</strong> As you point out, this will unfortunately open outlook express instead of outlook.<br>\nHowever if you have Windows Live Mail installed, it will use that.</p>\n'}, {'answer_id': 82337, 'author': 'entzik', 'author_id': 12297, 'author_profile': 'https://Stackoverflow.com/users/12297', 'pm_score': 0, 'selected': False, 'text': '<p>JDIC may not always be available on your user\'s platform. A good way to do this is to use the javamail API. You can send a multi-part e-mail message as explained in this tutorial by SUN:</p>\n\n<p><a href="http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#SendingAttachments" rel="nofollow noreferrer">Sending Attachments</a></p>\n'}, {'answer_id': 83815, 'author': 'Asgeir S. Nilsen', 'author_id': 16023, 'author_profile': 'https://Stackoverflow.com/users/16023', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using JDK 6 (you really should), the Desktop API is now part of the JRE. See <a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/" rel="nofollow noreferrer">http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/</a> for more information.</p>\n'}, {'answer_id': 86176, 'author': 'user11915', 'author_id': 11915, 'author_profile': 'https://Stackoverflow.com/users/11915', 'pm_score': 1, 'selected': False, 'text': "<p>As a completely different way of handling the same problem, we use a bug tracker with an XML-RPC interface, and our (RCP also, btw) app talks to that using a custom submission dialogue. It means we can send the log files to help diagnose the problem, without the user having to find them. </p>\n\n<p>I'm sure most bug trackers have something like this available. We use Jira, and it works great (apparently, they've just released a free Personal version that makes it easy to try).</p>\n"}, {'answer_id': 4014528, 'author': 'Joeky', 'author_id': 486406, 'author_profile': 'https://Stackoverflow.com/users/486406', 'pm_score': 0, 'selected': False, 'text': '<pre><code>import java.awt.Desktop;\nimport java.io.File;\nimport java.net.URI;\n\n\npublic class TestMail {\n\n public static void main(String[] args) {\n try { \n Runtime.getRuntime().exec(\n new String[] {"rundll32", "url.dll,FileProtocolHandler",\n "mailto:[email protected]?subject=someSubject&[email protected]&[email protected]&body=someBodyText&Attach=c:\\\\test\\\\test.doc"}, null\n );\n\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4737/'] |
81,870 | <p>For example:</p>
<pre><code>int a = 12;
cout << typeof(a) << endl;
</code></pre>
<p>Expected output:</p>
<pre><code>int
</code></pre>
| [{'answer_id': 81886, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 8, 'selected': False, 'text': '<p>Try:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>#include <typeinfo>\n\n// …\nstd::cout << typeid(a).name() << \'\\n\';\n</code></pre>\n\n<p>You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between.</p>\n'}, {'answer_id': 81913, 'author': 'mdec', 'author_id': 15534, 'author_profile': 'https://Stackoverflow.com/users/15534', 'pm_score': 6, 'selected': False, 'text': "<p>Don't forget to include <code><typeinfo></code></p>\n\n<p>I believe what you are referring to is runtime type identification. You can achieve the above by doing .</p>\n\n<pre><code>#include <iostream>\n#include <typeinfo>\n\nusing namespace std;\n\nint main() {\n int i;\n cout << typeid(i).name();\n return 0;\n}\n</code></pre>\n"}, {'answer_id': 81939, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 4, 'selected': False, 'text': '<p>You could use a traits class for this. Something like:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\ntemplate <typename T> class type_name {\npublic:\n static const char *name;\n};\n\n#define DECLARE_TYPE_NAME(x) template<> const char *type_name<x>::name = #x;\n#define GET_TYPE_NAME(x) (type_name<typeof(x)>::name)\n\nDECLARE_TYPE_NAME(int);\n\nint main()\n{\n int a = 12;\n cout << GET_TYPE_NAME(a) << endl;\n}\n</code></pre>\n\n<p>The <code>DECLARE_TYPE_NAME</code> define exists to make your life easier in declaring this traits class for all the types you expect to need.</p>\n\n<p>This might be more useful than the solutions involving <code>typeid</code> because you get to control the output. For example, using <code>typeid</code> for <code>long long</code> on my compiler gives "x".</p>\n'}, {'answer_id': 81956, 'author': 'Nick', 'author_id': 3233, 'author_profile': 'https://Stackoverflow.com/users/3233', 'pm_score': 5, 'selected': False, 'text': '<p>You can use templates.</p>\n\n<pre><code>template <typename T> const char* typeof(T&) { return "unknown"; } // default\ntemplate<> const char* typeof(int&) { return "int"; }\ntemplate<> const char* typeof(float&) { return "float"; }\n</code></pre>\n\n<p>In the example above, when the type is not matched it will print "unknown". </p>\n'}, {'answer_id': 82102, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 5, 'selected': False, 'text': "<p>Note that the names generated by the RTTI feature of C++ is <strong>not</strong> portable.\nFor example, the class</p>\n\n<pre><code>MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>\n</code></pre>\n\n<p>will have the following names:</p>\n\n<pre><code>// MSVC 2003:\nclass MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]\n// G++ 4.2:\nN8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE\n</code></pre>\n\n<p>So you can't use this information for serialization. But still, the typeid(a).name() property can still be used for log/debug purposes</p>\n"}, {'answer_id': 82144, 'author': 'James Hopkin', 'author_id': 11828, 'author_profile': 'https://Stackoverflow.com/users/11828', 'pm_score': 3, 'selected': False, 'text': '<p>The other answers involving RTTI (typeid) are probably what you want, as long as:</p>\n\n<ul>\n<li>you can afford the memory overhead (which can be considerable with some compilers)</li>\n<li>the class names your compiler returns are useful</li>\n</ul>\n\n<p>The alternative, (similar to Greg Hewgill\'s answer), is to build a compile-time table of traits.</p>\n\n<pre><code>template <typename T> struct type_as_string;\n\n// declare your Wibble type (probably with definition of Wibble)\ntemplate <>\nstruct type_as_string<Wibble>\n{\n static const char* const value = "Wibble";\n};\n</code></pre>\n\n<p>Be aware that if you wrap the declarations in a macro, you\'ll have trouble declaring names for template types taking more than one parameter (e.g. std::map), due to the comma.</p>\n\n<p>To access the name of the type of a variable, all you need is</p>\n\n<pre><code>template <typename T>\nconst char* get_type_as_string(const T&)\n{\n return type_as_string<T>::value;\n}\n</code></pre>\n'}, {'answer_id': 14617848, 'author': 'NickV', 'author_id': 1617892, 'author_profile': 'https://Stackoverflow.com/users/1617892', 'pm_score': 7, 'selected': False, 'text': '<p>Very ugly but does the trick if you only want compile time info (e.g. for debugging):</p>\n\n<pre><code>auto testVar = std::make_tuple(1, 1.0, "abc");\ndecltype(testVar)::foo= 1;\n</code></pre>\n\n<p>Returns:</p>\n\n<pre><code>Compilation finished with errors:\nsource.cpp: In function \'int main()\':\nsource.cpp:5:19: error: \'foo\' is not a member of \'std::tuple<int, double, const char*>\'\n</code></pre>\n'}, {'answer_id': 14633413, 'author': 'ipapadop', 'author_id': 487362, 'author_profile': 'https://Stackoverflow.com/users/487362', 'pm_score': 5, 'selected': False, 'text': '<p>As mentioned, <code>typeid().name()</code> may return a mangled name. In GCC (and some other compilers) you can work around it with the following code:</p>\n\n<pre><code>#include <cxxabi.h>\n#include <iostream>\n#include <typeinfo>\n#include <cstdlib>\n\nnamespace some_namespace { namespace another_namespace {\n\n class my_class { };\n\n} }\n\nint main() {\n typedef some_namespace::another_namespace::my_class my_type;\n // mangled\n std::cout << typeid(my_type).name() << std::endl;\n\n // unmangled\n int status = 0;\n char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &status);\n\n switch (status) {\n case -1: {\n // could not allocate memory\n std::cout << "Could not allocate memory" << std::endl;\n return -1;\n } break;\n case -2: {\n // invalid name under the C++ ABI mangling rules\n std::cout << "Invalid name" << std::endl;\n return -1;\n } break;\n case -3: {\n // invalid argument\n std::cout << "Invalid argument to demangle()" << std::endl;\n return -1;\n } break;\n }\n std::cout << demangled << std::endl;\n\n free(demangled);\n\n return 0;\n</code></pre>\n\n<p>}</p>\n'}, {'answer_id': 20170989, 'author': 'Howard Hinnant', 'author_id': 576911, 'author_profile': 'https://Stackoverflow.com/users/576911', 'pm_score': 11, 'selected': True, 'text': '<p>C++11 update to a very old question: Print variable type in C++.</p>\n<p>The accepted (and good) answer is to use <code>typeid(a).name()</code>, where <code>a</code> is a variable name.</p>\n<p>Now in C++11 we have <code>decltype(x)</code>, which can turn an expression into a type. And <code>decltype()</code> comes with its own set of very interesting rules. For example <code>decltype(a)</code> and <code>decltype((a))</code> will generally be different types (and for good and understandable reasons once those reasons are exposed).</p>\n<p>Will our trusty <code>typeid(a).name()</code> help us explore this brave new world?</p>\n<p>No.</p>\n<p>But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to <code>typeid(a).name()</code>. And this new tool is actually built on top of <code>typeid(a).name()</code>.</p>\n<p><strong>The fundamental issue:</strong></p>\n<pre><code>typeid(a).name()\n</code></pre>\n<p>throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example:</p>\n<pre><code>const int ci = 0;\nstd::cout << typeid(ci).name() << \'\\n\';\n</code></pre>\n<p>For me outputs:</p>\n<pre><code>i\n</code></pre>\n<p>and I\'m guessing on MSVC outputs:</p>\n<pre><code>int\n</code></pre>\n<p>I.e. the <code>const</code> is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior.</p>\n<p>What I\'m recommending below is:</p>\n<pre><code>template <typename T> std::string type_name();\n</code></pre>\n<p>which would be used like this:</p>\n<pre><code>const int ci = 0;\nstd::cout << type_name<decltype(ci)>() << \'\\n\';\n</code></pre>\n<p>and for me outputs:</p>\n<pre><code>int const\n</code></pre>\n<p><code><disclaimer></code> I have not tested this on MSVC. <code></disclaimer></code> But I welcome feedback from those who do.</p>\n<p><strong>The C++11 Solution</strong></p>\n<p>I am using <code>__cxa_demangle</code> for non-MSVC platforms as recommend by <a href="https://stackoverflow.com/users/487362/ipapadop">ipapadop</a> in his answer to demangle types. But on MSVC I\'m trusting <code>typeid</code> to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type.</p>\n<pre><code>#include <type_traits>\n#include <typeinfo>\n#ifndef _MSC_VER\n# include <cxxabi.h>\n#endif\n#include <memory>\n#include <string>\n#include <cstdlib>\n\ntemplate <class T>\nstd::string\ntype_name()\n{\n typedef typename std::remove_reference<T>::type TR;\n std::unique_ptr<char, void(*)(void*)> own\n (\n#ifndef _MSC_VER\n abi::__cxa_demangle(typeid(TR).name(), nullptr,\n nullptr, nullptr),\n#else\n nullptr,\n#endif\n std::free\n );\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n if (std::is_const<TR>::value)\n r += " const";\n if (std::is_volatile<TR>::value)\n r += " volatile";\n if (std::is_lvalue_reference<T>::value)\n r += "&";\n else if (std::is_rvalue_reference<T>::value)\n r += "&&";\n return r;\n}\n</code></pre>\n<p><strong>The Results</strong></p>\n<p>With this solution I can do this:</p>\n<pre><code>int& foo_lref();\nint&& foo_rref();\nint foo_value();\n\nint\nmain()\n{\n int i = 0;\n const int ci = 0;\n std::cout << "decltype(i) is " << type_name<decltype(i)>() << \'\\n\';\n std::cout << "decltype((i)) is " << type_name<decltype((i))>() << \'\\n\';\n std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << \'\\n\';\n std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << \'\\n\';\n std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << \'\\n\';\n std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << \'\\n\';\n std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << \'\\n\';\n std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << \'\\n\';\n std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << \'\\n\';\n std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << \'\\n\';\n}\n</code></pre>\n<p>and the output is:</p>\n<pre><code>decltype(i) is int\ndecltype((i)) is int&\ndecltype(ci) is int const\ndecltype((ci)) is int const&\ndecltype(static_cast<int&>(i)) is int&\ndecltype(static_cast<int&&>(i)) is int&&\ndecltype(static_cast<int>(i)) is int\ndecltype(foo_lref()) is int&\ndecltype(foo_rref()) is int&&\ndecltype(foo_value()) is int\n</code></pre>\n<p>Note (for example) the difference between <code>decltype(i)</code> and <code>decltype((i))</code>. The former is the type of the <em>declaration</em> of <code>i</code>. The latter is the "type" of the <em>expression</em> <code>i</code>. (expressions never have reference type, but as a convention <code>decltype</code> represents lvalue expressions with lvalue references).</p>\n<p>Thus this tool is an excellent vehicle just to learn about <code>decltype</code>, in addition to exploring and debugging your own code.</p>\n<p>In contrast, if I were to build this just on <code>typeid(a).name()</code>, without adding back lost cv-qualifiers or references, the output would be:</p>\n<pre><code>decltype(i) is int\ndecltype((i)) is int\ndecltype(ci) is int\ndecltype((ci)) is int\ndecltype(static_cast<int&>(i)) is int\ndecltype(static_cast<int&&>(i)) is int\ndecltype(static_cast<int>(i)) is int\ndecltype(foo_lref()) is int\ndecltype(foo_rref()) is int\ndecltype(foo_value()) is int\n</code></pre>\n<p>I.e. Every reference and cv-qualifier is stripped off.</p>\n<p><strong>C++14 Update</strong></p>\n<p>Just when you think you\'ve got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-)</p>\n<p><a href="https://stackoverflow.com/a/35943472/576911">This answer</a> from <a href="https://stackoverflow.com/users/2969631/jamboree">Jamboree</a> shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons:</p>\n<ol>\n<li>It\'s at compile time!</li>\n<li>You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas).</li>\n</ol>\n<p><a href="https://stackoverflow.com/users/2969631/jamboree">Jamboree\'s</a> <a href="https://stackoverflow.com/a/35943472/576911">answer</a> doesn\'t quite lay everything out for VS, and I\'m tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened.</p>\n<pre><code>#include <cstddef>\n#include <stdexcept>\n#include <cstring>\n#include <ostream>\n\n#ifndef _MSC_VER\n# if __cplusplus < 201103\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif __cplusplus < 201402\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#else // _MSC_VER\n# if _MSC_VER < 1900\n# define CONSTEXPR11_TN\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN\n# elif _MSC_VER < 2000\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN\n# define NOEXCEPT_TN noexcept\n# else\n# define CONSTEXPR11_TN constexpr\n# define CONSTEXPR14_TN constexpr\n# define NOEXCEPT_TN noexcept\n# endif\n#endif // _MSC_VER\n\nclass static_string\n{\n const char* const p_;\n const std::size_t sz_;\n\npublic:\n typedef const char* const_iterator;\n\n template <std::size_t N>\n CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN\n : p_(a)\n , sz_(N-1)\n {}\n\n CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN\n : p_(p)\n , sz_(N)\n {}\n\n CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}\n\n CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}\n CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;}\n\n CONSTEXPR11_TN char operator[](std::size_t n) const\n {\n return n < sz_ ? p_[n] : throw std::out_of_range("static_string");\n }\n};\n\ninline\nstd::ostream&\noperator<<(std::ostream& os, static_string const& s)\n{\n return os.write(s.data(), s.size());\n}\n\ntemplate <class T>\nCONSTEXPR14_TN\nstatic_string\ntype_name()\n{\n#ifdef __clang__\n static_string p = __PRETTY_FUNCTION__;\n return static_string(p.data() + 31, p.size() - 31 - 1);\n#elif defined(__GNUC__)\n static_string p = __PRETTY_FUNCTION__;\n# if __cplusplus < 201402\n return static_string(p.data() + 36, p.size() - 36 - 1);\n# else\n return static_string(p.data() + 46, p.size() - 46 - 1);\n# endif\n#elif defined(_MSC_VER)\n static_string p = __FUNCSIG__;\n return static_string(p.data() + 38, p.size() - 38 - 7);\n#endif\n}\n</code></pre>\n<p>This code will auto-backoff on the <code>constexpr</code> if you\'re still stuck in ancient C++11. And if you\'re painting on the cave wall with C++98/03, the <code>noexcept</code> is sacrificed as well.</p>\n<p><strong>C++17 Update</strong></p>\n<p>In the comments below <a href="https://stackoverflow.com/users/3624760/lyberta">Lyberta</a> points out that the new <code>std::string_view</code> can replace <code>static_string</code>:</p>\n<pre><code>template <class T>\nconstexpr\nstd::string_view\ntype_name()\n{\n using namespace std;\n#ifdef __clang__\n string_view p = __PRETTY_FUNCTION__;\n return string_view(p.data() + 34, p.size() - 34 - 1);\n#elif defined(__GNUC__)\n string_view p = __PRETTY_FUNCTION__;\n# if __cplusplus < 201402\n return string_view(p.data() + 36, p.size() - 36 - 1);\n# else\n return string_view(p.data() + 49, p.find(\';\', 49) - 49);\n# endif\n#elif defined(_MSC_VER)\n string_view p = __FUNCSIG__;\n return string_view(p.data() + 84, p.size() - 84 - 7);\n#endif\n}\n</code></pre>\n<p>I\'ve updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below.</p>\n<h2>Update:</h2>\n<p>Be sure to check out <a href="https://stackoverflow.com/a/56766138/576911">this</a> rewrite or <a href="https://stackoverflow.com/a/64490578/576911">this</a> rewrite below which eliminate the unreadable magic numbers in my latest formulation.</p>\n'}, {'answer_id': 29040615, 'author': 'Jahid', 'author_id': 3744681, 'author_profile': 'https://Stackoverflow.com/users/3744681', 'pm_score': 3, 'selected': False, 'text': '<p>I like Nick\'s method, A complete form might be this (for all basic data types):</p>\n\n<pre><code>template <typename T> const char* typeof(T&) { return "unknown"; } // default\ntemplate<> const char* typeof(int&) { return "int"; }\ntemplate<> const char* typeof(short&) { return "short"; }\ntemplate<> const char* typeof(long&) { return "long"; }\ntemplate<> const char* typeof(unsigned&) { return "unsigned"; }\ntemplate<> const char* typeof(unsigned short&) { return "unsigned short"; }\ntemplate<> const char* typeof(unsigned long&) { return "unsigned long"; }\ntemplate<> const char* typeof(float&) { return "float"; }\ntemplate<> const char* typeof(double&) { return "double"; }\ntemplate<> const char* typeof(long double&) { return "long double"; }\ntemplate<> const char* typeof(std::string&) { return "String"; }\ntemplate<> const char* typeof(char&) { return "char"; }\ntemplate<> const char* typeof(signed char&) { return "signed char"; }\ntemplate<> const char* typeof(unsigned char&) { return "unsigned char"; }\ntemplate<> const char* typeof(char*&) { return "char*"; }\ntemplate<> const char* typeof(signed char*&) { return "signed char*"; }\ntemplate<> const char* typeof(unsigned char*&) { return "unsigned char*"; }\n</code></pre>\n'}, {'answer_id': 29043884, 'author': 'Jahid', 'author_id': 3744681, 'author_profile': 'https://Stackoverflow.com/users/3744681', 'pm_score': 3, 'selected': False, 'text': '<p>A more generic solution without function overloading than my previous one:</p>\n\n<pre><code>template<typename T>\nstd::string TypeOf(T){\n std::string Type="unknown";\n if(std::is_same<T,int>::value) Type="int";\n if(std::is_same<T,std::string>::value) Type="String";\n if(std::is_same<T,MyClass>::value) Type="MyClass";\n\n return Type;}\n</code></pre>\n\n<p>Here MyClass is user defined class. More conditions can be added here as well.</p>\n\n<p>Example:</p>\n\n<pre><code>#include <iostream>\n\n\n\nclass MyClass{};\n\n\ntemplate<typename T>\nstd::string TypeOf(T){\n std::string Type="unknown";\n if(std::is_same<T,int>::value) Type="int";\n if(std::is_same<T,std::string>::value) Type="String";\n if(std::is_same<T,MyClass>::value) Type="MyClass";\n return Type;}\n\n\nint main(){;\n int a=0;\n std::string s="";\n MyClass my;\n std::cout<<TypeOf(a)<<std::endl;\n std::cout<<TypeOf(s)<<std::endl;\n std::cout<<TypeOf(my)<<std::endl;\n\n return 0;}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>int\nString\nMyClass\n</code></pre>\n'}, {'answer_id': 35703301, 'author': 'Alan', 'author_id': 1691719, 'author_profile': 'https://Stackoverflow.com/users/1691719', 'pm_score': 3, 'selected': False, 'text': '<p>You may also use c++filt with option -t (type) to demangle the type name:</p>\n\n<pre><code>#include <iostream>\n#include <typeinfo>\n#include <string>\n\nusing namespace std;\n\nint main() {\n auto x = 1;\n string my_type = typeid(x).name();\n system(("echo " + my_type + " | c++filt -t").c_str());\n return 0;\n}\n</code></pre>\n\n<p>Tested on linux only.</p>\n'}, {'answer_id': 39937286, 'author': 'abodeofcode', 'author_id': 6942726, 'author_profile': 'https://Stackoverflow.com/users/6942726', 'pm_score': 4, 'selected': False, 'text': '<p>In C++11, we have decltype. There is no way in standard c++ to display exact type of variable declared using decltype. We can use boost typeindex i.e <code>type_id_with_cvr</code> (cvr stands for const, volatile, reference) to print type like below.</p>\n\n<pre><code>#include <iostream>\n#include <boost/type_index.hpp>\n\nusing namespace std;\nusing boost::typeindex::type_id_with_cvr;\n\nint main() {\n int i = 0;\n const int ci = 0;\n cout << "decltype(i) is " << type_id_with_cvr<decltype(i)>().pretty_name() << \'\\n\';\n cout << "decltype((i)) is " << type_id_with_cvr<decltype((i))>().pretty_name() << \'\\n\';\n cout << "decltype(ci) is " << type_id_with_cvr<decltype(ci)>().pretty_name() << \'\\n\';\n cout << "decltype((ci)) is " << type_id_with_cvr<decltype((ci))>().pretty_name() << \'\\n\';\n cout << "decltype(std::move(i)) is " << type_id_with_cvr<decltype(std::move(i))>().pretty_name() << \'\\n\';\n cout << "decltype(std::static_cast<int&&>(i)) is " << type_id_with_cvr<decltype(static_cast<int&&>(i))>().pretty_name() << \'\\n\';\n return 0;\n}\n</code></pre>\n'}, {'answer_id': 45457278, 'author': 'Graywolf', 'author_id': 7138477, 'author_profile': 'https://Stackoverflow.com/users/7138477', 'pm_score': 2, 'selected': False, 'text': '<pre><code>#include <iostream>\n#include <typeinfo>\nusing namespace std;\n#define show_type_name(_t) \\\n system(("echo " + string(typeid(_t).name()) + " | c++filt -t").c_str())\n\nint main() {\n auto a = {"one", "two", "three"};\n cout << "Type of a: " << typeid(a).name() << endl;\n cout << "Real type of a:\\n";\n show_type_name(a);\n for (auto s : a) {\n if (string(s) == "one") {\n cout << "Type of s: " << typeid(s).name() << endl;\n cout << "Real type of s:\\n";\n show_type_name(s);\n }\n cout << s << endl;\n }\n\n int i = 5;\n cout << "Type of i: " << typeid(i).name() << endl;\n cout << "Real type of i:\\n";\n show_type_name(i);\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Type of a: St16initializer_listIPKcE\nReal type of a:\nstd::initializer_list<char const*>\nType of s: PKc\nReal type of s:\nchar const*\none\ntwo\nthree\nType of i: i\nReal type of i:\nint\n</code></pre>\n'}, {'answer_id': 45743053, 'author': 'HolyBlackCat', 'author_id': 2752075, 'author_profile': 'https://Stackoverflow.com/users/2752075', 'pm_score': 3, 'selected': False, 'text': "<p>As I challenge I decided to test how far can one go with platform-independent (hopefully) template trickery.</p>\n\n<p>The names are assembled completely at compilation time. (Which means <code>typeid(T).name()</code> couldn't be used, thus you have to explicitly provide names for non-compound types. Otherwise placeholders will be displayed instead.)</p>\n\n<p>Example usage:</p>\n\n<pre><code>TYPE_NAME(int)\nTYPE_NAME(void)\n// You probably should list all primitive types here.\n\nTYPE_NAME(std::string)\n\nint main()\n{\n // A simple case\n std::cout << type_name<void(*)(int)> << '\\n';\n // -> `void (*)(int)`\n\n // Ugly mess case\n // Note that compiler removes cv-qualifiers from parameters and replaces arrays with pointers.\n std::cout << type_name<void (std::string::*(int[3],const int, void (*)(std::string)))(volatile int*const*)> << '\\n';\n // -> `void (std::string::*(int *,int,void (*)(std::string)))(volatile int *const*)`\n\n // A case with undefined types\n // If a type wasn't TYPE_NAME'd, it's replaced by a placeholder, one of `class?`, `union?`, `enum?` or `??`.\n std::cout << type_name<std::ostream (*)(int, short)> << '\\n';\n // -> `class? (*)(int,??)`\n // With appropriate TYPE_NAME's, the output would be `std::string (*)(int,short)`.\n}\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>#include <type_traits>\n#include <utility>\n\nstatic constexpr std::size_t max_str_lit_len = 256;\n\ntemplate <std::size_t I, std::size_t N> constexpr char sl_at(const char (&str)[N])\n{\n if constexpr(I < N)\n return str[I];\n else\n return '\\0';\n}\n\nconstexpr std::size_t sl_len(const char *str)\n{\n for (std::size_t i = 0; i < max_str_lit_len; i++)\n if (str[i] == '\\0')\n return i;\n return 0;\n}\n\ntemplate <char ...C> struct str_lit\n{\n static constexpr char value[] {C..., '\\0'};\n static constexpr int size = sl_len(value);\n\n template <typename F, typename ...P> struct concat_impl {using type = typename concat_impl<F>::type::template concat_impl<P...>::type;};\n template <char ...CC> struct concat_impl<str_lit<CC...>> {using type = str_lit<C..., CC...>;};\n template <typename ...P> using concat = typename concat_impl<P...>::type;\n};\n\ntemplate <typename, const char *> struct trim_str_lit_impl;\ntemplate <std::size_t ...I, const char *S> struct trim_str_lit_impl<std::index_sequence<I...>, S>\n{\n using type = str_lit<S[I]...>;\n};\ntemplate <std::size_t N, const char *S> using trim_str_lit = typename trim_str_lit_impl<std::make_index_sequence<N>, S>::type;\n\n#define STR_LIT(str) ::trim_str_lit<::sl_len(str), ::str_lit<STR_TO_VA(str)>::value>\n#define STR_TO_VA(str) STR_TO_VA_16(str,0),STR_TO_VA_16(str,16),STR_TO_VA_16(str,32),STR_TO_VA_16(str,48)\n#define STR_TO_VA_16(str,off) STR_TO_VA_4(str,0+off),STR_TO_VA_4(str,4+off),STR_TO_VA_4(str,8+off),STR_TO_VA_4(str,12+off)\n#define STR_TO_VA_4(str,off) ::sl_at<off+0>(str),::sl_at<off+1>(str),::sl_at<off+2>(str),::sl_at<off+3>(str)\n\ntemplate <char ...C> constexpr str_lit<C...> make_str_lit(str_lit<C...>) {return {};}\ntemplate <std::size_t N> constexpr auto make_str_lit(const char (&str)[N])\n{\n return trim_str_lit<sl_len((const char (&)[N])str), str>{};\n}\n\ntemplate <std::size_t A, std::size_t B> struct cexpr_pow {static constexpr std::size_t value = A * cexpr_pow<A,B-1>::value;};\ntemplate <std::size_t A> struct cexpr_pow<A,0> {static constexpr std::size_t value = 1;};\ntemplate <std::size_t N, std::size_t X, typename = std::make_index_sequence<X>> struct num_to_str_lit_impl;\ntemplate <std::size_t N, std::size_t X, std::size_t ...Seq> struct num_to_str_lit_impl<N, X, std::index_sequence<Seq...>>\n{\n static constexpr auto func()\n {\n if constexpr (N >= cexpr_pow<10,X>::value)\n return num_to_str_lit_impl<N, X+1>::func();\n else\n return str_lit<(N / cexpr_pow<10,X-1-Seq>::value % 10 + '0')...>{};\n }\n};\ntemplate <std::size_t N> using num_to_str_lit = decltype(num_to_str_lit_impl<N,1>::func());\n\n\nusing spa = str_lit<' '>;\nusing lpa = str_lit<'('>;\nusing rpa = str_lit<')'>;\nusing lbr = str_lit<'['>;\nusing rbr = str_lit<']'>;\nusing ast = str_lit<'*'>;\nusing amp = str_lit<'&'>;\nusing con = str_lit<'c','o','n','s','t'>;\nusing vol = str_lit<'v','o','l','a','t','i','l','e'>;\nusing con_vol = con::concat<spa, vol>;\nusing nsp = str_lit<':',':'>;\nusing com = str_lit<','>;\nusing unk = str_lit<'?','?'>;\n\nusing c_cla = str_lit<'c','l','a','s','s','?'>;\nusing c_uni = str_lit<'u','n','i','o','n','?'>;\nusing c_enu = str_lit<'e','n','u','m','?'>;\n\ntemplate <typename T> inline constexpr bool ptr_or_ref = std::is_pointer_v<T> || std::is_reference_v<T> || std::is_member_pointer_v<T>;\ntemplate <typename T> inline constexpr bool func_or_arr = std::is_function_v<T> || std::is_array_v<T>;\n\ntemplate <typename T> struct primitive_type_name {using value = unk;};\n\ntemplate <typename T, typename = std::enable_if_t<std::is_class_v<T>>> using enable_if_class = T;\ntemplate <typename T, typename = std::enable_if_t<std::is_union_v<T>>> using enable_if_union = T;\ntemplate <typename T, typename = std::enable_if_t<std::is_enum_v <T>>> using enable_if_enum = T;\ntemplate <typename T> struct primitive_type_name<enable_if_class<T>> {using value = c_cla;};\ntemplate <typename T> struct primitive_type_name<enable_if_union<T>> {using value = c_uni;};\ntemplate <typename T> struct primitive_type_name<enable_if_enum <T>> {using value = c_enu;};\n\ntemplate <typename T> struct type_name_impl;\n\ntemplate <typename T> using type_name_lit = std::conditional_t<std::is_same_v<typename primitive_type_name<T>::value::template concat<spa>,\n typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>,\n typename primitive_type_name<T>::value,\n typename type_name_impl<T>::l::template concat<typename type_name_impl<T>::r>>;\ntemplate <typename T> inline constexpr const char *type_name = type_name_lit<T>::value;\n\ntemplate <typename T, typename = std::enable_if_t<!std::is_const_v<T> && !std::is_volatile_v<T>>> using enable_if_no_cv = T;\n\ntemplate <typename T> struct type_name_impl\n{\n using l = typename primitive_type_name<T>::value::template concat<spa>;\n using r = str_lit<>;\n};\ntemplate <typename T> struct type_name_impl<const T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<con>,\n con::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<volatile T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<vol>,\n vol::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<const volatile T>\n{\n using new_T_l = std::conditional_t<type_name_impl<T>::l::size && !ptr_or_ref<T>,\n spa::concat<typename type_name_impl<T>::l>,\n typename type_name_impl<T>::l>;\n using l = std::conditional_t<ptr_or_ref<T>,\n typename new_T_l::template concat<con_vol>,\n con_vol::concat<new_T_l>>;\n using r = typename type_name_impl<T>::r;\n};\ntemplate <typename T> struct type_name_impl<T *>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, ast>,\n typename type_name_impl<T>::l::template concat< ast>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T &>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, amp>,\n typename type_name_impl<T>::l::template concat< amp>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T &&>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, amp, amp>,\n typename type_name_impl<T>::l::template concat< amp, amp>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T, typename C> struct type_name_impl<T C::*>\n{\n using l = std::conditional_t<func_or_arr<T>,\n typename type_name_impl<T>::l::template concat<lpa, type_name_lit<C>, nsp, ast>,\n typename type_name_impl<T>::l::template concat< type_name_lit<C>, nsp, ast>>;\n using r = std::conditional_t<func_or_arr<T>,\n rpa::concat<typename type_name_impl<T>::r>,\n typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<enable_if_no_cv<T[]>>\n{\n using l = typename type_name_impl<T>::l;\n using r = lbr::concat<rbr, typename type_name_impl<T>::r>;\n};\ntemplate <typename T, std::size_t N> struct type_name_impl<enable_if_no_cv<T[N]>>\n{\n using l = typename type_name_impl<T>::l;\n using r = lbr::concat<num_to_str_lit<N>, rbr, typename type_name_impl<T>::r>;\n};\ntemplate <typename T> struct type_name_impl<T()>\n{\n using l = typename type_name_impl<T>::l;\n using r = lpa::concat<rpa, typename type_name_impl<T>::r>;\n};\ntemplate <typename T, typename P1, typename ...P> struct type_name_impl<T(P1, P...)>\n{\n using l = typename type_name_impl<T>::l;\n using r = lpa::concat<type_name_lit<P1>,\n com::concat<type_name_lit<P>>..., rpa, typename type_name_impl<T>::r>;\n};\n\n#define TYPE_NAME(t) template <> struct primitive_type_name<t> {using value = STR_LIT(#t);};\n</code></pre>\n"}, {'answer_id': 56453627, 'author': 'Milo Lu', 'author_id': 2846062, 'author_profile': 'https://Stackoverflow.com/users/2846062', 'pm_score': 3, 'selected': False, 'text': "<p>As explained by Scott Meyers in <em>Effective Modern C++</em>,</p>\n<blockquote>\n<p>Calls to <code>std::type_info::name</code> are not guaranteed to return anything sensible.</p>\n</blockquote>\n<p>The best solution is to let the compiler generate an error message during the type deduction, for example:</p>\n<pre><code>template<typename T>\nclass TD;\n\nint main(){\n const int theAnswer = 32;\n auto x = theAnswer;\n auto y = &theAnswer;\n TD<decltype(x)> xType;\n TD<decltype(y)> yType;\n return 0;\n}\n</code></pre>\n<p>The result will be something like this, depending on the compilers:</p>\n<pre><code>test4.cpp:10:21: error: aggregate ‘TD<int> xType’ has incomplete type and cannot be defined TD<decltype(x)> xType;\n\ntest4.cpp:11:21: error: aggregate ‘TD<const int *> yType’ has incomplete type and cannot be defined TD<decltype(y)> yType;\n</code></pre>\n<p>Hence, we get to know that <code>x</code>'s type is <code>int</code> and <code>y</code>'s type is <code>const int*</code></p>\n"}, {'answer_id': 56766138, 'author': '康桓瑋', 'author_id': 11638718, 'author_profile': 'https://Stackoverflow.com/users/11638718', 'pm_score': 7, 'selected': False, 'text': '<p>According to <a href="https://stackoverflow.com/a/20170989/11638718">Howard</a>\'s solution, if you don\'t like the magic number, I think this is a good way to represent and it looks intuitive:</p>\n<pre><code>#include <string_view>\n\ntemplate <typename T>\nconstexpr auto type_name() {\n std::string_view name, prefix, suffix;\n#ifdef __clang__\n name = __PRETTY_FUNCTION__;\n prefix = "auto type_name() [T = ";\n suffix = "]";\n#elif defined(__GNUC__)\n name = __PRETTY_FUNCTION__;\n prefix = "constexpr auto type_name() [with T = ";\n suffix = "]";\n#elif defined(_MSC_VER)\n name = __FUNCSIG__;\n prefix = "auto __cdecl type_name<";\n suffix = ">(void)";\n#endif\n name.remove_prefix(prefix.size());\n name.remove_suffix(suffix.size());\n return name;\n}\n</code></pre>\n<p><a href="https://godbolt.org/z/Mr1ercr49" rel="noreferrer">Demo.</a></p>\n'}, {'answer_id': 58331141, 'author': 'Val', 'author_id': 7163942, 'author_profile': 'https://Stackoverflow.com/users/7163942', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/20170989">Howard Hinnant</a> used magic numbers to extract type name. <a href="https://stackoverflow.com/a/56766138">康桓瑋</a> suggested string prefix and suffix. But prefix/suffix keep changing.\nWith “probe_type” type_name automatically calculates prefix and suffix sizes for “probe_type” to extract type name:</p>\n<pre><code>#include <string_view>\nusing namespace std;\n\nnamespace typeName {\n template <typename T>\n constexpr string_view wrapped_type_name () {\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#endif\n }\n\n class probe_type;\n constexpr string_view probe_type_name ("typeName::probe_type");\n constexpr string_view probe_type_name_elaborated ("class typeName::probe_type");\n constexpr string_view probe_type_name_used (wrapped_type_name<probe_type> ().find (probe_type_name_elaborated) != -1 ? probe_type_name_elaborated : probe_type_name);\n\n constexpr size_t prefix_size () {\n return wrapped_type_name<probe_type> ().find (probe_type_name_used);\n }\n\n constexpr size_t suffix_size () {\n return wrapped_type_name<probe_type> ().length () - prefix_size () - probe_type_name_used.length ();\n }\n\n template <typename T>\n string_view type_name () {\n constexpr auto type_name = wrapped_type_name<T> ();\n\n return type_name.substr (prefix_size (), type_name.length () - prefix_size () - suffix_size ());\n }\n}\n\n#include <iostream>\n\nusing typeName::type_name;\nusing typeName::probe_type;\n\nclass test;\n\nint main () {\n cout << type_name<class test> () << endl;\n\n cout << type_name<const int*&> () << endl;\n cout << type_name<unsigned int> () << endl;\n\n const int ic = 42;\n const int* pic = &ic;\n const int*& rpic = pic;\n cout << type_name<decltype(ic)> () << endl;\n cout << type_name<decltype(pic)> () << endl;\n cout << type_name<decltype(rpic)> () << endl;\n\n cout << type_name<probe_type> () << endl;\n}\n</code></pre>\n<p>Output</p>\n<p><a href="https://godbolt.org" rel="noreferrer">gcc 10.2</a>:</p>\n<pre><code>test\nconst int *&\nunsigned int\nconst int\nconst int *\nconst int *&\ntypeName::probe_type\n</code></pre>\n<p><a href="https://godbolt.org" rel="noreferrer">clang 11.0.0</a>:</p>\n<pre><code>test\nconst int *&\nunsigned int\nconst int\nconst int *\nconst int *&\ntypeName::probe_type\n</code></pre>\n<p>VS 2019 version 16.7.6:</p>\n<pre><code>class test\nconst int*&\nunsigned int\nconst int\nconst int*\nconst int*&\nclass typeName::probe_type\n</code></pre>\n'}, {'answer_id': 61344776, 'author': 'Lars Melchior', 'author_id': 2397086, 'author_profile': 'https://Stackoverflow.com/users/2397086', 'pm_score': 2, 'selected': False, 'text': '<p>For anyone still visiting, I\'ve recently had the same issue and decided to write a small library based on answers from this post. It provides constexpr type names and type indices und is is tested on Mac, Windows and Ubuntu.</p>\n\n<p>The library code is here: <a href="https://github.com/TheLartians/StaticTypeInfo" rel="nofollow noreferrer">https://github.com/TheLartians/StaticTypeInfo</a></p>\n'}, {'answer_id': 64490578, 'author': 'einpoklum', 'author_id': 1593077, 'author_profile': 'https://Stackoverflow.com/users/1593077', 'pm_score': 4, 'selected': False, 'text': '<p><sub>Another take on <a href="https://stackoverflow.com/a/56766138">@康桓瑋\'s answer</a> (originally ), making less assumptions about the prefix and suffix specifics, and inspired by <a href="https://stackoverflow.com/a/58331141/1593077">@Val\'s answer</a> - but without polluting the global namespace; without any conditions; and hopefully easier to read.</sub></p>\n<p>The popular compilers provide a macro with the current function\'s signature. Now, functions are templatable; so the signature contains the template arguments. So, the basic approach is: Given a type, be in a function with that type as a template argument.</p>\n<p>Unfortunately, the type name is wrapped in text describing the function, which is different between compilers. For example, with GCC, the signature of <code>template <typename T> int foo()</code> with type <code>double</code> is: <code>int foo() [T = double]</code>.</p>\n<p>So, how do you get rid of the wrapper text? @HowardHinnant\'s solution is the shortest and most "direct": Just use per-compiler magic numbers to remove a prefix and a suffix. But obviously, that\'s very brittle; and nobody likes magic numbers in their code. It turns out, however, that given the macro value for a type with a known name, you can determine what prefix and suffix constitute the wrapping.</p>\n<pre class="lang-c++ prettyprint-override"><code>#include <string_view>\n\ntemplate <typename T> constexpr std::string_view type_name();\n\ntemplate <>\nconstexpr std::string_view type_name<void>()\n{ return "void"; }\n\nnamespace detail {\n\nusing type_name_prober = void;\n\ntemplate <typename T>\nconstexpr std::string_view wrapped_type_name() \n{\n#ifdef __clang__\n return __PRETTY_FUNCTION__;\n#elif defined(__GNUC__)\n return __PRETTY_FUNCTION__;\n#elif defined(_MSC_VER)\n return __FUNCSIG__;\n#else\n#error "Unsupported compiler"\n#endif\n}\n\nconstexpr std::size_t wrapped_type_name_prefix_length() { \n return wrapped_type_name<type_name_prober>().find(type_name<type_name_prober>()); \n}\n\nconstexpr std::size_t wrapped_type_name_suffix_length() { \n return wrapped_type_name<type_name_prober>().length() \n - wrapped_type_name_prefix_length() \n - type_name<type_name_prober>().length();\n}\n\n} // namespace detail\n\ntemplate <typename T>\nconstexpr std::string_view type_name() {\n constexpr auto wrapped_name = detail::wrapped_type_name<T>();\n constexpr auto prefix_length = detail::wrapped_type_name_prefix_length();\n constexpr auto suffix_length = detail::wrapped_type_name_suffix_length();\n constexpr auto type_name_length = wrapped_name.length() - prefix_length - suffix_length;\n return wrapped_name.substr(prefix_length, type_name_length);\n}\n</code></pre>\n<p>See it on <a href="https://godbolt.org/z/3ac5f5" rel="noreferrer"><kbd>GodBolt</kbd></a>. This should be working with MSVC as well.</p>\n'}, {'answer_id': 64717914, 'author': 'CourageousPotato', 'author_id': 11502722, 'author_profile': 'https://Stackoverflow.com/users/11502722', 'pm_score': 1, 'selected': False, 'text': '<p>Copying from this answer: <a href="https://stackoverflow.com/a/56766138/11502722">https://stackoverflow.com/a/56766138/11502722</a></p>\n<p>I was able to get this <em>somewhat</em> working for C++ <code>static_assert()</code>. The wrinkle here is that <code>static_assert()</code> only accepts string literals; <code>constexpr string_view</code> will not work. You will need to accept extra text around the typename, but it works:</p>\n<pre class="lang-cpp prettyprint-override"><code>template<typename T>\nconstexpr void assertIfTestFailed()\n{\n#ifdef __clang__\n static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);\n#elif defined(__GNUC__)\n static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);\n#elif defined(_MSC_VER)\n static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);\n#else\n static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");\n#endif\n }\n}\n</code></pre>\n<p>MSVC Output:</p>\n<pre><code>error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)\n... continued trace of where the erroring code came from ...\n</code></pre>\n'}, {'answer_id': 67562646, 'author': 'Chris Uzdavinis', 'author_id': 8309701, 'author_profile': 'https://Stackoverflow.com/users/8309701', 'pm_score': 2, 'selected': False, 'text': '<p>For something different, here\'s a "To English" conversion of the type, deconstructing every qualifier, extent, argument, and so on, recursively building the string describing the type I think the "deduced this" proposal would help cut down many of the specializations. In any case, this was a fun morning exercise, regardless of excessive bloat. :)</p>\n<pre><code>struct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n\n std::cout << describe<decltype(&X::f)>() << std::endl;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>pointer to member function of class 1X taking (pointer to array[10]\nof pointer to int, pointer to volatile pointer to const unsigned \nlong long), and returning pointer to array[10] of pointer to int\n</code></pre>\n<p>Here\'s the code:\n<a href="https://godbolt.org/z/7jKK4or43" rel="nofollow noreferrer">https://godbolt.org/z/7jKK4or43</a></p>\n<p><strong>Note</strong>: most current version is in my github: <a href="https://github.com/cuzdav/type_to_string" rel="nofollow noreferrer">https://github.com/cuzdav/type_to_string</a></p>\n<pre class="lang-cpp prettyprint-override"><code>// Print types as strings, including functions, member \n\n#include <type_traits>\n#include <typeinfo>\n#include <string>\n#include <utility>\n\nnamespace detail {\n\ntemplate <typename T> struct Describe;\n\ntemplate <typename T, class ClassT> \nstruct Describe<T (ClassT::*)> {\n static std::string describe();\n};\ntemplate <typename RetT, typename... ArgsT> \nstruct Describe<RetT(ArgsT...)> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...)> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...)&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile &> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile &&> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept> {\n static std::string describe();\n};\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstruct Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept> {\n static std::string describe();\n};\n\ntemplate <typename T>\nstd::string describe()\n{\n using namespace std::string_literals;\n auto terminal = [&](char const * desc) {\n return desc + " "s + typeid(T).name();\n };\n if constexpr(std::is_const_v<T>) {\n return "const " + describe<std::remove_const_t<T>>();\n }\n else if constexpr(std::is_volatile_v<T>) {\n return "volatile " + describe<std::remove_volatile_t<T>>();\n }\n else if constexpr (std::is_same_v<bool, T>) {\n return "bool";\n }\n else if constexpr(std::is_same_v<char, T>) {\n return "char";\n }\n else if constexpr(std::is_same_v<signed char, T>) {\n return "signed char";\n }\n else if constexpr(std::is_same_v<unsigned char, T>) {\n return "unsigned char";\n }\n else if constexpr(std::is_unsigned_v<T>) {\n return "unsigned " + describe<std::make_signed_t<T>>();\n }\n else if constexpr(std::is_void_v<T>) {\n return "void";\n }\n else if constexpr(std::is_integral_v<T>) {\n if constexpr(std::is_same_v<short, T>) \n return "short";\n else if constexpr(std::is_same_v<int, T>) \n return "int";\n else if constexpr(std::is_same_v<long, T>) \n return "long";\n else if constexpr(std::is_same_v<long long, T>) \n return "long long";\n }\n else if constexpr(std::is_same_v<float, T>) {\n return "float";\n }\n else if constexpr(std::is_same_v<double, T>) {\n return "double";\n }\n else if constexpr(std::is_same_v<long double, T>) {\n return "long double";\n }\n else if constexpr(std::is_same_v<std::nullptr_t, T>) { \n return "nullptr_t";\n }\n else if constexpr(std::is_class_v<T>) {\n return terminal("class");\n }\n else if constexpr(std::is_union_v<T>) {\n return terminal("union");\n }\n else if constexpr(std::is_enum_v<T>) {\n std::string result;\n if (!std::is_convertible_v<T, std::underlying_type_t<T>>) {\n result += "scoped ";\n }\n return result + terminal("enum");\n } \n else if constexpr(std::is_pointer_v<T>) {\n return "pointer to " + describe<std::remove_pointer_t<T>>();\n }\n else if constexpr(std::is_lvalue_reference_v<T>) {\n return "lvalue-ref to " + describe<std::remove_reference_t<T>>();\n }\n else if constexpr(std::is_rvalue_reference_v<T>) {\n return "rvalue-ref to " + describe<std::remove_reference_t<T>>();\n }\n else if constexpr(std::is_bounded_array_v<T>) {\n return "array[" + std::to_string(std::extent_v<T>) + "] of " +\n describe<std::remove_extent_t<T>>();\n }\n else if constexpr(std::is_unbounded_array_v<T>) {\n return "array[] of " + describe<std::remove_extent_t<T>>();\n }\n else if constexpr(std::is_function_v<T>) {\n return Describe<T>::describe();\n }\n else if constexpr(std::is_member_object_pointer_v<T>) {\n return Describe<T>::describe();\n }\n else if constexpr(std::is_member_function_pointer_v<T>) {\n return Describe<T>::describe();\n }\n}\n\ntemplate <typename RetT, typename... ArgsT> \nstd::string Describe<RetT(ArgsT...)>::describe() {\n std::string result = "function taking (";\n ((result += detail::describe<ArgsT>(", ")), ...);\n return result + "), returning " + detail::describe<RetT>();\n}\n\ntemplate <typename T, class ClassT> \nstd::string Describe<T (ClassT::*)>::describe() {\n return "pointer to member of " + detail::describe<ClassT>() +\n " of type " + detail::describe<T>();\n}\n\nstruct Comma {\n char const * sep = "";\n std::string operator()(std::string const& str) {\n return std::exchange(sep, ", ") + str;\n }\n};\nenum Qualifiers {NONE=0, CONST=1, VOLATILE=2, NOEXCEPT=4, LVREF=8, RVREF=16};\n\ntemplate <typename RetT, typename ClassT, typename... ArgsT>\nstd::string describeMemberPointer(Qualifiers q) {\n std::string result = "pointer to ";\n if (NONE != (q & CONST)) result += "const ";\n if (NONE != (q & VOLATILE)) result += "volatile ";\n if (NONE != (q & NOEXCEPT)) result += "noexcept ";\n if (NONE != (q & LVREF)) result += "lvalue-ref ";\n if (NONE != (q & RVREF)) result += "rvalue-ref ";\n result += "member function of " + detail::describe<ClassT>() + " taking (";\n Comma comma;\n ((result += comma(detail::describe<ArgsT>())), ...);\n return result + "), and returning " + detail::describe<RetT>();\n}\n\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...)>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(NONE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(CONST | VOLATILE | NOEXCEPT);\n}\n\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile & noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(LVREF | CONST | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...)&&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) volatile && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | VOLATILE | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile &&>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | NOEXCEPT);\n}\ntemplate <typename RetT, class ClassT, typename... ArgsT> \nstd::string Describe<RetT(ClassT::*)(ArgsT...) const volatile && noexcept>::describe() {\n return describeMemberPointer<RetT, ClassT, ArgsT...>(RVREF | CONST | VOLATILE | NOEXCEPT);\n}\n\n} // detail\n\n///////////////////////////////////\n// Main function\n///////////////////////////////////\ntemplate <typename T>\nstd::string describe() {\n return detail::describe<T>();\n}\n\n\n///////////////////////////////////\n// Sample code\n///////////////////////////////////\n#include <iostream>\n\n\nstruct X {\n using T = int *((*)[10]);\n T f(T, const unsigned long long * volatile * );\n};\n\nint main() {\n std::cout << describe<decltype(&X::f)>() << std::endl;\n}\n\n</code></pre>\n'}, {'answer_id': 70839988, 'author': 'Jonas', 'author_id': 2378300, 'author_profile': 'https://Stackoverflow.com/users/2378300', 'pm_score': 1, 'selected': False, 'text': '<p>Building on a number of the previous answers, I made this solution which does not store the result of <code>__PRETTY_FUNCTION__</code> in the binary. It uses a static array to hold the string representation of the type name.</p>\n<p>It requires C++23.</p>\n<pre><code>#include <iostream>\n#include <string_view>\n#include <array>\n\ntemplate <typename T>\nconstexpr auto type_name() {\n auto gen = [] <class R> () constexpr -> std::string_view {\n return __PRETTY_FUNCTION__;\n };\n constexpr std::string_view search_type = "float";\n constexpr auto search_type_string = gen.template operator()<float>();\n constexpr auto prefix = search_type_string.find(search_type);\n constexpr auto suffix = search_type_string.size() - prefix - search_type.size();\n constexpr auto str = gen.template operator()<T>();\n constexpr int size = str.size() - prefix - suffix;\n constexpr auto static arr = [&]<std::size_t... I>(std::index_sequence<I...>) constexpr {\n return std::array<char, size>{str[prefix + I]...};\n } (std::make_index_sequence<size>{});\n\n return std::string_view(arr.data(), size);\n}\n</code></pre>\n'}, {'answer_id': 72650356, 'author': 'Haseeb Mir', 'author_id': 6219626, 'author_profile': 'https://Stackoverflow.com/users/6219626', 'pm_score': 1, 'selected': False, 'text': '<p>C++ Data type resolve in Compile-Time using Template and Runtime using TypeId.</p>\n<p>Compile time solution.</p>\n<pre><code>template <std::size_t...Idxs>\nconstexpr auto substring_as_array(std::string_view str, std::index_sequence<Idxs...>)\n{\n return std::array{str[Idxs]..., \'\\n\'};\n}\n\ntemplate <typename T>\nconstexpr auto type_name_array()\n{\n#if defined(__clang__)\n constexpr auto prefix = std::string_view{"[T = "};\n constexpr auto suffix = std::string_view{"]"};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(__GNUC__)\n constexpr auto prefix = std::string_view{"with T = "};\n constexpr auto suffix = std::string_view{"]"};\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n constexpr auto prefix = std::string_view{"type_name_array<"};\n constexpr auto suffix = std::string_view{">(void)"};\n constexpr auto function = std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n\n constexpr auto start = function.find(prefix) + prefix.size();\n constexpr auto end = function.rfind(suffix);\n\n static_assert(start < end);\n\n constexpr auto name = function.substr(start, (end - start));\n return substring_as_array(name, std::make_index_sequence<name.size()>{});\n}\n\ntemplate <typename T>\nstruct type_name_holder {\n static inline constexpr auto value = type_name_array<T>();\n};\n\ntemplate <typename T>\nconstexpr auto type_name() -> std::string_view\n{\n constexpr auto& value = type_name_holder<T>::value;\n return std::string_view{value.data(), value.size()};\n}\n</code></pre>\n<p>Runtime solution.</p>\n<pre><code>template <typename T>\nvoid PrintDataType(T type)\n{\n auto name = typeid(type).name();\n string cmd_str = "echo \'" + string(name) + "\' | c++filt -t";\n system(cmd_str.c_str());\n}\n</code></pre>\n<p>Main Code</p>\n<pre><code>#include <iostream>\n#include <map>\n#include <string>\n#include <typeinfo>\n#include <string_view>\n#include <array> // std::array\n#include <utility> // std::index_sequence\nusing std::string;\n</code></pre>\n<blockquote>\n<pre><code>int main()\n{\n //Dynamic resolution.\n std::map<int, int> iMap;\n PrintDataType(iMap);\n \n //Compile type resolution.\n std::cout << type_name<std::list<int>>() << std::endl;\n\n return 0;\n}\n</code></pre>\n</blockquote>\n<p><a href="https://gist.github.com/haseeb-heaven/d6093f68d160b92ba1c69ccd9df7ec80" rel="nofollow noreferrer">Code Snippet</a></p>\n'}, {'answer_id': 73058336, 'author': 'CPP_is_no_STANDARD', 'author_id': 18032104, 'author_profile': 'https://Stackoverflow.com/users/18032104', 'pm_score': -1, 'selected': False, 'text': '<p>Consider this code:</p>\n<pre><code>#include <iostream>\n\nint main()\n{\n int a = 2; // Declare type "int"\n std::string b = "Hi"; // Declare type "string"\n long double c = 3438; // Declare type "long double"\n if(typeid(a) == typeid(int))\n {\n std::cout<<"int\\n";\n }\n\n if(typeid(b) == typeid(std::string))\n {\n std::cout<<"string\\n";\n }\n \n if(typeid(c) == typeid(long double))\n {\n std::cout<<"long double";\n }\n return 0;\n}\n</code></pre>\n<p>I believe you want the whole word (rather than only printing the short form of <code>int</code> (which is <code>i</code>), you want <code>int</code>), that is why I did the <code>if</code>.</p>\n<p>For some of the variables (<code>string</code>,<code>long double</code> etc... which do not print the expected result comparing their short forms), you need to compare the result of applying the <code>typeid</code> operator with the <code>typeid</code> of a specific type.</p>\n<p>From cppreference:</p>\n<blockquote>\n<p>Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.</p>\n</blockquote>\n<hr>\n<p>IMO, Python is better than C++ in this case. Python has built-in <code>type</code> function to directly access the data type of the variable.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6508/'] |
81,874 | <p>Just want to know what is better way to get start developing faccebook app?Any tutorial recommnedation?And which is better to start up -php or rails?</p>
| [{'answer_id': 81900, 'author': 'Oli', 'author_id': 12870, 'author_profile': 'https://Stackoverflow.com/users/12870', 'pm_score': 1, 'selected': False, 'text': '<p>Start with their docs: <a href="http://developer.facebook.com/get_started.php?tab=tutorial" rel="nofollow noreferrer">http://developer.facebook.com/get_started.php?tab=tutorial</a></p>\n\n<p>There are libraries floating around for lots of different languages and frameworks so I say: whatever you\'re happiest with is where you should start.</p>\n'}, {'answer_id': 81907, 'author': 'danio', 'author_id': 12663, 'author_profile': 'https://Stackoverflow.com/users/12663', 'pm_score': 0, 'selected': False, 'text': '<p>Use the <a href="http://developers.facebook.com/get_started.php?tab=tutorial" rel="nofollow noreferrer">Get Started tutorial</a> on <a href="http://developers.facebook.com" rel="nofollow noreferrer">developers.facebook.com</a>. This will suggest you use the sample code button which will give you some PHP to list your friends.\nThen you can start playing with the PHP using the wiki for reference to the FQL and FBML.</p>\n\n<p>PHP will be easier to start with as there are lots of samples in PHP. Rails may have advantages in the long term though.</p>\n'}, {'answer_id': 83021, 'author': 'ceejayoz', 'author_id': 1902010, 'author_profile': 'https://Stackoverflow.com/users/1902010', 'pm_score': 0, 'selected': False, 'text': "<p>Re: Ruby on Rails vs. PHP - whichever you're currently competent in. If neither, whichever you'd <em>like</em> to become competent in. Both can do what you want.</p>\n"}, {'answer_id': 350602, 'author': 'bradheintz', 'author_id': 40093, 'author_profile': 'https://Stackoverflow.com/users/40093', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve seen pretty complete FB wrapper libraries for both PHP and Ruby. Which one you should choose really depends on which language/framework you\'re more comfortable with.</p>\n\n<p>I will say that when I was evaluating Ruby libraries recently, <a href="http://github.com/mmangino/facebooker/tree/master" rel="nofollow noreferrer" title="Facebooker">Facebooker</a> seemed to be superior in terms of active development and <a href="http://apps.facebook.com/facebooker_tutorial/" rel="nofollow noreferrer" title="Facebooker Tutorial">tutorial content</a> on the web. (Be sure to use the Facebooker project on GitHub, not the deprecated one on RubyForge.)</p>\n'}, {'answer_id': 372596, 'author': 'Steve', 'author_id': 39816, 'author_profile': 'https://Stackoverflow.com/users/39816', 'pm_score': 2, 'selected': False, 'text': '<p>Btw, you can also use ASP.NET, in which case here is how to get started:</p>\n\n<p><a href="http://www.stevetrefethen.com/wiki/Facebook%20application%20development%20in%20ASP.NET.ashx" rel="nofollow noreferrer">http://www.stevetrefethen.com/wiki/Facebook%20application%20development%20in%20ASP.NET.ashx</a></p>\n\n<p>The link includes a VS.NET starter kit which makes it very easy to get started quickly.</p>\n'}, {'answer_id': 400290, 'author': 'Tom Wright', 'author_id': 50151, 'author_profile': 'https://Stackoverflow.com/users/50151', 'pm_score': 3, 'selected': False, 'text': "<p>From my experience, there is a much better support focus on PHP than on anything else. That said, there'd be no point learning PHP just to take advantage of the superior support.</p>\n\n<p>Two other general points:</p>\n\n<ol>\n<li>The official support community is really awful. The community has no expert voices and the FB staff only interject when their reputation is at stake. Your best friend is Google and your ability to extrapolate from tutorials.</li>\n<li>The FB style of interaction doesn't really lend itself to an MVC framework. One might still save you time, but I find they get under my feet. If you need convincing on this point, may I refer you to the many cases where JSON responses are required or where FBML needs to be 'set' for the profile. </li>\n</ol>\n\n<p>The Facebook platform isn't a whole lot of fun and your users won't thank you for your work. But it's a massive audience and a very useful learning experience.</p>\n\n<p>Good luck!</p>\n"}, {'answer_id': 3893196, 'author': 'Richard Jordan', 'author_id': 444134, 'author_profile': 'https://Stackoverflow.com/users/444134', 'pm_score': 1, 'selected': False, 'text': '<p>Can I put a shout out for Ruby On Rails with the Koala gem?</p>\n\n<p>I have built a Facebook app in the last two months learning Ruby On Rails from scratch (the last programming of any kind I did was mathematical modeling for my Physics degree project in 1995 in Fortran!).</p>\n\n<p>Ruby On Rails was very simple to pick up and there is a ton of help out there. There are also lots of work already done for you in the way of Ruby Gems. For Facebook I looked through them all and I found Koala the easiest to use, personally.</p>\n\n<p><a href="http://github.com/arsduo/koala/" rel="nofollow">http://github.com/arsduo/koala/</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15476/'] |
81,896 | <p>I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line:</p>
<pre><code>header( 'application/javascript' );
</code></pre>
<p>But on my live server, this line crashes the page and causes a 500 error.</p>
<p>Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.</p>
| [{'answer_id': 81940, 'author': 'Sietse', 'author_id': 6400, 'author_profile': 'https://Stackoverflow.com/users/6400', 'pm_score': 8, 'selected': True, 'text': "<p>The header is incorrect, try this instead:</p>\n\n<pre><code>header('Content-Type: application/javascript');\n</code></pre>\n"}, {'answer_id': 1052918, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>take a look at <strong><a href="http://en.wikipedia.org/wiki/Mime_type" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Mime_type</a></strong></p>\n\n<p>There it says you should use application/javascript instead of text/javascript.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15567/'] |
81,902 | <p>I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it.</p>
| [{'answer_id': 81948, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 0, 'selected': False, 'text': '<p>You will have to call some native code, since IMHO there is no library that does it. Since JNI is cumbersome and hard you might try to use JNA (Java Native Access). <a href="https://jna.dev.java.net/" rel="nofollow noreferrer">https://jna.dev.java.net/</a></p>\n'}, {'answer_id': 81974, 'author': 'arturh', 'author_id': 4186, 'author_profile': 'https://Stackoverflow.com/users/4186', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a command line tool for killing processes like <a href="http://technet.microsoft.com/de-de/sysinternals/bb896683.aspx" rel="nofollow noreferrer">SysInternals PsKill</a> and <a href="http://technet.microsoft.com/de-de/sysinternals/bb896682.aspx" rel="nofollow noreferrer">SysInternals PsList</a>.</p>\n\n<p>You could also use the build-in tasklist.exe and taskkill.exe, but those are only available on Windows XP Professional and later (not in the Home Edition).</p>\n\n<p>Use <a href="http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String)" rel="nofollow noreferrer">java.lang.Runtime.exec</a> to execute the program.</p>\n'}, {'answer_id': 82035, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': True, 'text': '<p>You can use command line windows tools <code>tasklist</code> and <code>taskkill</code> and call them from Java using <code>Runtime.exec()</code>.</p>\n'}, {'answer_id': 2667948, 'author': 'Daniel Lindner', 'author_id': 320402, 'author_profile': 'https://Stackoverflow.com/users/320402', 'pm_score': 2, 'selected': False, 'text': '<p>There is a little API providing the desired functionality:</p>\n\n<p><a href="https://github.com/kohsuke/winp" rel="nofollow noreferrer">https://github.com/kohsuke/winp</a></p>\n\n<p>Windows Process Library</p>\n'}, {'answer_id': 7473589, 'author': '1-14x0r', 'author_id': 334927, 'author_profile': 'https://Stackoverflow.com/users/334927', 'pm_score': 6, 'selected': False, 'text': '<pre><code>private static final String TASKLIST = "tasklist";\nprivate static final String KILL = "taskkill /F /IM ";\n\npublic static boolean isProcessRunning(String serviceName) throws Exception {\n\n Process p = Runtime.getRuntime().exec(TASKLIST);\n BufferedReader reader = new BufferedReader(new InputStreamReader(\n p.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n\n System.out.println(line);\n if (line.contains(serviceName)) {\n return true;\n }\n }\n\n return false;\n\n}\n\npublic static void killProcess(String serviceName) throws Exception {\n\n Runtime.getRuntime().exec(KILL + serviceName);\n\n }\n</code></pre>\n\n<p>EXAMPLE:</p>\n\n<pre><code>public static void main(String args[]) throws Exception {\n String processName = "WINWORD.EXE";\n\n //System.out.print(isProcessRunning(processName));\n\n if (isProcessRunning(processName)) {\n\n killProcess(processName);\n }\n}\n</code></pre>\n'}, {'answer_id': 29413515, 'author': 'Craig', 'author_id': 529256, 'author_profile': 'https://Stackoverflow.com/users/529256', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a groovy way of doing it:</p>\n\n<pre><code>final Process jpsProcess = "cmd /c jps".execute()\nfinal BufferedReader reader = new BufferedReader(new InputStreamReader(jpsProcess.getInputStream()));\ndef jarFileName = "FileName.jar"\ndef processId = null\nreader.eachLine {\n if (it.contains(jarFileName)) {\n def args = it.split(" ")\n if (processId != null) {\n throw new IllegalStateException("Multiple processes found executing ${jarFileName} ids: ${processId} and ${args[0]}")\n } else {\n processId = args[0]\n }\n }\n}\nif (processId != null) {\n def killCommand = "cmd /c TASKKILL /F /PID ${processId}"\n def killProcess = killCommand.execute()\n def stdout = new StringBuilder()\n def stderr = new StringBuilder()\n killProcess.consumeProcessOutput(stdout, stderr)\n println(killCommand)\n def errorOutput = stderr.toString()\n if (!errorOutput.empty) {\n println(errorOutput)\n }\n def stdOutput = stdout.toString()\n if (!stdOutput.empty) {\n println(stdOutput)\n }\n killProcess.waitFor()\n} else {\n System.err.println("Could not find process for jar ${jarFileName}")\n}\n</code></pre>\n'}, {'answer_id': 30458368, 'author': 'Harvendra', 'author_id': 3343726, 'author_profile': 'https://Stackoverflow.com/users/3343726', 'pm_score': 0, 'selected': False, 'text': '<p>small change in answer written by Super kakes</p>\n\n<pre><code>private static final String KILL = "taskkill /IMF ";\n</code></pre>\n\n<p>Changed to ..</p>\n\n<pre><code>private static final String KILL = "taskkill /IM ";\n</code></pre>\n\n<p><code>/IMF</code> option doesnot work .it does not kill notepad..while <code>/IM</code> option actually works</p>\n'}, {'answer_id': 30843674, 'author': 'BullyWiiPlaza', 'author_id': 3764804, 'author_profile': 'https://Stackoverflow.com/users/3764804', 'pm_score': 1, 'selected': False, 'text': '<p>Use the following class to <a href="https://en.wikipedia.org/wiki/Kill_(command)#Microsoft_Windows" rel="nofollow">kill a Windows process</a> (<a href="https://en.wikipedia.org/wiki/Tasklist" rel="nofollow">if it is running</a>). I\'m using the force command line argument <code>/F</code> to make sure that the process specified by the <code>/IM</code> argument will be terminated.</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.InputStreamReader;\n\npublic class WindowsProcess\n{\n private String processName;\n\n public WindowsProcess(String processName)\n {\n this.processName = processName;\n }\n\n public void kill() throws Exception\n {\n if (isRunning())\n {\n getRuntime().exec("taskkill /F /IM " + processName);\n }\n }\n\n private boolean isRunning() throws Exception\n {\n Process listTasksProcess = getRuntime().exec("tasklist");\n BufferedReader tasksListReader = new BufferedReader(\n new InputStreamReader(listTasksProcess.getInputStream()));\n\n String tasksLine;\n\n while ((tasksLine = tasksListReader.readLine()) != null)\n {\n if (tasksLine.contains(processName))\n {\n return true;\n }\n }\n\n return false;\n }\n\n private Runtime getRuntime()\n {\n return Runtime.getRuntime();\n }\n}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11705/'] |
81,904 | <p>I use Virtual PC to create fresh environments for testing my installer. But I must be doing something wrong because a VPC image with Vista or XP inside is taking around 15GB of disk space (that includes VS2005/S2008 installed in them). </p>
<p>To create a new copy for testing I copy and paste the folder that has the .vhd, .vmc and .vsv files inside. After using the new VPC image for testing I then delete that copied folder. This works but it takes a looong time to copy 15GB each time. Is there some faster/more efficent approach?</p>
| [{'answer_id': 81923, 'author': 'Oli', 'author_id': 12870, 'author_profile': 'https://Stackoverflow.com/users/12870', 'pm_score': 1, 'selected': False, 'text': '<p>Doesn\'t VirtualPC have a fake-write/snapshot mode? That way it should not write to your original disk at all unless you say so at the end of the session.</p>\n\n<p>If it doesn\'t, you might seriously want to consider VMWare or VirtualBox as these do have this feature and it\'s REALLY useful for things like this.</p>\n\n<p>Edit: it looks like VPC does have a feature like this called differencing disks. Have a look at this:\n<a href="http://www.andrewconnell.com/blog/articles/UseVirtualPCsDifferencingDisksToYourAdvantage.aspx" rel="nofollow noreferrer">http://www.andrewconnell.com/blog/articles/UseVirtualPCsDifferencingDisksToYourAdvantage.aspx</a></p>\n'}, {'answer_id': 81929, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 4, 'selected': True, 'text': '<p>Use <a href="http://www.petri.co.il/virtual_creating_differencing_disks_with.htm" rel="nofollow noreferrer">differencing/undo disks</a>. This means when you shut down your VPC you\'ll be asked if you want to save changes, simply answer no and you\'ll be back to where you started.</p>\n'}, {'answer_id': 81930, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>VPC has a so called undo disk. you create sg similar like "restore point" and in vpc you can roll back to that version. ideal for testing setups.</p>\n'}, {'answer_id': 81931, 'author': 'John Sibly', 'author_id': 1078, 'author_profile': 'https://Stackoverflow.com/users/1078', 'pm_score': 1, 'selected': False, 'text': '<p>Sound like you need to use differencing virtual hard disks rather than creating a new copy every time.</p>\n\n<p>Instructions <a href="http://dotnet.org.za/matt/pages/2413.aspx" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 81982, 'author': 'kfh', 'author_id': 6597, 'author_profile': 'https://Stackoverflow.com/users/6597', 'pm_score': 0, 'selected': False, 'text': '<p>Also, you mentioned cut & paste, this is not the best way to be copying large amounts of data within windows. At least use xcopy, robocopy is even faster.</p>\n'}, {'answer_id': 129032, 'author': 'seisyll', 'author_id': 21815, 'author_profile': 'https://Stackoverflow.com/users/21815', 'pm_score': 1, 'selected': False, 'text': "<p>Another option: you can use Microsoft's ImageX to store VHDs in WIM format. If you have multiple images you are constantly reusing, this is an incredible way to manage VMs. I have a slew of Windows XP and 2003 images I keep in compressed WIM format.</p>\n\n<p>You can capture the VMs by mounting them in Windows PE and then capturing them to a network drive.</p>\n"}, {'answer_id': 282498, 'author': 'John Baughman', 'author_id': 26923, 'author_profile': 'https://Stackoverflow.com/users/26923', 'pm_score': 0, 'selected': False, 'text': '<p>Also, another option if you are looking to duplicate the images for use on other real machines, you can convert the disk to a dynamically expanding disk which will reduce the size of the vdisk making it easier to copy. This also allows for a more rapid backup, which looks to be part of what your testing does by default. The problem with dynamic disks is they tend to be slightly slower performance wise than fixed-size disks. </p>\n\n<p>However, if all you are doing is using it for testing on the same machine, see the answers above. Differencing is the way to go.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6276/'] |
81,905 | <p>I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:</p>
<pre><code>Start Stop
9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM
9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM
9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM
9/16/2008 12:30:45 PM 12/31/9999 12:00:00 AM
</code></pre>
<p>I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.</p>
<p>How would I do this using Transact-SQL?</p>
| [{'answer_id': 81928, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/ms189794.aspx" rel="nofollow noreferrer">datediff function</a> can display the elapsed minutes. The if statement for the 12/31/9999 check I\'ll leave as an excercise for the reader ;-)</p>\n'}, {'answer_id': 81981, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>--you can play with the datediff using mi for minutes</p>\n\n<p>-- this give you second of each task</p>\n\n<pre><code>select Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable\n</code></pre>\n\n<p>-- sum</p>\n\n<pre><code>Select Sum(duration_in_seconds)\nfrom \n(\nselect Start, \n Stop, \n CASE \n WHEN Stop = '9999-12-31' THEN datediff(ss, start,getdate())\n ELSE datediff(ss, start,stop) \n END duration_in_seconds \n\nfrom mytable)x\n</code></pre>\n"}, {'answer_id': 81983, 'author': 'tsilb', 'author_id': 11112, 'author_profile': 'https://Stackoverflow.com/users/11112', 'pm_score': 0, 'selected': False, 'text': '<p>Datediff becomes more difficult to use as you have more dateparts in your difference (i.e. in your case, looks like minutes and seconds; occasionally hours). Fortunately, in most variations of TSQL, you can simply perform math on the dates. Assuming this is a date field, you can probably just query:</p>\n\n<p>select duration = stop - start</p>\n\n<p>For a practical example, let\'s select the difference between two datetimes without bothering with a table:</p>\n\n<p>select convert(datetime,\'2008-09-17 04:56:45.030\') - convert(datetime,\'2008-09-17 04:53:05.920\')</p>\n\n<p>which returns "1900-01-01 00:03:39.110", indicating there are zero years/months/days; 3 mins, 39.11 seconds between these two datetimes. From there, your code can TimeSpan.Parse this value.</p>\n'}, {'answer_id': 82039, 'author': 'Nerdfest', 'author_id': 7855, 'author_profile': 'https://Stackoverflow.com/users/7855', 'pm_score': 2, 'selected': False, 'text': "<p>Try:</p>\n\n<pre><code>Select Sum(\n DateDiff(\n Minute,\n IsNull((Select Start where Start != '9999.12.31'), GetDate()),\n IsNull((Select End where End != '9999.12.31'), GetDate())\n )\n)\nfrom *tableName*\n</code></pre>\n"}, {'answer_id': 82100, 'author': 'Martynnw', 'author_id': 5466, 'author_profile': 'https://Stackoverflow.com/users/5466', 'pm_score': 1, 'selected': False, 'text': "<p>The following will work for SQL Server, other databases use different functions for date calculation and getting the current time.</p>\n\n<pre><code>Select Case When (Stop <> '31 Dec 9999') Then \n DateDiff(mi, Start, Stop) \n Else \n DateDiff(mi, Start, GetDate()) \n End\nFrom ATable\n</code></pre>\n"}, {'answer_id': 83005, 'author': 'AJ.', 'author_id': 7211, 'author_profile': 'https://Stackoverflow.com/users/7211', 'pm_score': 5, 'selected': True, 'text': "<pre><code>SELECT SUM( CASE WHEN Stop = '31 dec 9999' \n THEN DateDiff(mi, Start, Stop)\n ELSE DateDiff(mi, Start, GetDate())\n END ) AS TotalMinutes \nFROM task\n</code></pre>\n\n<p>However, a better solution would be to make the <code>Stop field nullable, and make it null when the task is still running. That way, you could do this: </p>\n\n<pre>SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes \nFROM task\n</code></pre>\n"}, {'answer_id': 86813, 'author': 'mattruma', 'author_id': 1768, 'author_profile': 'https://Stackoverflow.com/users/1768', 'pm_score': 0, 'selected': False, 'text': '<p>Using help from AJ\'s <a href="https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#83005">answer</a>, BelowNinety\'s <a href="https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#82039">answer</a> and Nerdfest\'s <a href="https://stackoverflow.com/questions/81905/transact-sql-to-sum-up-elapsed-time#82039">answer</a>, I came up with the following:</p>\n\n<pre><code>Select Sum(\n Case When End = \'12/31/9999 12:00:00 AM\' Then\n DateDiff(mi, Start, Getdate()) \n Else \n DateDiff(mi, Start, End) \n End) As ElapsedTime \nFrom Table\n</code></pre>\n\n<p>Thanks for the help!</p>\n'}, {'answer_id': 136859, 'author': 'GilM', 'author_id': 10192, 'author_profile': 'https://Stackoverflow.com/users/10192', 'pm_score': 2, 'selected': False, 'text': "<p>I think this is cleaner:</p>\n\n<pre><code> SELECT SUM(\n DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))\n ) AS ElapsedTime\n FROM Table\n</code></pre>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768/'] |
81,911 | <p>I have a solution with several projects in Visual 2008, let's say SuggestionProcessor (a class library) and Suggestions (a website) with a webhandler GetSuggestions.ashx. I changed a method in SuggestionProcessor which is used in the webhandler. The call in the webhandler has been adjusted to the changed method.</p>
<p>But now when I try to execute the webhandler after a rebuild I get an error that the method I changed is <strong>missing</strong>, displaying the <strong>old method signature</strong>. When I try to rebuild the entire project it seems that the website does not rebuild properly and the code I changed in the webhandler does not seem to be included in the rebuild. I made sure that the website is last in the build order.</p>
<p>What I tried is <strong>remove the dlls that the build process should rebuild</strong> from the bin folder (not the ones referenced from outside the website). When rebuilding I now get a: '<strong>could not load type</strong> Suggestions.global'. Duh, that is what the build process should create. What is going wrong here? </p>
| [{'answer_id': 81926, 'author': 'cjheath', 'author_id': 337110, 'author_profile': 'https://Stackoverflow.com/users/337110', 'pm_score': 0, 'selected': False, 'text': '<p>I would check your web.config file, there may be references there that are causing the error since they are missing.</p>\n'}, {'answer_id': 81969, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 0, 'selected': False, 'text': '<p>Maybe try and right click on your solution and select "Clean solution" and then try and rebuild all.</p>\n\n<p>If that doesn\'t work, check your solutions build configuration and make sure all your projects are getting built</p>\n'}, {'answer_id': 82014, 'author': 'Oded', 'author_id': 1583, 'author_profile': 'https://Stackoverflow.com/users/1583', 'pm_score': 0, 'selected': False, 'text': '<p>Try "Clean Solution", then building SuggestionProcessor, and after that clean and rebuild the web solution.</p>\n'}, {'answer_id': 82668, 'author': 'Drejc', 'author_id': 6482, 'author_profile': 'https://Stackoverflow.com/users/6482', 'pm_score': 0, 'selected': False, 'text': '<p>Visual Studio creates a copy of all your DLLs and sometimes this copies are not refreshed.\nJust execute <strong>iisreset</strong> and delete all folders in: </p>\n\n<blockquote>\n <p>C:\\WINDOWS\\Microsoft.NET\\Framework\\v1.1.4322\\Temporary\n ASP.NET Files\\</p>\n</blockquote>\n\n<p>Of course change windows installation folder and framework folder to your version!</p>\n'}, {'answer_id': 82837, 'author': 'Michiel Borkent', 'author_id': 6264, 'author_profile': 'https://Stackoverflow.com/users/6264', 'pm_score': 2, 'selected': True, 'text': "<p>I solved this one by reverting to a previous state when it still worked. </p>\n\n<p>Thanks for the suggestions, I'm sorry they didn't work in my situation. </p>\n\n<p>Shall I delete this question now that it doesn't really have a clear use for someone else?</p>\n"}, {'answer_id': 82873, 'author': 'kooshmoose', 'author_id': 7436, 'author_profile': 'https://Stackoverflow.com/users/7436', 'pm_score': 0, 'selected': False, 'text': "<p>I don't think so... I've seen similar issues in Visual Studio 2008 working on web projects where the build and rebuild would fail time after time. I knew that my changes shouldn't have affected the build so I just kept cleaning and building each of the individual projects in my solution until finally (and I do mean finally as in, it took up to 10 builds) my web project would build correctly. I have no idea why, but it feels like some sort of caching issue.</p>\n"}, {'answer_id': 2023292, 'author': 'jyoungdev', 'author_id': 120682, 'author_profile': 'https://Stackoverflow.com/users/120682', 'pm_score': 0, 'selected': False, 'text': '<p>From my answer at <a href="https://stackoverflow.com/questions/2005747/could-not-load-type-namespace-global-causing-me-grief/2023267#2023267">"Could not load type [Namespace].Global" causing me grief</a>:</p>\n<blockquote>\n<p>It seems that VS 2008 does not always add the .asax(.cs) files correctly by default.</p>\n</blockquote>\n<p>In this case, refreshing, rebuilding, removing and re-adding, etc. etc. will not fix the problem. Instead:</p>\n<blockquote>\n<p>Check the Build Action of Global.asax.cs. It should be set to Compile.</p>\n<p>In Solution Explorer, Right-click Global.asax.cs and go to Properties. In the Properties pane, set the Build Action (while not debugging).</p>\n</blockquote>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6264/'] |
81,934 | <p>I need a way to easily export and then import data in a MySQL table from a remote server to my home server. I don't have direct access to the server, and no utilities such as phpMyAdmin are installed. I do, however, have the ability to put PHP scripts on the server.</p>
<p>How do I get at the data?</p>
<p><em>I ask this question purely to record my way to do it</em></p>
| [{'answer_id': 81951, 'author': 'Jrgns', 'author_id': 6681, 'author_profile': 'https://Stackoverflow.com/users/6681', 'pm_score': 4, 'selected': False, 'text': '<p>I did it by exporting to CSV, and then importing with whatever utility is available. I quite like the use of the php://output stream.</p>\n\n<pre><code>$result = $db_con->query(\'SELECT * FROM `some_table`\');\n$fp = fopen(\'php://output\', \'w\');\nif ($fp && $result) {\n header(\'Content-Type: text/csv\');\n header(\'Content-Disposition: attachment; filename="export.csv"\');\n while ($row = $result->fetch_array(MYSQLI_NUM)) {\n fputcsv($fp, array_values($row));\n }\n die;\n}\n</code></pre>\n'}, {'answer_id': 82016, 'author': 'Lasar', 'author_id': 9438, 'author_profile': 'https://Stackoverflow.com/users/9438', 'pm_score': 2, 'selected': False, 'text': '<p>If you have FTP/SFTP access you could just go ahead and upload phpMyAdmin yourself.</p>\n\n<p>I\'m using this little package to make automated mysql backups from a server I only have FTP access to:<br>\n<a href="http://www.taw24.de/download/pafiledb.php?PHPSESSID=b48001ea004aacd86f5643a72feb2829&action=viewfile&fid=43&id=1" rel="nofollow noreferrer">http://www.taw24.de/download/pafiledb.php?PHPSESSID=b48001ea004aacd86f5643a72feb2829&action=viewfile&fid=43&id=1</a><br>\nThe site is in german but the download has some english documentation as well.</p>\n\n<p>A quick google also turns up this, but I have not used it myself:<br>\n<a href="http://snipplr.com/view/173/mysql-dump/" rel="nofollow noreferrer">http://snipplr.com/view/173/mysql-dump/</a></p>\n'}, {'answer_id': 82119, 'author': 'lewis', 'author_id': 14442, 'author_profile': 'https://Stackoverflow.com/users/14442', 'pm_score': 6, 'selected': True, 'text': '<p>You could use SQL for this:</p>\n\n<pre><code>$file = \'backups/mytable.sql\';\n$result = mysql_query("SELECT * INTO OUTFILE \'$file\' FROM `##table##`");\n</code></pre>\n\n<p>Then just point a browser or FTP client at the directory/file (backups/mytable.sql). This is also a nice way to do incremental backups, given the filename a timestamp for example.</p>\n\n<p>To get it back in to your DataBase from that file you can use:</p>\n\n<pre><code>$file = \'backups/mytable.sql\';\n$result = mysql_query("LOAD DATA INFILE \'$file\' INTO TABLE `##table##`");\n</code></pre>\n\n<p>The other option is to use PHP to invoke a system command on the server and run \'mysqldump\':</p>\n\n<pre><code>$file = \'backups/mytable.sql\';\nsystem("mysqldump --opt -h ##databaseserver## -u ##username## -p ##password## ##database | gzip > ".$file);\n</code></pre>\n'}, {'answer_id': 84981, 'author': 'SeanDowney', 'author_id': 5261, 'author_profile': 'https://Stackoverflow.com/users/5261', 'pm_score': -1, 'selected': False, 'text': '<p>I use mysqldump via the command line :</p>\n\n<pre><code>exec("mysqldump sourceDatabase -uUsername -p\'password\' > outputFilename.sql");\n</code></pre>\n\n<p>Then you just download the resulting file and your done.</p>\n'}, {'answer_id': 85332, 'author': 'DreamWerx', 'author_id': 15487, 'author_profile': 'https://Stackoverflow.com/users/15487', 'pm_score': 2, 'selected': False, 'text': '<p>You might consider looking at: <a href="http://www.webyog.com" rel="nofollow noreferrer">http://www.webyog.com</a>\nThis is a great GUI admin tool, and they have a really neat HTTP-Tunneling feature (I\'m not sure if this is only in enterprise which costs a few bucks). </p>\n\n<p>Basically you upload a script they provide into your webspace (php script) and point sqlyog manager to it and you can access the database(s). It uses this script to tunnel/proxy the requests/queries between your home client and the server.</p>\n\n<p>I know at least 1 person who uses this method with great results.</p>\n'}, {'answer_id': 97208, 'author': 'Shinhan', 'author_id': 18219, 'author_profile': 'https://Stackoverflow.com/users/18219', 'pm_score': 4, 'selected': False, 'text': '<p>You should also consider <a href="http://phpminadmin.sourceforge.net/" rel="noreferrer">phpMinAdmin</a> which is only one file, so its easy to upload and setup.</p>\n'}, {'answer_id': 30223691, 'author': 'T.Todua', 'author_id': 2377343, 'author_profile': 'https://Stackoverflow.com/users/2377343', 'pm_score': 3, 'selected': False, 'text': '<p><strong>WORKING SOLUTION</strong> (latest version at:\n<a href="https://github.com/tazotodua/useful-php-scripts/blob/master/export-mysql-database-sql-backup.php" rel="noreferrer"><strong>Export.php</strong></a> + <a href="https://github.com/tazotodua/useful-php-scripts/blob/master/import-sql-database-mysql.php" rel="noreferrer"><strong>Import.php</strong></a> )</p>\n\n<pre><code>EXPORT_TABLES("localhost","user","pass","db_name");\n</code></pre>\n\n<p>CODE:</p>\n\n<pre><code>//https://github.com/tazotodua/useful-php-scripts\nfunction EXPORT_TABLES($host,$user,$pass,$name, $tables=false, $backup_name=false ){\n $mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES \'utf8\'");\n $queryTables = $mysqli->query(\'SHOW TABLES\'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }\n foreach($target_tables as $table){\n $result = $mysqli->query(\'SELECT * FROM \'.$table); $fields_amount=$result->field_count; $rows_num=$mysqli->affected_rows; $res = $mysqli->query(\'SHOW CREATE TABLE \'.$table); $TableMLine=$res->fetch_row();\n $content = (!isset($content) ? \'\' : $content) . "\\n\\n".$TableMLine[1].";\\n\\n";\n for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {\n while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):\n if ($st_counter%100 == 0 || $st_counter == 0 ) {$content .= "\\nINSERT INTO ".$table." VALUES";}\n $content .= "\\n(";\n for($j=0; $j<$fields_amount; $j++) { $row[$j] = str_replace("\\n","\\\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= \'"\'.$row[$j].\'"\' ; }else {$content .= \'""\';} if ($j<($fields_amount-1)){$content.= \',\';} }\n $content .=")";\n //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler\n if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;\n }\n } $content .="\\n\\n\\n";\n }\n $backup_name = $backup_name ? $backup_name : $name."___(".date(\'H-i-s\')."_".date(\'d-m-Y\').")__rand".rand(1,11111111).".sql";\n header(\'Content-Type: application/octet-stream\'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\\"".$backup_name."\\""); echo $content; exit;\n}\n</code></pre>\n'}, {'answer_id': 32117725, 'author': 'Vali Munteanu', 'author_id': 4800442, 'author_profile': 'https://Stackoverflow.com/users/4800442', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a <code>PHP</code> script I made which will backup all tables in your database. It is based on this <a href="http://davidwalsh.name/backup-mysql-database-php" rel="nofollow">http://davidwalsh.name/backup-mysql-database-php</a> with some improvements. First of all it will correctly set up <code>foreign key restrictions</code>.</p>\n\n<p>In my set up the script will run on a certain day of the week, let\'s say Monday. In case it did not run on Monday, it will still run on Tuesday (for example), creating the <code>.sql</code> file with the date of previous Monday, when it was supposed to run. It will erase <code>.sql</code> file from 4 weeks ago, so it always keeps the last 4 backups. Here\'s the code: </p>\n\n<pre><code><?php\n\nbackup_tables();\n\n// backup all tables in db\nfunction backup_tables()\n{\n $day_of_backup = \'Monday\'; //possible values: `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` `Sunday`\n $backup_path = \'databases/\'; //make sure it ends with "/"\n $db_host = \'localhost\';\n $db_user = \'root\';\n $db_pass = \'\';\n $db_name = \'movies_database_1\';\n\n //set the correct date for filename\n if (date(\'l\') == $day_of_backup) {\n $date = date("Y-m-d");\n } else {\n //set $date to the date when last backup had to occur\n $datetime1 = date_create($day_of_backup);\n $date = date("Y-m-d", strtotime($day_of_backup.\' -7 days\'));\n }\n\n if (!file_exists($backup_path.$date.\'-backup\'.\'.sql\')) {\n\n //connect to db\n $link = mysqli_connect($db_host,$db_user,$db_pass);\n mysqli_set_charset($link,\'utf8\');\n mysqli_select_db($link,$db_name);\n\n //get all of the tables\n $tables = array();\n $result = mysqli_query($link, \'SHOW TABLES\');\n while($row = mysqli_fetch_row($result))\n {\n $tables[] = $row[0];\n }\n\n //disable foreign keys (to avoid errors)\n $return = \'SET FOREIGN_KEY_CHECKS=0;\' . "\\r\\n";\n $return.= \'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";\' . "\\r\\n";\n $return.= \'SET AUTOCOMMIT=0;\' . "\\r\\n";\n $return.= \'START TRANSACTION;\' . "\\r\\n";\n\n //cycle through\n foreach($tables as $table)\n {\n $result = mysqli_query($link, \'SELECT * FROM \'.$table);\n $num_fields = mysqli_num_fields($result);\n $num_rows = mysqli_num_rows($result);\n $i_row = 0;\n\n //$return.= \'DROP TABLE \'.$table.\';\'; \n $row2 = mysqli_fetch_row(mysqli_query($link,\'SHOW CREATE TABLE \'.$table));\n $return.= "\\n\\n".$row2[1].";\\n\\n"; \n\n if ($num_rows !== 0) {\n $row3 = mysqli_fetch_fields($result);\n $return.= \'INSERT INTO \'.$table.\'( \';\n foreach ($row3 as $th) \n { \n $return.= \'`\'.$th->name.\'`, \'; \n }\n $return = substr($return, 0, -2);\n $return.= \' ) VALUES\';\n\n for ($i = 0; $i < $num_fields; $i++) \n {\n while($row = mysqli_fetch_row($result))\n {\n $return.="\\n(";\n for($j=0; $j<$num_fields; $j++) \n {\n $row[$j] = addslashes($row[$j]);\n $row[$j] = preg_replace("#\\n#","\\\\n",$row[$j]);\n if (isset($row[$j])) { $return.= \'"\'.$row[$j].\'"\' ; } else { $return.= \'""\'; }\n if ($j<($num_fields-1)) { $return.= \',\'; }\n }\n if (++$i_row == $num_rows) {\n $return.= ");"; // last row\n } else {\n $return.= "),"; // not last row\n } \n }\n }\n }\n $return.="\\n\\n\\n";\n }\n\n // enable foreign keys\n $return .= \'SET FOREIGN_KEY_CHECKS=1;\' . "\\r\\n";\n $return.= \'COMMIT;\';\n\n //set file path\n if (!is_dir($backup_path)) {\n mkdir($backup_path, 0755, true);\n }\n\n //delete old file\n $old_date = date("Y-m-d", strtotime(\'-4 weeks\', strtotime($date)));\n $old_file = $backup_path.$old_date.\'-backup\'.\'.sql\';\n if (file_exists($old_file)) unlink($old_file);\n\n //save file\n $handle = fopen($backup_path.$date.\'-backup\'.\'.sql\',\'w+\');\n fwrite($handle,$return);\n fclose($handle);\n }\n}\n\n?>\n</code></pre>\n'}, {'answer_id': 56603821, 'author': 'Teepeemm', 'author_id': 2336725, 'author_profile': 'https://Stackoverflow.com/users/2336725', 'pm_score': 1, 'selected': False, 'text': '<p>I found that I didn\'t have enough permissions for <code>SELECT * INTO OUTFILE</code>.\nBut I was able to use enough php (iterating and imploding) to really cut down on the nested loops compared to other approaches.</p>\n\n<pre><code>$dbfile = tempnam(sys_get_temp_dir(),\'sql\');\n\n// array_chunk, but for an iterable\nfunction iter_chunk($iterable,$chunksize) {\n foreach ( $iterable as $item ) {\n $ret[] = $item;\n if ( count($ret) >= $chunksize ) {\n yield $ret;\n $ret = array();\n }\n }\n if ( count($ret) > 0 ) {\n yield $ret;\n }\n}\n\nfunction tupleFromArray($assocArr) {\n return \'(\'.implode(\',\',array_map(function($val) {\n return \'"\'.addslashes($val).\'"\';\n },array_values($assocArr))).\')\';\n}\n\nfile_put_contents($dbfile,"\\n-- Table $table --\\n/*\\n");\n$description = $db->query("DESCRIBE `$table`");\n$row = $description->fetch_assoc();\nfile_put_contents($dbfile,implode("\\t",array_keys($row))."\\n",FILE_APPEND);\nforeach ( $description as $row ) {\n file_put_contents($dbfile,implode("\\t",array_values($row))."\\n",FILE_APPEND);\n}\nfile_put_contents($dbfile,"*/\\n",FILE_APPEND);\nfile_put_contents($dbfile,"DROP TABLE IF EXISTS `$table`;\\n",FILE_APPEND);\nfile_put_contents($dbfile,array_pop($db->query("SHOW CREATE TABLE `$table`")->fetch_row()),FILE_APPEND);\n$ret = $db->query("SELECT * FROM `$table`");\n$chunkedData = iter_chunk($ret,1023);\nforeach ( $chunkedData as $chunk ) {\n file_put_contents($dbfile, "\\n\\nINSERT INTO `$table` VALUES " . implode(\',\',array_map(\'tupleFromArray\',$chunk)) . ";\\n", FILE_APPEND );\n}\nreadfile($dbfile);\nunlink($dbfile);\n</code></pre>\n\n<p>If you have tables with foreign keys, this approach can still work if you drop\nthem in the correct order and then recreate them in the correct (reverse) order.\nThe <code>CREATE</code> statement will create the foreign key dependency for you.\nGo through <code>SELECT * FROM information_schema.referential_constraints</code> to\ndetermine that order.</p>\n\n<p>If your foreign keys have a circular dependency, then there is no possible order to drop or create. In that case, you might be able to follow the lead of phpMyAdmin, which creates all of the foreign keys at the end. But this also means that you have to adjust the <code>CREATE</code> statements.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6681/'] |
81,945 | <p>Is there a way to hide the google toolbar in my browser programmable?</p>
| [{'answer_id': 81965, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': "<p>You haven't said which browser you are using so I'm going to assume Internet Explorer* and answer No.</p>\n\n<p>If JavaScript on a web page could manipulate the browser, it would be a serious security hole and could create a lot of confusion for users.</p>\n\n<p>So no... for a good reason: Security.</p>\n\n<p>*. If you were using Firefox, and were talking about JavaScript within an extension to manipulate and theme the window chrome then this would be a different story.</p>\n"}, {'answer_id': 81970, 'author': 'user15453', 'author_id': 15453, 'author_profile': 'https://Stackoverflow.com/users/15453', 'pm_score': 0, 'selected': False, 'text': '<p>I really think that it is imposible to do that with javascript. This is because javascript is designed to control the behaviour of the site. And the browser is not part of the site.\n<br/><br/>\nOf course maby you are talking about some other Google toolbar then the plugin in the browser.</p>\n'}, {'answer_id': 81978, 'author': 'Peter', 'author_id': 15349, 'author_profile': 'https://Stackoverflow.com/users/15349', 'pm_score': 0, 'selected': False, 'text': '<p>As far as I know, you cannot access these parts of the browser due to security issues. But you can load new browser windows without toolbars as such. I don\'t know exactly how (hopefully other users will help yout out), but maybe start here: <a href="http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20782379.html" rel="nofollow noreferrer">http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20782379.html</a></p>\n\n<p>(PS: I know, it\'s experts-exchange, but I\'m not going to copy someone elses work, even if it\'s posted on EE).</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
81,949 | <p>Is there a unicode debug visualizer in Visual Studio 2008? I have a xml file that I'm pretty sure is in unicode. When I open it in wordpad, it shows the japanese characters correctly. When I read the file into a string using File.ReadAllText (UTF8), all the japanese characters show up as blocks in the string visualizer. If I use the xml visualizer, the characters show up correctly.</p>
| [{'answer_id': 82378, 'author': 'Duncan Smart', 'author_id': 1278, 'author_profile': 'https://Stackoverflow.com/users/1278', 'pm_score': 1, 'selected': False, 'text': "<p>You say it's <strong>Unicode</strong>, so why not use File.ReadAllText(<strong>Encoding.Unicode</strong>) then?</p>\n"}, {'answer_id': 97784, 'author': 'JasonTrue', 'author_id': 13433, 'author_profile': 'https://Stackoverflow.com/users/13433', 'pm_score': 2, 'selected': False, 'text': "<p>If you're getting square blocks, rather than complete garbage, you probably just need to specify a more suitable font in Visual Studio (in Tools | Options | Fonts and Colors). Try MS Gothic or MS Mincho (both Japanese fonts); I am guessing your issue can be resolved by tweaking the settings for [Watch, Locals and Autos Tool Windows], but it could be somewhere else.</p>\n\n<p>Not all applications magically font-link to a font that contains the characters you want to display.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9539/'] |
81,963 | <p>I can use DCOMCNFG to disable remote launch on my DCOM application, but I would like to do this programatically. I looked at CoInitializeSecurity, but that does not seem to do it. Anyone done this?</p>
<p>I am using Delphi BTW.</p>
| [{'answer_id': 82160, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 1, 'selected': False, 'text': "<p>The permissions for Remote/Local Activation/Launch are stored in the registry under the AppID for the object.</p>\n\n<p>I'm not sure how to edit it programmatically.</p>\n"}, {'answer_id': 1941922, 'author': 'ChristianWimmer', 'author_id': 117262, 'author_profile': 'https://Stackoverflow.com/users/117262', 'pm_score': 2, 'selected': False, 'text': '<p>The binary data is simply a security descriptor structure (PSecurityDescriptor). I mean it is a copy of the memory of this structure. And, of course, the security descriptor is self relative.\nJWSCL can create such a structure easily. </p>\n\n<p>Launch- and AccessPermission list for every user access rights that also contain remote and local access.</p>\n'}, {'answer_id': 2073995, 'author': 'Ruddy', 'author_id': 229904, 'author_profile': 'https://Stackoverflow.com/users/229904', 'pm_score': 0, 'selected': False, 'text': '<p>This is very similar to <a href="https://stackoverflow.com/questions/1998882/change-access-permissions-in-component-services-com-security-with-script-api/2072344#2072344">change Access Permissions in Component Services > COM Security with script/api?</a> for which i posted a response.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4382/'] |
81,972 | <p>The question I want to ask is thus:</p>
<p>Is casting down the inheritance tree (ie. towards a more specialiased class) from inside an abstract class excusable, or even a good thing, or is it always a poor choice with better options available?</p>
<p>Now, the example of why I think it can be used for good.</p>
<p>I recently implemented <a href="http://www.bittorrent.org/beps/bep_0003.html#the-connectivity-is-as-follows" rel="nofollow noreferrer">Bencoding from the BitTorrent protocol</a> in C#. A simple enough problem, how to represent the data. I chose to do it this way,</p>
<p>We have an <code>abstract BItem</code> class, which provides some basic functionality, including the <code>static BItem Decode(string)</code> that is used to decode a Bencoded string into the necessary structure.</p>
<p>There are also four derived classes, <code>BString</code>, <code>BInteger</code>, <code>BList</code> and <code>BDictionary</code>, representing the four different data types that be encoded. Now, here is the tricky part. <code>BList</code> and <code>BDictionary</code> have <code>this[int]</code> and <code>this[string]</code> accessors respectively to allow access to the array-like qualities of these data types.</p>
<p>The potentially horrific part is coming now:</p>
<pre><code>BDictionary torrent = (BDictionary) BItem.DecodeFile("my.torrent");
int filelength = (BInteger)((BDictionary)((BList)((BDictionary)
torrent["info"])["files"])[0])["length"];
</code></pre>
<p>Well, you get the picture... Ouch, that's hard on the eyes, not to mention the brain. So, I introduced something extra into the abstract class:</p>
<pre><code>public BItem this[int index]
{
get { return ((BList)this)[index]; }
}
public BItem this[string index]
{
get { return ((BDictionary)this)[index]; }
}
</code></pre>
<p>Now we could rewrite that old code as:</p>
<pre><code>BDictionary torrent = (BDictionary)BItem.DecodeFile("my.torrent");
int filelength = (BInteger)torrent["info"]["files"][0]["length"];
</code></pre>
<p>Wow, hey presto, MUCH more readable code. But did I just sell part of my soul for implying knowledge of subclasses into the abstract class?</p>
<p>EDIT: In response to some of the answers coming in, you're completely off track for this particular question since the structure is variable, for instance my example of <code>torrent["info"]["files"][0]["length"]</code> is valid, but so is <code>torrent["announce-list"][0][0]</code>, and both would be in 90% of torrent files out there. Generics isn't the way to go, with this problem atleast :(. Have a click through to the spec I linked, it's only 4 small dot-points large.</p>
| [{'answer_id': 81990, 'author': 'petr k.', 'author_id': 15497, 'author_profile': 'https://Stackoverflow.com/users/15497', 'pm_score': 2, 'selected': False, 'text': "<p>You really should not access any derived classes from the base class as it pretty much breaks the idea of OOP. Readibility certainly goes a long way, but I wouldn't trade it for reusability. Consider the case when you'll need to add another subclass - you'll also need to update the base class accordingly.</p>\n"}, {'answer_id': 82012, 'author': 'RickL', 'author_id': 7261, 'author_profile': 'https://Stackoverflow.com/users/7261', 'pm_score': 1, 'selected': False, 'text': '<p>If file length is something you retrieve often, why not implement a property in the BDictionary (?) class... so that you code becomes:</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile("my.torrent");\nint filelength = torrent.FileLength;\n</code></pre>\n\n<p>That way the implementation details are hidden from the user.</p>\n'}, {'answer_id': 82013, 'author': 'Rasmus Faber', 'author_id': 5542, 'author_profile': 'https://Stackoverflow.com/users/5542', 'pm_score': 4, 'selected': True, 'text': '<p>I think I would make the this[int] and this[string] accessors virtual and override them in BList/BDictionary. Classes where the accessors does not make sense should cast a NotSupportedException() (perhaps by having a default implementation in BItem).</p>\n\n<p>That makes your code work in the same way and gives you a more readable error in case you should write</p>\n\n<pre><code> (BInteger)torrent["info"][0]["files"]["length"];\n</code></pre>\n\n<p>by mistake.</p>\n'}, {'answer_id': 82023, 'author': 'Stormenet', 'author_id': 2090, 'author_profile': 'https://Stackoverflow.com/users/2090', 'pm_score': 0, 'selected': False, 'text': '<p>Did you concider parsing a simple "path" so you could write it this way:</p>\n\n<p><p><code>\nBDictionary torrent = BItem.DecodeFile("my.torrent");<br />\nint filelength = (int)torrent.Fetch("info.files.0.length");\n</code></p><p>\nPerhaps not the best way, but the readability increases(a little)</p></p>\n'}, {'answer_id': 82037, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 0, 'selected': False, 'text': "<ul>\n<li>If you have complete control of your codebase and your thought-process, by all means do.</li>\n<li>If not, you'll regret this the day some new person injects a BItem derivation that you didn't see coming into <em>your</em> BList or BDictionary.</li>\n</ul>\n\n<p>If you have to do this, atleast wrap it (control access to the list) in a class which has strongly typed method signatures. </p>\n\n<pre><code>BString GetString(BInteger);\nSetString(BInteger, BString);\n</code></pre>\n\n<p>Accept and return BStrings even though you internally store it in a BList of BItems. <em>(let me split before I make my 2 B or not 2 B)</em></p>\n"}, {'answer_id': 82040, 'author': 'John Christensen', 'author_id': 1194, 'author_profile': 'https://Stackoverflow.com/users/1194', 'pm_score': 0, 'selected': False, 'text': "<p>Hmm. I would actually argue that the first line of coded is more readable than the second - it takes a little longer to figure out what's going on it, but its more apparant that you're treating objects as BList or BDictionary. Applying the methods to the abstract class hides that detail, which can make it harder to figure out what your method is actually doing.</p>\n"}, {'answer_id': 82044, 'author': 'neaorin', 'author_id': 15591, 'author_profile': 'https://Stackoverflow.com/users/15591', 'pm_score': 1, 'selected': False, 'text': "<p>The way I see it, not all BItems are collections, thus not all BItems have indexers, so the indexer shouldn't be in BItem. I would derive another abstract class from BItem, let's name it BCollection, and put the indexers there, something like:</p>\n\n<pre><code>abstract class BCollection : BItem {\n\n public BItem this[int index] {get;}\n public BItem this[string index] {get;}\n}\n</code></pre>\n\n<p>and make BList and BDictionary inherit from BCollection.\nOr you could go the extra mile and make BCollection a generic class.</p>\n"}, {'answer_id': 82193, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>If you introduce generics, you can avoid casting.</p>\n\n<pre><code>class DecodedTorrent : BDictionary<BDictionary<BList<BDictionary<BInteger>>>>\n{\n}\n</code></pre>\n\n<hr>\n\n<pre><code>DecodedTorrent torrent = BItem.DecodeFile("mytorrent");\nint x = torrent["info"]["files"][0]["length"];\n</code></pre>\n\n<p>Hmm, but that probably won\'t work, as the types may depend on the path you take through the structure.</p>\n'}, {'answer_id': 82399, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Is it just me</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile("my.torrent");int filelength = (BInteger)((BDictionary)((BList)((BDictionary) torrent["info"])["files"])[0])["length"];\n</code></pre>\n\n<p>You don\'t need the BDictionary cast \'torrent\' is declared as a BDictionary</p>\n\n<pre><code>public BItem this[int index]{&nbsp; &nbsp; get { return ((BList)this)[index]; }}public BItem this[string index]{&nbsp; &nbsp; get { return ((BDictionary)this)[index]; }}\n</code></pre>\n\n<p>These don\'t acheive the desired result as the return type is still the abstrat version, so you still have to cast.</p>\n\n<p>The rewritten code would have to be</p>\n\n<pre><code>BDictionary torrent = BItem.DecodeFile("my.torrent");int filelength = (BInteger)((BList)((BDictionary)torrent["info"]["files"])[0])["length"];\n</code></pre>\n\n<p>Which is the just as bad as the first lot</p>\n'}, {'answer_id': 86393, 'author': 'Thomas Eyde', 'author_id': 3282, 'author_profile': 'https://Stackoverflow.com/users/3282', 'pm_score': 1, 'selected': False, 'text': '<p>My recommendation would be to introduce more abstractions. I find it confusing that a BItem has a DecodeFile() which returns a BDictionary. This may be a reasonable thing to do in the torrent domain, I don\'t know.</p>\n\n<p>However, I would find an api like the following more reasonable:</p>\n\n<pre><code>BFile torrent = BFile.DecodeFile("my.torrent");\nint filelength = torrent.Length;\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15537/'] |
81,973 | <p>Has anyone used ruby in 64-bit environments in various platforms (HP=UX, Solaris, AIX etc.) in a commercial production environment that heavily relies on database.</p>
<p>Have you faced any issues / bugs during these times?</p>
<p>I know that overall things look ok. Compilation, deployment etc.
I would like to know if you encountered any 'gotcha's</p>
| [{'answer_id': 89311, 'author': 'epochwolf', 'author_id': 16204, 'author_profile': 'https://Stackoverflow.com/users/16204', 'pm_score': 1, 'selected': False, 'text': "<p>I have no issues with Debian on a 64 bit platform. The only issues I've had with 64 bit linux environments is related to things like the flash plugin for Firefox. </p>\n\n<p>Edit: I used Debian on a server and a laptop. The firefox problem was only on the laptop. (For obvious reasons)</p>\n"}, {'answer_id': 180333, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 1, 'selected': False, 'text': "<p>We use it on 64-bit freebsd (mysql database server). \nRuby itself has been fine.</p>\n\n<p>There was an issue with phusion passenger a while ago, but it's since been fixed, and we've had some issues with C extensions (notably RMagick), but we've been able to overcome them all.<br>\nRMagick didn't crash, but had a bug where it wouldn't produce valid output when compositing TIFF files with clipping paths.</p>\n\n<p>If you don't rely on any obscure C extensions I'd say you'll be fine.</p>\n"}, {'answer_id': 908736, 'author': 'brianegge', 'author_id': 14139, 'author_profile': 'https://Stackoverflow.com/users/14139', 'pm_score': 0, 'selected': False, 'text': '<p>I run both 32 bit and 64 bit ruby on Solaris 10. Compiling extensions for 64-bit AMD64 can be a little tricky. There exists a <a href="http://www.theeggeadventure.com/wikimedia/index.php/Ruby_Sybase_Solaris" rel="nofollow noreferrer">Sybase driver, which works but has a couple of bugs</a>. The Oracle driver is a little better. It\'s not the most common setup, so finding help can be a bit difficult.</p>\n\n<p>I\'m running Ruby 1.8.6-p287. Later versions have caused issues. I usually compile 32 bit ruby with gcc and 64 bit with Sun C 5.8.</p>\n'}, {'answer_id': 910352, 'author': 'rampion', 'author_id': 9859, 'author_profile': 'https://Stackoverflow.com/users/9859', 'pm_score': 1, 'selected': False, 'text': "<p>I had to use 32-bit MySQL on my 64-bit MacBookPro with rails b/c mysql.gem couldn't handle 64-bit MySQL.</p>\n"}, {'answer_id': 910370, 'author': 'Friedrich', 'author_id': 15068, 'author_profile': 'https://Stackoverflow.com/users/15068', 'pm_score': 1, 'selected': False, 'text': "<p>I'm sorry I've not experiences with Ruby on anything else but Linux. As epochwolf has written I have also not troubles with Debian, Postgres, Rails, (neither with Apache and passenger nor with Mongrel cluster. So I'm using probably the most widely used platform for Ruby, so I'd expect that there are less problems. I've done my share of AIX administration but to that time ruby was not even known. So I can't tell if Ruby is that stabel on other Unices. However it seems one can get around this in two ways\n1) just try it on others systems but Linux (or some BSD (be it Free, Open, or Net)\n2) if you encounter problems use a server under Linux and/or some BSD whic is known to work.</p>\n\n<p>Regards\nFriedrich</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396527/'] |
81,991 | <p>Every time a user posts something containing <code><</code> or <code>></code> in a page in my web application, I get this exception thrown.</p>
<p>I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.</p>
<p>Trapping the exception and showing</p>
<blockquote>
<p>An error has occurred please go back and re-type your entire form again, but this time please do not use <</p>
</blockquote>
<p>doesn't seem professional enough to me.</p>
<p>Disabling post validation (<code>validateRequest="false"</code>) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.</p>
<p>Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.
So the <code>.Text</code> property of my text-box will be <code>something & lt; html & gt;</code></p>
<p>Is there a way I can do this from a handler?</p>
| [{'answer_id': 82121, 'author': 'Pavel Chuchuva', 'author_id': 14131, 'author_profile': 'https://Stackoverflow.com/users/14131', 'pm_score': 6, 'selected': False, 'text': '<p>You can <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.htmlencode" rel="noreferrer">HTML encode</a> text box content, but unfortunately that won\'t stop the exception from happening. In my experience there is no way around, and you have to disable page validation. By doing that you\'re saying: "I\'ll be careful, I promise."</p>\n'}, {'answer_id': 82136, 'author': 'bastos.sergio', 'author_id': 12772, 'author_profile': 'https://Stackoverflow.com/users/12772', 'pm_score': 2, 'selected': False, 'text': '<p>You should use the Server.HtmlEncode method to protect your site from dangerous input.</p>\n\n<p><a href="http://www.asp.net/learn/whitepapers/request-validation/" rel="nofollow noreferrer">More info here</a></p>\n'}, {'answer_id': 82170, 'author': 'JacquesB', 'author_id': 7488, 'author_profile': 'https://Stackoverflow.com/users/7488', 'pm_score': 11, 'selected': True, 'text': '<p>I think you are attacking it from the wrong angle by trying to encode all posted data.</p>\n<p>Note that a "<code><</code>" could also come from other outside sources, like a database field, a configuration, a file, a feed and so on.</p>\n<p>Furthermore, "<code><</code>" is not inherently dangerous. It\'s only dangerous in a specific context: when writing strings that haven\'t been encoded to HTML output (because of XSS).</p>\n<p>In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string "<code>javascript:</code>" may be dangerous. The single quote character on the other hand is dangerous when interpolating strings in SQL queries, but perfectly safe if it is a part of a name submitted from a form or read from a database field.</p>\n<p>The bottom line is: you can\'t filter random input for dangerous characters, because any character may be dangerous under the right circumstances. You should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning. When you write a string to HTML, you should encode characters that have special meaning in HTML, using Server.HtmlEncode. If you pass a string to a dynamic SQL statement, you should encode different characters (or better, let the framework do it for you by using prepared statements or the like)..</p>\n<p><em>When</em> you are sure you HTML-encode everywhere you pass strings to HTML, then set <code>ValidateRequest="false"</code> in the <code><%@ Page ... %></code> directive in your <code>.aspx</code> file(s).</p>\n<p>In .NET 4 you may need to do a little more. Sometimes it\'s necessary to also add <code><httpRuntime requestValidationMode="2.0" /></code> to web.config (<a href="http://www.asp.net/%28S%28ywiyuluxr3qb2dfva1z5lgeg%29%29/learn/whitepapers/aspnet4/breaking-changes/" rel="noreferrer">reference</a>).</p>\n'}, {'answer_id': 82174, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 4, 'selected': False, 'text': '<p>I guess you could do it in a module; but that leaves open some questions; what if you want to save the input to a database? Suddenly because you\'re saving encoded data to the database you end up trusting input from it which is probably a bad idea. Ideally you store raw unencoded data in the database and the encode every time.</p>\n\n<p>Disabling the protection on a per page level and then encoding each time is a better option.</p>\n\n<p>Rather than using Server.HtmlEncode you should look at the newer, more complete <a href="http://blogs.msdn.com/ace_team/archive/2006/11/20/microsoft-anti-cross-site-scripting-library-v1-5-is-done.aspx" rel="nofollow noreferrer">Anti-XSS library</a> from the Microsoft ACE team.</p>\n'}, {'answer_id': 82179, 'author': 'Paweł Hajdan', 'author_id': 9403, 'author_profile': 'https://Stackoverflow.com/users/9403', 'pm_score': 3, 'selected': False, 'text': '<p>As long as these are <strong>only</strong> "<" and ">" (and not the double quote itself) characters and you\'re using them in context like <input value="<em>this</em>" />, you\'re safe (while for <textarea><em>this one</em></textarea> you would be vulnerable of course). That may simplify your situation, but for <strong>anything</strong> more use one of other posted solutions.</p>\n'}, {'answer_id': 82203, 'author': 'woany', 'author_id': 15623, 'author_profile': 'https://Stackoverflow.com/users/15623', 'pm_score': 3, 'selected': False, 'text': '<p>Disable the page validation if you really need the special characters like, <code>></code>, , <code><</code>, etc. Then ensure that when the user input is displayed, the data is HTML-encoded. </p>\n\n<p>There is a security vulnerability with the page validation, so it can be bypassed. Also the page validation shouldn\'t be solely relied on.</p>\n\n<p>See: <a href="http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf" rel="nofollow noreferrer">http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf</a></p>\n'}, {'answer_id': 82243, 'author': 'Captain Toad', 'author_id': 15664, 'author_profile': 'https://Stackoverflow.com/users/15664', 'pm_score': 3, 'selected': False, 'text': "<p>If you're just looking to tell your users that < and > are not to be used BUT, you don't want the entire form processed/posted back (and lose all the input) before-hand could you not simply put in a validator around the field to screen for those (and maybe other potentially dangerous) characters?</p>\n"}, {'answer_id': 83949, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Please bear in mind that some .NET controls will automatically HTML encode the output. For instance, setting the .Text property on a TextBox control will automatically encode it. That specifically means converting <code><</code> into <code>&lt;</code>, <code>></code> into <code>&gt;</code> and <code>&</code> into <code>&amp;</code>. So be wary of doing this...</p>\n\n<pre><code>myTextBox.Text = Server.HtmlEncode(myStringFromDatabase); // Pseudo code\n</code></pre>\n\n<p>However, the .Text property for HyperLink, Literal and Label won\'t HTML encode things, so wrapping Server.HtmlEncode(); around anything being set on these properties is a must if you want to prevent <code><script> window.location = "http://www.google.com"; </script></code> from being output into your page and subsequently executed.</p>\n\n<p>Do a little experimenting to see what gets encoded and what doesn\'t.</p>\n'}, {'answer_id': 436247, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>If you don\'t want to disable ValidateRequest you need to implement a JavaScript function in order to avoid the exception. It is not the best option, but it works.</p>\n\n<pre><code>function AlphanumericValidation(evt)\n{\n var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :\n ((evt.which) ? evt.which : 0));\n\n // User type Enter key\n if (charCode == 13)\n {\n // Do something, set controls focus or do anything\n return false;\n }\n\n // User can not type non alphanumeric characters\n if ( (charCode < 48) ||\n (charCode > 122) ||\n ((charCode > 57) && (charCode < 65)) ||\n ((charCode > 90) && (charCode < 97))\n )\n {\n // Show a message or do something\n return false;\n }\n}\n</code></pre>\n\n<p>Then in code behind, on the PageLoad event, add the attribute to your control with the next code:</p>\n\n<pre><code>Me.TextBox1.Attributes.Add("OnKeyPress", "return AlphanumericValidation(event);")\n</code></pre>\n'}, {'answer_id': 1540976, 'author': 'Zack Peterson', 'author_id': 83, 'author_profile': 'https://Stackoverflow.com/users/83', 'pm_score': 9, 'selected': False, 'text': '<p>There\'s a different solution to this error if you\'re using ASP.NET MVC:</p>\n\n<ul>\n<li><a href="http://jwwishart.wordpress.com/2009/06/22/asp-net-mvc-pages-validaterequestfalse-doesnt-work/" rel="noreferrer">ASP.NET MVC – pages validateRequest=false doesn’t work?</a></li>\n<li><a href="https://stackoverflow.com/questions/807662/why-is-validateinputfalse-not-working">Why is ValidateInput(False) not working?</a></li>\n<li><a href="https://web.archive.org/web/20160327063049/http://weblogs.asp.net:80/rashid/asp-net-mvc-rc1-validateinput-a-potential-dangerous-request-and-the-pitfall" rel="noreferrer">ASP.NET MVC RC1, VALIDATEINPUT, A POTENTIAL DANGEROUS REQUEST AND THE PITFALL</a></li>\n</ul>\n\n<p>C# sample:</p>\n\n<pre><code>[HttpPost, ValidateInput(false)]\npublic ActionResult Edit(FormCollection collection)\n{\n // ...\n}\n</code></pre>\n\n<p>Visual Basic sample:</p>\n\n<pre><code><AcceptVerbs(HttpVerbs.Post), ValidateInput(False)> _\nFunction Edit(ByVal collection As FormCollection) As ActionResult\n ...\nEnd Function\n</code></pre>\n'}, {'answer_id': 1563330, 'author': 'BenMaddox', 'author_id': 38698, 'author_profile': 'https://Stackoverflow.com/users/38698', 'pm_score': 6, 'selected': False, 'text': '<p>You can catch that error in Global.asax. I still want to validate, but show an appropriate message. On the blog listed below, a sample like this was available. </p>\n\n<pre><code> void Application_Error(object sender, EventArgs e)\n {\n Exception ex = Server.GetLastError();\n\n if (ex is HttpRequestValidationException)\n {\n Response.Clear();\n Response.StatusCode = 200;\n Response.Write(@"[html]");\n Response.End();\n }\n }\n</code></pre>\n\n<p>Redirecting to another page also seems like a reasonable response to the exception.</p>\n\n<p><a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="noreferrer">http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html</a></p>\n'}, {'answer_id': 3368769, 'author': 'JordanC', 'author_id': 172330, 'author_profile': 'https://Stackoverflow.com/users/172330', 'pm_score': 8, 'selected': False, 'text': '<p>If you are on .NET 4.0 make sure you add this in your <em>web.config</em> file inside the <code><system.web></code> tags:</p>\n\n<pre><code><httpRuntime requestValidationMode="2.0" />\n</code></pre>\n\n<hr>\n\n<p>In .NET 2.0, request validation only applied to <code>aspx</code> requests. In .NET 4.0 this was expanded to include <strong>all</strong> requests. You can revert to <em>only</em> performing XSS validation when processing <code>.aspx</code> by specifying:</p>\n\n<pre><code>requestValidationMode="2.0"\n</code></pre>\n\n<p>You can disable request validate <em>entirely</em> by specifying:</p>\n\n<pre><code>validateRequest="false"\n</code></pre>\n'}, {'answer_id': 4113591, 'author': 'gligoran', 'author_id': 227613, 'author_profile': 'https://Stackoverflow.com/users/227613', 'pm_score': 6, 'selected': False, 'text': '<p>The previous answers are great, but nobody said how to exclude a single field from being validated for HTML/JavaScript injections. I don\'t know about previous versions, but in MVC3 Beta you can do this:</p>\n\n<pre><code>[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]\npublic virtual ActionResult Edit(int id, FormCollection collection)\n{\n ...\n}\n</code></pre>\n\n<p>This still validates all the fields except for the excluded one. The nice thing about this is that your validation attributes still validate the field, but you just don\'t get the "A potentially dangerous Request.Form value was detected from the client" exceptions.</p>\n\n<p>I\'ve used this for validating a regular expression. I\'ve made my own ValidationAttribute to see if the regular expression is valid or not. As regular expressions can contain something that looks like a script I applied the above code - the regular expression is still being checked if it\'s valid or not, but not if it contains scripts or HTML.</p>\n'}, {'answer_id': 4313998, 'author': 'ranthonissen', 'author_id': 403259, 'author_profile': 'https://Stackoverflow.com/users/403259', 'pm_score': 6, 'selected': False, 'text': '<p>In ASP.NET MVC you need to set requestValidationMode="2.0" and validateRequest="false" in web.config, and apply a ValidateInput attribute to your controller action:</p>\n\n<pre><code><httpRuntime requestValidationMode="2.0"/>\n\n<configuration>\n <system.web>\n <pages validateRequest="false" />\n </system.web>\n</configuration>\n</code></pre>\n\n<p>and</p>\n\n<pre><code>[Post, ValidateInput(false)]\npublic ActionResult Edit(string message) {\n ...\n}\n</code></pre>\n'}, {'answer_id': 7306222, 'author': 'Anthony Johnston', 'author_id': 122232, 'author_profile': 'https://Stackoverflow.com/users/122232', 'pm_score': 9, 'selected': False, 'text': '<p>In ASP.NET MVC (starting in version 3), you can add the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.allowhtmlattribute.aspx" rel="noreferrer"><code>AllowHtml</code></a> attribute to a property on your model.</p>\n\n<p>It allows a request to include HTML markup during model binding by skipping request validation for the property.</p>\n\n<pre><code>[AllowHtml]\npublic string Description { get; set; }\n</code></pre>\n'}, {'answer_id': 9035316, 'author': 'Piercy', 'author_id': 455135, 'author_profile': 'https://Stackoverflow.com/users/455135', 'pm_score': 5, 'selected': False, 'text': '<p>It seems no one has mentioned the below yet, but it fixes the issue for me. And before anyone says yeah it\'s Visual Basic... yuck.</p>\n\n<pre><code><%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Example.aspx.vb" Inherits="Example.Example" **ValidateRequest="false"** %>\n</code></pre>\n\n<p>I don\'t know if there are any downsides, but for me this worked amazing.</p>\n'}, {'answer_id': 9237332, 'author': 'Trisped', 'author_id': 641833, 'author_profile': 'https://Stackoverflow.com/users/641833', 'pm_score': 3, 'selected': False, 'text': '<p>You could also use JavaScript\'s <a href="http://www.w3schools.com/jsref/jsref_escape.asp" rel="noreferrer">escape(string)</a> function to replace the special characters. Then server side use Server.<a href="http://msdn.microsoft.com/en-us/library/hwzhtkke.aspx" rel="noreferrer">URLDecode(string)</a> to switch it back.</p>\n\n<p>This way you don\'t have to turn off input validation and it will be more clear to other programmers that the string may have HTML content.</p>\n'}, {'answer_id': 9711182, 'author': 'Mahdi jokar', 'author_id': 1125430, 'author_profile': 'https://Stackoverflow.com/users/1125430', 'pm_score': 5, 'selected': False, 'text': '<p>In the web.config file, within the tags, insert the httpRuntime element with the attribute requestValidationMode="2.0". Also add the validateRequest="false" attribute in the pages element.</p>\n\n<p>Example:</p>\n\n<pre><code><configuration>\n <system.web>\n <httpRuntime requestValidationMode="2.0" />\n </system.web>\n <pages validateRequest="false">\n </pages>\n</configuration>\n</code></pre>\n'}, {'answer_id': 9739209, 'author': 'magritte', 'author_id': 931545, 'author_profile': 'https://Stackoverflow.com/users/931545', 'pm_score': 3, 'selected': False, 'text': "<p>The other solutions here are nice, however it's a bit of a royal pain in the rear to have to apply [AllowHtml] to every single Model property, especially if you have over 100 models on a decent sized site.</p>\n\n<p>If like me, you want to turn this (IMHO pretty pointless) feature off site wide you can override the Execute() method in your base controller (if you don't already have a base controller I suggest you make one, they can be pretty useful for applying common functionality).</p>\n\n<pre><code> protected override void Execute(RequestContext requestContext)\n {\n // Disable requestion validation (security) across the whole site\n ValidateRequest = false;\n base.Execute(requestContext);\n }\n</code></pre>\n\n<p>Just make sure that you are HTML encoding everything that is pumped out to the views that came from user input (it's default behaviour in ASP.NET MVC 3 with Razor anyway, so unless for some bizarre reason you are using Html.Raw() you shouldn't require this feature.</p>\n"}, {'answer_id': 11530248, 'author': 'Jaider', 'author_id': 480700, 'author_profile': 'https://Stackoverflow.com/users/480700', 'pm_score': 4, 'selected': False, 'text': '<p>In ASP.NET, you can catch the exception and do something about it, such as displaying a friendly message or redirect to another page... Also there is a possibility that you can handle the validation by yourself...</p>\n\n<p>Display friendly message:</p>\n\n<pre><code>protected override void OnError(EventArgs e)\n{\n base.OnError(e);\n var ex = Server.GetLastError().GetBaseException();\n if (ex is System.Web.HttpRequestValidationException)\n {\n Response.Clear();\n Response.Write("Invalid characters."); // Response.Write(HttpUtility.HtmlEncode(ex.Message));\n Response.StatusCode = 200;\n Response.End();\n }\n}\n</code></pre>\n'}, {'answer_id': 11798616, 'author': 'Ryan', 'author_id': 1574529, 'author_profile': 'https://Stackoverflow.com/users/1574529', 'pm_score': 3, 'selected': False, 'text': '<p>I ended up using JavaScript before each postback to check for the characters you didn\'t want, such as:</p>\n\n<pre><code><asp:Button runat="server" ID="saveButton" Text="Save" CssClass="saveButton" OnClientClick="return checkFields()" />\n\nfunction checkFields() {\n var tbs = new Array();\n tbs = document.getElementsByTagName("input");\n var isValid = true;\n for (i=0; i<tbs.length; i++) {\n if (tbs(i).type == \'text\') {\n if (tbs(i).value.indexOf(\'<\') != -1 || tbs(i).value.indexOf(\'>\') != -1) {\n alert(\'<> symbols not allowed.\');\n isValid = false;\n }\n }\n }\n return isValid;\n}\n</code></pre>\n\n<p>Granted my page is mostly data entry, and there are very few elements that do postbacks, but at least their data is retained.</p>\n'}, {'answer_id': 11955698, 'author': 'Leniel Maccaferri', 'author_id': 114029, 'author_profile': 'https://Stackoverflow.com/users/114029', 'pm_score': 3, 'selected': False, 'text': '<p>I was getting this error too.</p>\n\n<p>In my case, a user entered an accented character <code>á</code> in a Role Name (regarding the ASP.NET membership provider).</p>\n\n<p>I pass the role name to a method to grant Users to that role and the <code>$.ajax</code> post request was failing miserably...</p>\n\n<p>I did this to solve the problem:</p>\n\n<p>Instead of</p>\n\n<pre><code>data: { roleName: \'@Model.RoleName\', users: users }\n</code></pre>\n\n<p>Do this</p>\n\n<pre><code>data: { roleName: \'@Html.Raw(@Model.RoleName)\', users: users }\n</code></pre>\n\n<p><code>@Html.Raw</code> did the trick.</p>\n\n<p>I was getting the Role name as HTML value <code>roleName="Cadastro b&#225;s"</code>. This value with HTML entity <code>&#225;</code> was being blocked by ASP.NET MVC. Now I get the <code>roleName</code> parameter value the way it should be: <code>roleName="Cadastro Básico"</code> and ASP.NET MVC engine won\'t block the request anymore.</p>\n'}, {'answer_id': 13589607, 'author': 'Carter Medlin', 'author_id': 324479, 'author_profile': 'https://Stackoverflow.com/users/324479', 'pm_score': 7, 'selected': False, 'text': '<p>For ASP.NET 4.0, you can allow markup as input for specific pages instead of the whole site by putting it all in a <code><location></code> element. This will make sure all your other pages are safe. You do NOT need to put <code>ValidateRequest="false"</code> in your .aspx page.</p>\n\n<pre><code><configuration>\n...\n <location path="MyFolder/.aspx">\n <system.web>\n <pages validateRequest="false" />\n <httpRuntime requestValidationMode="2.0" />\n </system.web>\n </location>\n...\n</configuration>\n</code></pre>\n\n<p>It is safer to control this inside your web.config, because you can see at a site level which pages allow markup as input.</p>\n\n<p><strong>You still need to programmatically validate input on pages where request validation is disabled.</strong></p>\n'}, {'answer_id': 14925246, 'author': 'Mike S.', 'author_id': 1937357, 'author_profile': 'https://Stackoverflow.com/users/1937357', 'pm_score': 2, 'selected': False, 'text': "<p>None of the suggestions worked for me. I did not want to turn off this feature for the whole website anyhow because 99% time I do not want my users placing HTML on web forms. I just created my own work around method since I'm the only one using this particular application. I convert the input to HTML in the code behind and insert it into my database.</p>\n"}, {'answer_id': 16224548, 'author': 'flakomalo', 'author_id': 2321524, 'author_profile': 'https://Stackoverflow.com/users/2321524', 'pm_score': 6, 'selected': False, 'text': '<p>The answer to this question is simple:</p>\n\n<pre><code>var varname = Request.Unvalidated["parameter_name"];\n</code></pre>\n\n<p>This would disable validation for the particular request.</p>\n'}, {'answer_id': 16867157, 'author': 'Ady Levy', 'author_id': 2442115, 'author_profile': 'https://Stackoverflow.com/users/2442115', 'pm_score': 3, 'selected': False, 'text': '<p>You can use something like:</p>\n\n<pre><code>var nvc = Request.Unvalidated().Form;\n</code></pre>\n\n<p>Later, <code>nvc["yourKey"]</code> should work.</p>\n'}, {'answer_id': 20450300, 'author': 'Sel', 'author_id': 2706338, 'author_profile': 'https://Stackoverflow.com/users/2706338', 'pm_score': 4, 'selected': False, 'text': '<p>Another solution is:</p>\n\n<pre><code>protected void Application_Start()\n{\n ...\n RequestValidator.Current = new MyRequestValidator();\n}\n\npublic class MyRequestValidator: RequestValidator\n{\n protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n {\n bool result = base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n\n if (!result)\n {\n // Write your validation here\n if (requestValidationSource == RequestValidationSource.Form ||\n requestValidationSource == RequestValidationSource.QueryString)\n\n return true; // Suppress error message\n }\n return result;\n }\n}\n</code></pre>\n'}, {'answer_id': 21427148, 'author': 'A.Dara', 'author_id': 1115537, 'author_profile': 'https://Stackoverflow.com/users/1115537', 'pm_score': 5, 'selected': False, 'text': '<p>For MVC, ignore input validation by adding </p>\n\n<blockquote>\n <p>[ValidateInput(false)]</p>\n</blockquote>\n\n<p>above each Action in the Controller.</p>\n'}, {'answer_id': 23415656, 'author': 'Walden Leverich', 'author_id': 2673770, 'author_profile': 'https://Stackoverflow.com/users/2673770', 'pm_score': 2, 'selected': False, 'text': '<p>As indicated in my comment to <a href="https://stackoverflow.com/questions/81991/a-potentially-dangerous-request-form-value-was-detected-from-the-client/20450300#20450300">Sel\'s answer</a>, this is our extension to a custom request validator.</p>\n\n<pre><code>public class SkippableRequestValidator : RequestValidator\n{\n protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n {\n if (collectionKey != null && collectionKey.EndsWith("_NoValidation"))\n {\n validationFailureIndex = 0;\n return true;\n }\n\n return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n }\n}\n</code></pre>\n'}, {'answer_id': 25872850, 'author': 'Jason Shuler', 'author_id': 1026711, 'author_profile': 'https://Stackoverflow.com/users/1026711', 'pm_score': 4, 'selected': False, 'text': '<p>I found a solution that uses JavaScript to encode the data, which is decoded in .NET (and doesn\'t require jQuery).</p>\n\n<ul>\n<li>Make the textbox an HTML element (like textarea) instead of an ASP one.</li>\n<li>Add a hidden field.</li>\n<li><p>Add the following JavaScript function to your header.</p>\n\n\n function boo() {\n targetText = document.getElementById("HiddenField1");\n sourceText = document.getElementById("userbox");\n targetText.value = escape(sourceText.innerText);\n }\n</li>\n</ul>\n\n<p>In your textarea, include an onchange that calls boo():</p>\n\n<pre><code><textarea id="userbox" onchange="boo();"></textarea>\n</code></pre>\n\n<p>Finally, in .NET, use</p>\n\n<pre><code>string val = Server.UrlDecode(HiddenField1.Value);\n</code></pre>\n\n<p>I am aware that this is one-way - if you need two-way you\'ll have to get creative, but this provides a solution if you cannot edit the web.config</p>\n\n<p>Here\'s an example I (MC9000) came up with and use via jQuery:</p>\n\n<pre><code>$(document).ready(function () {\n\n $("#txtHTML").change(function () {\n var currentText = $("#txtHTML").text();\n currentText = escape(currentText); // Escapes the HTML including quotations, etc\n $("#hidHTML").val(currentText); // Set the hidden field\n });\n\n // Intercept the postback\n $("#btnMyPostbackButton").click(function () {\n $("#txtHTML").val(""); // Clear the textarea before POSTing\n // If you don\'t clear it, it will give you\n // the error due to the HTML in the textarea.\n return true; // Post back\n });\n\n\n});\n</code></pre>\n\n<p>And the markup:</p>\n\n<pre><code><asp:HiddenField ID="hidHTML" runat="server" />\n<textarea id="txtHTML"></textarea>\n<asp:Button ID="btnMyPostbackButton" runat="server" Text="Post Form" />\n</code></pre>\n\n<p>This works great. If a hacker tries to post via bypassing JavaScript, they they will just see the error. You can save all this data encoded in a database as well, then unescape it (on the server side), and parse & check for attacks before displaying elsewhere.</p>\n'}, {'answer_id': 29366891, 'author': 'Devendra Patel', 'author_id': 3027600, 'author_profile': 'https://Stackoverflow.com/users/3027600', 'pm_score': -1, 'selected': False, 'text': '<p>Try with </p>\n\n<blockquote>\n <p><code>Server.Encode</code></p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p><code>Server.HtmlDecode</code>\n while sending and receiving.</p>\n</blockquote>\n'}, {'answer_id': 30838818, 'author': 'vakeel', 'author_id': 4222088, 'author_profile': 'https://Stackoverflow.com/users/4222088', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Cause</strong></p>\n\n<p>ASP.NET by default validates all input controls for potentially unsafe contents that can lead to <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> (XSS) and <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injections</a>. Thus it disallows such content by throwing the above exception. By default it is recommended to allow this check to happen on each postback.</p>\n\n<p><strong>Solution</strong></p>\n\n<p>On many occasions you need to submit HTML content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the <code>@Page</code> directive to false.</p>\n\n<pre><code><%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %>\n</code></pre>\n\n<p>This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this, check throughout your web application; you’ll need to set it to false in your web.config <system.web> section</p>\n\n<pre><code><pages validateRequest ="false" />\n</code></pre>\n\n<p>For .NET 4.0 or higher frameworks you will need to also add the following line in the <system.web> section to make the above work.</p>\n\n<pre><code><httpRuntime requestValidationMode = "2.0" />\n</code></pre>\n\n<p>That’s it. I hope this helps you in getting rid of the above issue.</p>\n\n<p>Reference by: <em><a href="http://www.aspsnippets.com/Articles/ASPNet-Error-A-potentially-dangerous-RequestForm-value-was-detected-from-the-client.aspx">ASP.Net Error: A potentially dangerous Request.Form value was detected from the client</a></em></p>\n'}, {'answer_id': 34196133, 'author': 'Durgesh Pandey', 'author_id': 5030579, 'author_profile': 'https://Stackoverflow.com/users/5030579', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re using framework 4.0 then the entry in the web.config (<pages validateRequest="false" />)</p>\n\n<pre><code><configuration>\n <system.web>\n <pages validateRequest="false" />\n </system.web>\n</configuration>\n</code></pre>\n\n<p>If you\'re using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")</p>\n\n<pre><code><system.web>\n <compilation debug="true" targetFramework="4.5" />\n <httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>\n</system.web>\n</code></pre>\n\n<p>If you want for only single page then, In you aspx file you should put the first line as this :</p>\n\n<pre><code><%@ Page EnableEventValidation="false" %>\n</code></pre>\n\n<p>if you already have something like <%@ Page so just add the rest => <code>EnableEventValidation="false"</code> %></p>\n\n<p>I recommend not to do it.</p>\n'}, {'answer_id': 35621783, 'author': 'Sel', 'author_id': 2706338, 'author_profile': 'https://Stackoverflow.com/users/2706338', 'pm_score': 2, 'selected': False, 'text': '<p>You can automatically HTML encode field in custom Model Binder. My solution some different, I put error in ModelState and display error message near the field. It`s easy to modify this code for automatically encode </p>\n\n<pre><code> public class AppModelBinder : DefaultModelBinder\n {\n protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n {\n try\n {\n return base.CreateModel(controllerContext, bindingContext, modelType);\n }\n catch (HttpRequestValidationException e)\n {\n HandleHttpRequestValidationException(bindingContext, e);\n return null; // Encode here\n }\n }\n protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,\n PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)\n {\n try\n {\n return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);\n }\n catch (HttpRequestValidationException e)\n {\n HandleHttpRequestValidationException(bindingContext, e);\n return null; // Encode here\n }\n }\n\n protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)\n {\n var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;\n if (valueProviderCollection != null)\n {\n ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);\n bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n }\n\n string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: <, &",\n bindingContext.ModelMetadata.DisplayName);\n\n bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);\n }\n }\n</code></pre>\n\n<p>In Application_Start:</p>\n\n<pre><code>ModelBinders.Binders.DefaultBinder = new AppModelBinder();\n</code></pre>\n\n<p>Note that it works only for form fields. Dangerous value not passed to controller model, but stored in ModelState and can be redisplayed on form with error message. </p>\n\n<p>Dangerous chars in URL may be handled this way:</p>\n\n<pre><code>private void Application_Error(object sender, EventArgs e)\n{\n Exception exception = Server.GetLastError();\n HttpContext httpContext = HttpContext.Current;\n\n HttpException httpException = exception as HttpException;\n if (httpException != null)\n {\n RouteData routeData = new RouteData();\n routeData.Values.Add("controller", "Error");\n var httpCode = httpException.GetHttpCode();\n switch (httpCode)\n {\n case (int)HttpStatusCode.BadRequest /* 400 */:\n if (httpException.Message.Contains("Request.Path"))\n {\n httpContext.Response.Clear();\n RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);\n requestContext.RouteData.Values["action"] ="InvalidUrl";\n requestContext.RouteData.Values["controller"] ="Error";\n IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();\n IController controller = factory.CreateController(requestContext, "Error");\n controller.Execute(requestContext);\n httpContext.Server.ClearError();\n Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;\n }\n break;\n }\n }\n}\n</code></pre>\n\n<p>ErrorController: </p>\n\n<pre><code>public class ErrorController : Controller\n {\n public ActionResult InvalidUrl()\n {\n return View();\n }\n} \n</code></pre>\n'}, {'answer_id': 36721339, 'author': 'Voigt', 'author_id': 6166500, 'author_profile': 'https://Stackoverflow.com/users/6166500', 'pm_score': 1, 'selected': False, 'text': '<p>Use the <code>Server.HtmlEncode("yourtext");</code></p>\n'}, {'answer_id': 41679015, 'author': 'Peter', 'author_id': 58553, 'author_profile': 'https://Stackoverflow.com/users/58553', 'pm_score': 1, 'selected': False, 'text': '<p>For those of us still stuck on webforms I found the following solution that enables you to only disable the validation on one field! (I would hate to disable it for the whole page.)</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Public Class UnvalidatedTextBox\n Inherits TextBox\n Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean\n Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)\n End Function\nEnd Class\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>public class UnvalidatedTextBox : TextBox\n{\n protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)\n {\n return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);\n }\n}\n</code></pre>\n\n<p>Now just use <code><prefix:UnvalidatedTextBox id="test" runat="server" /></code> instead of <code><asp:TextBox</code>, and it should allow all characters (this is perfect for password fields!)</p>\n'}, {'answer_id': 48480067, 'author': 'dpant', 'author_id': 313935, 'author_profile': 'https://Stackoverflow.com/users/313935', 'pm_score': 1, 'selected': False, 'text': '<p>Last but not least, please note ASP.NET Data Binding controls automatically <strong>encode</strong> values during data binding. This changes the default behavior of all ASP.NET controls (TextBox, Label etc) contained in the <code>ItemTemplate</code>. The following sample demonstrates (<code>ValidateRequest</code> is set to false):</p>\n\n<p><strong>aspx</strong></p>\n\n<pre><code><%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication17._Default" %> <html> <body>\n <form runat="server">\n <asp:FormView ID="FormView1" runat="server" ItemType="WebApplication17.S" SelectMethod="FormView1_GetItem">\n <ItemTemplate>\n <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>\n <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />\n <asp:Label ID="Label1" runat="server" Text="<%#: Item.Text %>"></asp:Label>\n <asp:TextBox ID="TextBox2" runat="server" Text="<%#: Item.Text %>"></asp:TextBox>\n </ItemTemplate>\n </asp:FormView>\n </form> \n</code></pre>\n\n<p> \n</p>\n\n<p><strong>code behind</strong></p>\n\n<pre><code>public partial class _Default : Page\n{\n S s = new S();\n\n protected void Button1_Click(object sender, EventArgs e)\n {\n s.Text = ((TextBox)FormView1.FindControl("TextBox1")).Text;\n FormView1.DataBind();\n }\n\n public S FormView1_GetItem(int? id)\n {\n return s;\n }\n}\n\npublic class S\n{\n public string Text { get; set; }\n}\n</code></pre>\n\n<ol>\n<li>Case submit value: <code>&#39;</code></li>\n</ol>\n\n<p><code>Label1.Text</code> value: <code>&#39;</code></p>\n\n<p><code>TextBox2.Text</code> value: <code>&amp;#39;</code></p>\n\n<ol start="2">\n<li>Case submit value: <code><script>alert(\'attack!\');</script></code></li>\n</ol>\n\n<p><code>Label1.Text</code> value: <code><script>alert(\'attack!\');</script></code></p>\n\n<p><code>TextBox2.Text</code> value: <code>&lt;script&gt;alert(&#39;attack!&#39;);&lt;/script&gt;</code></p>\n'}, {'answer_id': 49307591, 'author': 'KiranC', 'author_id': 8167813, 'author_profile': 'https://Stackoverflow.com/users/8167813', 'pm_score': 0, 'selected': False, 'text': '<p>In .Net 4.0 and onwards, which is the usual case, put the following setting in system.web</p>\n\n<pre><code><system.web>\n <httpRuntime requestValidationMode="2.0" />\n</code></pre>\n'}, {'answer_id': 49575929, 'author': 'Chris Catignani', 'author_id': 3072350, 'author_profile': 'https://Stackoverflow.com/users/3072350', 'pm_score': 2, 'selected': False, 'text': '<p>I see there\'s a lot written about this...and I didn\'t see this mentioned.\nThis has been available since .NET Framework 4.5</p>\n<p>The <a href="https://msdn.microsoft.com/en-us/library/system.web.ui.control.validaterequestmode.aspx" rel="nofollow noreferrer">ValidateRequestMode</a> setting for a control is a great option.\nThis way the other controls on the page are still protected.\nNo web.config changes needed.</p>\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n txtMachKey.ValidateRequestMode = ValidateRequestMode.Disabled;\n }\n</code></pre>\n'}, {'answer_id': 49639591, 'author': 'Magnus', 'author_id': 1765710, 'author_profile': 'https://Stackoverflow.com/users/1765710', 'pm_score': 2, 'selected': False, 'text': '<p><strong>A solution</strong></p>\n\n<p>I don\'t like to turn off the post validation (validateRequest="false"). On the other hand it is not acceptable that the application crashes just because an innocent user happens to type <code><x</code> or something. </p>\n\n<p>Therefore I wrote a client side javascript function (xssCheckValidates) that makes a preliminary check. This function is called when there is an attempt to post the form data, like this:</p>\n\n<pre><code><form id="form1" runat="server" onsubmit="return xssCheckValidates();">\n</code></pre>\n\n<p>The function is quite simple and could be improved but it is doing its job.</p>\n\n<p>Please notice that the purpose of this is not to protect the system from hacking, it is meant to protect the users from a bad experience. The request validation done at the server is still turned on, and that is (part of) the protection of the system (to the extent it is capable of doing that). </p>\n\n<p>The reason i say "part of" here is because I have heard that the built in request validation might not be enough, so other complementary means might be necessary to have full protection. But, again, the javascript function I present here has <em>nothing</em> to do with protecting the system. It is <em>only</em> meant to make sure the users will not have a bad experience.</p>\n\n<p>You can try it out here:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code> function xssCheckValidates() {\r\n var valid = true;\r\n var inp = document.querySelectorAll(\r\n "input:not(:disabled):not([readonly]):not([type=hidden])" +\r\n ",textarea:not(:disabled):not([readonly])");\r\n for (var i = 0; i < inp.length; i++) {\r\n if (!inp[i].readOnly) {\r\n if (inp[i].value.indexOf(\'<\') > -1) {\r\n valid = false;\r\n break;\r\n }\r\n if (inp[i].value.indexOf(\'&#\') > -1) {\r\n valid = false;\r\n break;\r\n }\r\n }\r\n }\r\n if (valid) {\r\n return true;\r\n } else {\r\n alert(\'In one or more of the text fields, you have typed\\r\\nthe character "<" or the character sequence "&#".\\r\\n\\r\\nThis is unfortunately not allowed since\\r\\nit can be used in hacking attempts.\\r\\n\\r\\nPlease edit the field and try again.\');\r\n return false;\r\n }\r\n }</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return xssCheckValidates();" >\r\n Try to type < or &# <br/>\r\n <input type="text" /><br/>\r\n <textarea></textarea>\r\n <input type="submit" value="Send" />\r\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 50174136, 'author': 'figolu', 'author_id': 3160060, 'author_profile': 'https://Stackoverflow.com/users/3160060', 'pm_score': 2, 'selected': False, 'text': '<p>I know this question is about form posting, but I would like to add some details for people who received this error on others circumstances. It could also occur on a handler used to implement a web service. </p>\n\n<p>Suppose your web client sends POST or PUT requests using ajax and sends either json or xml text or raw data (a file content) to your web service. Because your web service does not need to get any information from a Content-Type header, your JavaScript code did not set this header to your ajax request. But if you do not set this header on a POST/PUT ajax request, Safari may add this header: "Content-Type: application/x-www-form-urlencoded". I observed that on Safari 6 on iPhone, but others Safari versions/OS or Chrome may do the same. So when receiving this Content-Type header some part of .NET Framework assume the request body data structure corresponds to an html form posting while it does not and rose an HttpRequestValidationException exception. First thing to do is obviously to always set Content-Type header to anything but a form MIME type on a POST/PUT ajax request even it is useless to your web service.</p>\n\n<p>I also discovered this detail:<br>\nOn these circumstances, the HttpRequestValidationException exception is rose when your code tries to access HttpRequest.Params collection. But surprisingly, this exception is not rose when it accesses HttpRequest.ServerVariables collection. This shows that while these two collections seem to be nearly identical, one accesses request data through security checks and the other one does not.</p>\n'}, {'answer_id': 51490934, 'author': 'Wahid Masud', 'author_id': 5538471, 'author_profile': 'https://Stackoverflow.com/users/5538471', 'pm_score': 3, 'selected': False, 'text': '<p>For those who are not using model binding, who are extracting each parameter from the Request.Form, who are sure the input text will cause no harm, there is another way. Not a great solution but it will do the job. </p>\n\n<p>From client side, encode it as uri then send it.<br>\ne.g: </p>\n\n<pre><code>encodeURIComponent($("#MsgBody").val()); \n</code></pre>\n\n<p>From server side, accept it and decode it as uri.<br>\ne.g: </p>\n\n<pre><code>string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?\nSystem.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Form["MsgBody"]) : \nnull; \n</code></pre>\n\n<p>or </p>\n\n<pre><code>string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?\nSystem.Uri.UnescapeDataString(HttpContext.Current.Request.Form["MsgBody"]) : \nnull; \n</code></pre>\n\n<p>please look for the differences between <code>UrlDecode</code> and <code>UnescapeDataString</code></p>\n'}, {'answer_id': 53590303, 'author': 'maozx', 'author_id': 1516208, 'author_profile': 'https://Stackoverflow.com/users/1516208', 'pm_score': 3, 'selected': False, 'text': '<p>in my case, using asp:Textbox control (Asp.net 4.5), instead of setting the all page for <code>validateRequest="false"</code> \ni used </p>\n\n<pre><code><asp:TextBox runat="server" ID="mainTextBox"\n ValidateRequestMode="Disabled"\n ></asp:TextBox>\n</code></pre>\n\n<p>on the Textbox that caused the exception.</p>\n'}, {'answer_id': 61640372, 'author': 'Sanjeev Singh', 'author_id': 3288863, 'author_profile': 'https://Stackoverflow.com/users/3288863', 'pm_score': 0, 'selected': False, 'text': '<p><strong>How to fix this issue for AjaxExtControls in ASP.NET 4.6.2:</strong></p>\n\n<p>We had the same problem with AjaxExtControls rich text editor. This issue started right after upgrading from .NET 2.0 to .NET 4.5. I looked at all SOF answers but could not find a solution that does not compromise with the security provided by .NET 4.5.</p>\n\n<p><strong>Fix 1(Not Recommended as it can degrade application security)</strong> : I tested after changing this attribute in \n<code>requestValidationMode = "2.0</code> and it worked but I was concerned about the security features. So this is fix is like degrading the security for entire application.</p>\n\n<p><strong>Fix 2 (Recommended):</strong> Since this issue was only occurring with one of AjaxExtControl, I was finally able to solve this issue using the simple code below:</p>\n\n<pre><code>editorID.value = editorID.value.replace(/>/g, "&gt;");\neditorID.value = editorID.value.replace(/</g, "&lt;");\n</code></pre>\n\n<p>This code is executed on client side (javascript) before sending the request to server. Note that the editorID is not the ID that we have on our html/aspx pages but it is the id of the rich text editor that AjaxExtControl internally uses.</p>\n'}, {'answer_id': 67008025, 'author': 'syntap', 'author_id': 2108172, 'author_profile': 'https://Stackoverflow.com/users/2108172', 'pm_score': 0, 'selected': False, 'text': '<p>I have a Web Forms application that has had this issue for a text box comments field, where users sometimes pasted email text, and the "<" and ">" characters from email header info would creep in there and throw this exception.</p>\n<p>I addressed the issue from another angle... I was already using Ajax Control Toolkit, so I was able to use a FilteredTextBoxExtender to prevent those two characters from entry in the text box. A user copy-pasting text will then get what they were expecting, minus those characters.</p>\n<pre><code><asp:TextBox ID="CommentsTextBox" runat="server" TextMode="MultiLine"></asp:TextBox>\n<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server" TargetControlID="CommentsTextBox" filterMode="InvalidChars" InvalidChars="<>" />\n</code></pre>\n'}, {'answer_id': 70332576, 'author': 'Colin', 'author_id': 150342, 'author_profile': 'https://Stackoverflow.com/users/150342', 'pm_score': 0, 'selected': False, 'text': "<p>None of the answers worked for me. Then I discovered that if I removed the following code I could get it to work:</p>\n<pre><code>//Register action filter via Autofac rather than GlobalFilters to allow dependency injection\nbuilder.RegisterFilterProvider();\nbuilder.RegisterType<OfflineActionFilter>()\n .AsActionFilterFor<Controller>()\n .InstancePerLifetimeScope();\n</code></pre>\n<p>I can only conclude that something in Autofac's RegisterFilterProvider breaks or overrides the validateRequest attribute</p>\n"}, {'answer_id': 70866955, 'author': 'jcs', 'author_id': 2526059, 'author_profile': 'https://Stackoverflow.com/users/2526059', 'pm_score': 0, 'selected': False, 'text': '<p>Even after adding <code><httpRuntime requestValidationMode="2.0"></code> to web.config I still kept getting the error in an application that uses WIF for authentication.<br>\nWhat solved for me was adding <code><sessionState mode="InProc" cookieless="UseUri"/></code> inside the <code><system.web></code> element.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3263/'] |
81,994 | <p>Is is possible to get login credentials such as name/id if user does login by OpenId?</p>
| [{'answer_id': 82007, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 1, 'selected': False, 'text': '<p>You will not get their actual username (or password), but you will get their OpenID wich is unique.</p>\n'}, {'answer_id': 82018, 'author': 'Mat Mannion', 'author_id': 6282, 'author_profile': 'https://Stackoverflow.com/users/6282', 'pm_score': 4, 'selected': True, 'text': '<p>There are two accepted methods for retrieving these kind of things by OpenID: SReg and Attribute Exchange (AX). Both of these are extensions to the standard OpenID specification; SReg is the older of the two and specifies a set of fields that can be requested and sent with authentication, whereas AX allows requesting of any attribute.</p>\n\n<p>Both of the specification documents are pretty concise on how they work, although it\'s difficult to guage what the standard "names" are for attributes to be requested from AX. Usually, servers tend to implement the SReg names.</p>\n\n<p><a href="http://openid.net/specs/openid-simple-registration-extension-1_0.html" rel="noreferrer">OpenID Simple Registration Extension Specification 1.0</a></p>\n\n<p><a href="http://openid.net/specs/openid-attribute-exchange-1_0.html" rel="noreferrer">OpenID Attribute Exchange Specification 1.0 Final</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/81994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15476/'] |
82,003 | <p>I have a remote DB2 database that I'm accessing through ODBC. When I have a query like</p>
<pre><code>SELECT t.foo, t.bar, t.problemcolumn
FROM problemtable t
WHERE t.bar < 60;
</code></pre>
<p>it works like a charm, so the table and columns obviously exist.</p>
<p>But if I specify the problem column in the WHERE clause</p>
<pre><code>SELECT t.foo, t.bar, t.problemcolumn
FROM problemtable t
WHERE t.problemcolumn = 'x'
AND t.bar < 60;
</code></pre>
<p>it gives me an error </p>
<pre><code>Table "problemtable" does not exist.
</code></pre>
<p>What could possibly be the reason for this? I've double checked the spellings and I can trigger the problem just by including the problemcolumn in the where-clause.</p>
| [{'answer_id': 82070, 'author': 'Per Hornshøj-Schierbeck', 'author_id': 11619, 'author_profile': 'https://Stackoverflow.com/users/11619', 'pm_score': 2, 'selected': False, 'text': "<p>Sorry for the obvious answer, but does the problemtable exist? Your code looks like pseudo code because of the table/column names, but be sure to double check your spelling. It's not a view which might even consist of joined tables across different databases/servers?</p>\n"}, {'answer_id': 82194, 'author': 'bastos.sergio', 'author_id': 12772, 'author_profile': 'https://Stackoverflow.com/users/12772', 'pm_score': 2, 'selected': False, 'text': "<p>What is the actual SQL you're using? I don't see anything wrong with the example you put up. Try looking for misplaced commas and/or quotes that could be triggering the error.</p>\n"}, {'answer_id': 82283, 'author': 'Swati', 'author_id': 12682, 'author_profile': 'https://Stackoverflow.com/users/12682', 'pm_score': 0, 'selected': False, 'text': "<p>Does it work with just:</p>\n\n<pre><code>SELECT t.foo, t.bar, t.problemcolumn\nFROM problemtable t\nWHERE t.problemcolumn = 'x'\n</code></pre>\n"}, {'answer_id': 93478, 'author': 'boes', 'author_id': 17746, 'author_profile': 'https://Stackoverflow.com/users/17746', 'pm_score': 0, 'selected': False, 'text': "<p>Please run the next SQL statements. For me it works fine. If you still have this strange error, it will be a DB2 bug. I had some problems once with copying code from UNIX editors into Windows and vice versa. The SQL would not run, although it looked ok. Retyping the statement fixed my problem then.</p>\n\n<p>create table problemtable (\n foo varchar(10),\n bar int,\n problemcolumn varchar(10) \n);</p>\n\n<p>SELECT t.foo, t.bar, t.problemcolumn \n FROM problemtable t\n WHERE t.bar < 60;</p>\n\n<p>SELECT t.foo, t.bar, t.problemcolumn\n FROM problemtable t\n WHERE t.problemcolumn = 'x'\n AND t.bar < 60;</p>\n"}, {'answer_id': 163333, 'author': 'Fuangwith S.', 'author_id': 24550, 'author_profile': 'https://Stackoverflow.com/users/24550', 'pm_score': 0, 'selected': False, 'text': '<p>It think it should be work in DB2.\nWhat is your font-ent software?</p>\n'}, {'answer_id': 1107682, 'author': 'SO User', 'author_id': 39289, 'author_profile': 'https://Stackoverflow.com/users/39289', 'pm_score': 0, 'selected': False, 'text': '<p>DB2 sometimes gives misleading errors. You can try these troubleshooting steps:</p>\n\n<ol>\n<li>Try executing the code through\nDBArtisan or DB2 Control Center and\nsee if you get a proper result/ error\nmessage.</li>\n<li>Try using schema_name.problemtable\ninstead of just problemtable</li>\n<li>Make sure that problemcolumn is of\nthe same data type that you are\ncomparing it with.</li>\n</ol>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2087/'] |
82,008 | <p>I have xml where some of the element values are unicode characters. Is it possible to represent this in an ANSI encoding?</p>
<p>E.g.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xml>
<value>受</value>
</xml>
</code></pre>
<p>to</p>
<pre><code><?xml version="1.0" encoding="Windows-1252"?>
<xml>
<value>&#27544;</value>
</xml>
</code></pre>
<p>I deserialize the XML and then attempt to serialize it using XmlTextWriter specifying the Default encoding (Default is Windows-1252). All the unicode characters end up as question marks. I'm using VS 2008, C# 3.5</p>
| [{'answer_id': 82021, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 2, 'selected': False, 'text': '<p>If I understand the question, then yes. You just need a <code>;</code> after the <code>27544</code>:</p>\n\n<pre><code><?xml version="1.0" encoding="Windows-1252"?>\n<xml>\n<value>&#27544;</value>\n</xml>\n</code></pre>\n\n<p>Or are you wondering how to generate this XML programmatically? If so, what language/environment are you working in?</p>\n'}, {'answer_id': 82413, 'author': 'Richard Nienaber', 'author_id': 9539, 'author_profile': 'https://Stackoverflow.com/users/9539', 'pm_score': 4, 'selected': True, 'text': '<p>Okay I tested it with the following code:</p>\n\n<pre><code> string xml = "<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?><xml><value>受</value></xml>";\n\n XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Default };\n MemoryStream ms = new MemoryStream();\n using (XmlWriter writer = XmlTextWriter.Create(ms, settings))\n XElement.Parse(xml).WriteTo(writer);\n\n string value = Encoding.Default.GetString(ms.ToArray());\n</code></pre>\n\n<p>And it correctly escaped the unicode character thus:</p>\n\n<pre><code><?xml version="1.0" encoding="Windows-1252"?><xml><value>&#x53D7;</value></xml>\n</code></pre>\n\n<p>I must be doing something wrong somewhere else. Thanks for the help.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9539/'] |
82,022 | <p><strong>Do <em>you</em> write consumer desktop applications with .NET languages?</strong> If so what type?</p>
<p>My impression is that most consumer desktop applications are still native compiled applications in C, C++ and the like.</p>
<p>Whilst .NET languages are growing in up take and popularity, do these new breed of applications ever break out of the enterprise & web domain to become high street consumer applications?</p>
<p>For example look at your desktop now? how many applications are written in .NET languages, Firefox? Microsoft Office? Thunderbird? iTunes? Microsoft Visual Studio?</p>
<p>My company develops high end CAD/CAE applications we leverage new technology but our core development is still done with C++.</p>
| [{'answer_id': 82038, 'author': 'Per Hornshøj-Schierbeck', 'author_id': 11619, 'author_profile': 'https://Stackoverflow.com/users/11619', 'pm_score': 2, 'selected': False, 'text': "<p>That's a shame. The only reason to hold back on desktop development with .net is the requirement of the .net framework on the desktop machine, but imho that is a small price to pay for the bennefits you get when being able to work in the .net environment.</p>\n"}, {'answer_id': 82063, 'author': 'Giovanni Galbo', 'author_id': 4050, 'author_profile': 'https://Stackoverflow.com/users/4050', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe you are seeing this because many of the popular desktop apps have a code base older than 2001?</p>\n\n<p>Edit: I should probably have said older than 2003 or 2004...I doubt anyone would have started a major desktop app the first year or two of the .NET release.</p>\n'}, {'answer_id': 82078, 'author': 'Steve', 'author_id': 15526, 'author_profile': 'https://Stackoverflow.com/users/15526', 'pm_score': 0, 'selected': False, 'text': '<p>Well there are apps such as \n<a href="http://www.gnome.org/projects/tomboy/" rel="nofollow noreferrer">Tomboy</a> and <a href="http://beagle-project.org/Main_Page" rel="nofollow noreferrer">Beagle</a> which are available as part of some Linux distros so I\'m not sure if they count as high street consumer applications.\nCome to think of it I\'m not really that aware of any other "non-enterprise" applications written in .NET languages.</p>\n'}, {'answer_id': 82090, 'author': 'Morten Christiansen', 'author_id': 4055, 'author_profile': 'https://Stackoverflow.com/users/4055', 'pm_score': 2, 'selected': False, 'text': "<p>As long as you don't need über performance, I can't see any reason not to use .NET. With the new super small redistriutables you can include a .net installer that takes up a couple hundred KB.</p>\n\n<p>I would say that the productivity gains of a modern, garbage collected language should only make C++ a good option if you already have the developers who are proficient in that language or there are specific technical requirements which makes it necessary or if the clients' machines are locked down such that the .net platform cannot be used.</p>\n\n<p>While I'm not a part of the working force yet (i.e. I am a student), everything I can get away with I write in C#. Nothing else I've tried comes close to the level of efficiency and cleanness afforded by this language (and which provides all the productivity features of Visuall Studio).</p>\n"}, {'answer_id': 82094, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 3, 'selected': False, 'text': '<p>As mentioned, I know of Tomboy, Beagle, and in addition, F-Spot. All come as part of most linux distros. Paint.NET is another app.</p>\n'}, {'answer_id': 82105, 'author': 'Giovanni Galbo', 'author_id': 4050, 'author_profile': 'https://Stackoverflow.com/users/4050', 'pm_score': 0, 'selected': False, 'text': '<p>Not the traditional desktop app, but the ATI Catalyst Control Center is .NET based.</p>\n'}, {'answer_id': 82168, 'author': 'GvS', 'author_id': 11492, 'author_profile': 'https://Stackoverflow.com/users/11492', 'pm_score': 0, 'selected': False, 'text': '<p>Actually, I have found some applications that require .Net on my desktop. </p>\n\n<p>The most famous is Paint.Net, but also amongst them is "Catalyst Control Center", delivered with my ATI graphics card.</p>\n\n<p>And naturally, our company is writing our own desktop .Net application. Our target audience are business users.</p>\n'}, {'answer_id': 82211, 'author': 'Martin Marconcini', 'author_id': 2684, 'author_profile': 'https://Stackoverflow.com/users/2684', 'pm_score': 4, 'selected': True, 'text': '<p>I built and maintain a big desktop application written in .NET (1.1, 2.0 now). The application is for Dentists and it works by making use of the Ink technology found in the MIcrosoft.Ink namespace in the TabletPC SDK. \nSome dentists use Tablet PCs to make things easier and leverage the power of that technology.</p>\n\n<p>On the other hand, since I find Windows UI not good looking (XP/Vista) and find that every application looks the same and inconsistent, I wrote my own GDI+ library of controls and while respecting more or less the "windows UI guidelines", I came up with very nice buttons and other UI elements that make my App look "way better" than any other "normal" windows application. </p>\n\n<p>We run at full screen (maximixed, no controls, no app bar), but we do this because it\'s a very <em>specific</em> application used in machines <em>dedicated</em> to the task. Dental clinics don\'t use Microsoft Excel and ALT-TAB to our application. The application works like an "ATM", touch touch, done. Very simple. It has been a success in Europe where I am.</p>\n\n<p>So I have to say that I am glad that the app is <strong>not</strong> a web application, because when we started, the .NET GDI+ for Windows Forms was way superior to anything that WEB could have offered; even today, Ajax is not able to reproduce the full desktop experience (not that it should but…).</p>\n\n<p>Java had an ugly UI back then (don\'t know now) so we elected .NET and used C# ever since.</p>\n\n<p>Desktop applications are not going to die anytime soon, some things still cannot be reproduced inside a webrowser. </p>\n\n<p>I considered Java, C++, Delphi among others before starting with this six years ago. None offered the simplicity and power of c#.NET with little disadvantages (like the Framework that nobody had back then). Now, every windows box <em>will surely</em> have the .NET Framework 2.0.</p>\n\n<p>Again, my consumer application is very specific and targeted towards a closed market, but we don\'t have anything <em>against</em> .NET.</p>\n'}, {'answer_id': 82263, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 0, 'selected': False, 'text': "<p>There probably won't be a whole lot of winforms apps in the traditional sense being written, but the next version of both windows live messenger will be written in windows presnetation foundation and I think this is what the trend will be towards.</p>\n\n<p>Windows Media Centre was written in C# which is pretty impressive, but having said that, it's not your traditional winforms app either.</p>\n"}, {'answer_id': 82267, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>TechSmith's Jing is .NET, and in fact it is WPF so it is 3.5, bleeding edge .NET.</p>\n"}, {'answer_id': 82289, 'author': 'Captain Toad', 'author_id': 15664, 'author_profile': 'https://Stackoverflow.com/users/15664', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve noticed that in <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow noreferrer">Process Explorer</a> more and more of my desktop apps are being highlighted in yellow (meaning they\'re .Net). As mentioned above, ATI\'s Catalyst is, Windows Live Mesh, many games have .Net update or config engines, as well as most of the bits I write that haven\'t quite made it into the public arena yet (because I don\'t have as much time as I\'d like for coding & testing). Also, large parts of Visual Studio ARE .NET - at least according to Process Explorer.</p>\n\n<p>I think that, as somebody mentioned above, there are a lot of desktop apps already out there that have older code-bases which their owners won\'t convert unless there\'s some fantastic value in doing so.</p>\n'}, {'answer_id': 82318, 'author': 'Oliver Mellet', 'author_id': 12001, 'author_profile': 'https://Stackoverflow.com/users/12001', 'pm_score': 0, 'selected': False, 'text': "<p>Almost all the client programs written here where I work are in .NET; it's a terrific platform for business applications. Having said that, most of the programs out there that .NET would be a good target for are being deployed as web applications instead; the rest are typically graphical and cpu-intensive applications that are typically implemented in c++ for performance reasons. For the same reason, you don't see too many desktop applications written in java, either.</p>\n"}, {'answer_id': 82458, 'author': 'Łukasz Sowa', 'author_id': 347616, 'author_profile': 'https://Stackoverflow.com/users/347616', 'pm_score': 0, 'selected': False, 'text': "<p>Most of you refer to open source. I agree, there are some projects using .NET (I'm using RSSBandit for example) but they doesn't matter (mostly). But what about enterprise apps? Recently I've written app which is like MS Surface and it is for advertising purposes. Before this I had to write an app to maintain warehouse for example. Something different? In times of WinForms I've written an app to support ebay-like page. Do you need any more?</p>\n\n<p>Personally, I think that .NET is widely use in business (which you don't see everyday) and it's not used by open source (why? I don't know, maybe contributors hate MS?). However, I also think that it will be changing towards .NET, especially with the next releases of the Windows platform. And, I almost forgot - installing .NET framework is not a problem, be serious, users are not that stupid and lazy!</p>\n\n<p>And it's true that desktop is loosing it's mojo to web environment, but it will never die ;)</p>\n"}, {'answer_id': 180852, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 2, 'selected': False, 'text': '<p>Visual Studio (at least 2008) IS written in .NET</p>\n'}, {'answer_id': 609829, 'author': 'RBerteig', 'author_id': 68204, 'author_profile': 'https://Stackoverflow.com/users/68204', 'pm_score': 2, 'selected': False, 'text': "<p>Intuit's TurboTax 2007 and 2008 are both written in .NET. Unlike the demo of a niche-market video edit tool I griped about in a comment to another answer, it actually installed completely cleanly and without incident (including its self-updater trick) on my slightly aging XP box here at home.</p>\n\n<p>This year's UI is substantially different from past years, and for the most part its better. Since the transition to .NET seems to have happened last year without changing the UI much at all, the new UI can't be blamed on (or credited to) the switch to .NET.</p>\n\n<p>I'm just a user, and have no idea what motivated their dev team to switch.</p>\n\n<p>I do think that is the first retail software package I've caught in the wild that was clearly based on .NET.</p>\n"}, {'answer_id': 1559508, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 0, 'selected': False, 'text': '<p>Microsoft InfoPath - part of Microsoft Office is also written in .NET</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387/'] |
82,047 | <p>I have a requirement to validate an incoming file against an XSD. Both will be on the server file system.<br /></p>
<p>I've looked at <code>dbms_xmlschema</code>, but have had issues getting it to work.</p>
<p>Could it be easier to do it with some Java?<br />What's the simplest class I could put in the database?</p>
<p>Here's a simple example:</p>
<pre><code>DECLARE
v_schema_url VARCHAR2(200) := 'http://www.example.com/schema.xsd';
v_blob bLOB;
v_clob CLOB;
v_xml XMLTYPE;
BEGIN
begin
dbms_xmlschema.deleteschema(v_schema_url);
exception
when others then
null;
end;
dbms_xmlschema.registerSchema(schemaURL => v_schema_url,
schemaDoc => '
<xs:schema targetNamespace="http://www.example.com"
xmlns:ns="http://www.example.com"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified" version="3.0">
<xs:element name="something" type="xs:string"/>
</xs:schema>',
local => TRUE);
v_xml := XMLTYPE.createxml('<something xmlns="http://www.xx.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com/schema.xsd">
data
</something>');
IF v_xml.isschemavalid(v_schema_url) = 1 THEN
dbms_output.put_line('valid');
ELSE
dbms_output.put_line('not valid');
END IF;
END;
</code></pre>
<p>This generates the following error:</p>
<pre><code>ORA-01031: insufficient privileges
ORA-06512: at "XDB.DBMS_XDBZ0", line 275
ORA-06512: at "XDB.DBMS_XDBZ", line 7
ORA-06512: at line 1
ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 3
ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 14
ORA-06512: at line 12
</code></pre>
| [{'answer_id': 83488, 'author': 'Adam Hawkes', 'author_id': 6703, 'author_profile': 'https://Stackoverflow.com/users/6703', 'pm_score': -1, 'selected': False, 'text': "<p>If I remember correctly, that error message is given when XDB (Oracle's XML DataBase package) is not properly installed. Have the DBA check this out.</p>\n"}, {'answer_id': 178790, 'author': 'Jim Hudson', 'author_id': 8051, 'author_profile': 'https://Stackoverflow.com/users/8051', 'pm_score': 0, 'selected': False, 'text': '<p>Once you get past the install issues, there are challenges in some Oracle versions when the schemas get big, particularly when you have schemas that include other schemas. I know we had that issue in 9.2, not sure about 10.2 or 11.</p>\n\n<p>For small schemas like your example, though, it should just work.</p>\n'}, {'answer_id': 5274406, 'author': 'Tomasz Żuk', 'author_id': 655526, 'author_profile': 'https://Stackoverflow.com/users/655526', 'pm_score': 2, 'selected': False, 'text': '<p>You must have <code>ALTER SESSION</code> privilege granted in order to register a schema.</p>\n'}, {'answer_id': 6367816, 'author': 'user272735', 'author_id': 272735, 'author_profile': 'https://Stackoverflow.com/users/272735', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Update</strong></p>\n\n<p>XML Schema registration requires following privileges:</p>\n\n<pre><code>grant alter session to <USER>;\ngrant create type to <USER>; /* required when gentypes => true */\ngrant create table to <USER>; /* required when gentables => true */\n</code></pre>\n\n<p>For some reason it\'s not enough if those privileges are granted indirectly via roles, but the privileges need <em>to be granted directly to schema/user</em>.</p>\n\n<p><strong>Original Answer</strong></p>\n\n<p>I have also noticed that default values of parameters <code>gentables</code> and <code>gentypes</code> raise <code>insufficient privileges</code> exception. Probably I\'m just lacking of some privileges to use those features, but at the moment I don\'t have a good understanding what they do. I\'m just happy to disable them and validation seems to work fine.</p>\n\n<p>I\'m running on Oracle Database 11g Release 11.2.0.1.0</p>\n\n<h2>gentypes => true, gentables => true</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true\n --gentypes => false,\n --gentables => false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55\nORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159\nORA-06512: at "JANI.XML_VALIDATOR", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => false, gentables => true</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n gentypes => false\n --gentables => false\n );\n\nORA-31084: error while creating table "JANI"."example873_TAB" for element "example"\nORA-01031: insufficient privileges\nORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55\nORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159\nORA-06512: at "JANI.XML_VALIDATOR", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => true, gentables => false</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n --gentypes => false\n gentables => false\n );\n\nORA-01031: insufficient privileges\nORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 55\nORA-06512: at "XDB.DBMS_XMLSCHEMA", line 159\nORA-06512: at "JANI.XML_VALIDATOR", line 38\nORA-06512: at line 7\n</code></pre>\n\n<h2>gentypes => false, gentables => false</h2>\n\n<pre><code>dbms_xmlschema.registerschema(schemaurl => name,\n schemadoc => xmltype(schema),\n local => true,\n gentypes => false,\n gentables => false\n );\n\nPL/SQL procedure successfully completed.\n</code></pre>\n'}, {'answer_id': 12053644, 'author': 'Pierre-Gilles Levallois', 'author_id': 2162529, 'author_profile': 'https://Stackoverflow.com/users/2162529', 'pm_score': 2, 'selected': False, 'text': '<p>here is a piece of code that works for me.\nuser272735\'s answer is right, I wrote another answer as far as I can\'t write all the code in a comment (too long).</p>\n\n<pre><code>/* Formatted on 21/08/2012 12:52:47 (QP5 v5.115.810.9015) */\nDECLARE\n -- Local variables here\n res BOOLEAN;\n tempXML XMLTYPE;\n xmlDoc XMLTYPE;\n xmlSchema XMLTYPE;\n schemaURL VARCHAR2 (256) := \'testcase.xsd\';\nBEGIN\n dbms_xmlSchema.deleteSchema (schemaURL, 4);\n -- Test statements here\n xmlSchema :=\n xmlType(\'<?xml version="1.0" encoding="UTF-8"?>\n<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdb="http://xmlns.oracle.com/xdb"\nelementFormDefault="qualified" attributeFormDefault="unqualified">\n<xs:element name="root" xdb:defaultTable="ROOT_TABLE">\n<xs:complexType>\n<xs:sequence>\n<xs:element name="child1"/>\n<xs:element name="child2"/>\n</xs:sequence>\n</xs:complexType>\n</xs:element>\n</xs:schema>\n\');\n -- http://stackoverflow.com/questions/82047/validating-xml-files-against-schema-in-oracle-pl-sql\n dbms_xmlschema.registerschema(schemaurl => schemaURL,\n schemadoc => xmlSchema,\n local => true,\n gentypes => false,\n gentables => false\n );\n xmlDoc :=\n xmltype(\'<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="\'\n || schemaURL\n || \'"><child1>foo</child1><child2>bar</child2></root>\');\n xmlDoc.schemaValidate ();\n -- if we are here, xml is valid\n DBMS_OUTPUT.put_line (\'OK\');\nexception\n when others then\n DBMS_OUTPUT.put_line (SQLErrm);\nEND;\n</code></pre>\n'}, {'answer_id': 48176686, 'author': 'Robin', 'author_id': 6010174, 'author_profile': 'https://Stackoverflow.com/users/6010174', 'pm_score': 0, 'selected': False, 'text': '<p>Registering the XSD leads to creation of tables, types and triggers. Therefore you need the following grants:</p>\n\n<pre><code>grant create table to <user>;\ngrant create type to <user>;\ngrant create trigger to <user>;\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1895/'] |
82,058 | <p>Given the following JSON Date representation:</p>
<pre><code>"\/Date(1221644506800-0700)\/"
</code></pre>
<p>How do you deserialize this into it's JavaScript Date-type form?</p>
<p>I've tried using MS AJAX JavaScrioptSerializer as shown below:</p>
<pre><code>Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/")
</code></pre>
<p>However, all I get back is the literal string date.</p>
| [{'answer_id': 82244, 'author': 'Daniel', 'author_id': 6852, 'author_profile': 'https://Stackoverflow.com/users/6852', 'pm_score': 1, 'selected': False, 'text': '<p>The big number is the standard JS time</p>\n\n<pre><code>new Date(1221644506800)\n</code></pre>\n\n<p>Wed Sep 17 2008 19:41:46 GMT+1000 (EST)</p>\n'}, {'answer_id': 82377, 'author': 'Sjoerd Visscher', 'author_id': 5852, 'author_profile': 'https://Stackoverflow.com/users/5852', 'pm_score': 4, 'selected': False, 'text': '<p>A JSON value is a string, number, object, array, true, false or null. So this is just a string. There is no official way to represent dates in JSON. This syntax is from the asp.net ajax implementation. Others use the ISO 8601 format.</p>\n\n<p>You can parse it like this:</p>\n\n<pre><code>var s = "\\/Date(1221644506800-0700)\\/";\nvar m = s.match(/^\\/Date\\((\\d+)([-+]\\d\\d)(\\d\\d)\\)\\/$/);\nvar date = null;\nif (m)\n date = new Date(1*m[1] + 3600000*m[2] + 60000*m[3]);\n</code></pre>\n'}, {'answer_id': 428857, 'author': 'Kyle Jones', 'author_id': 53424, 'author_profile': 'https://Stackoverflow.com/users/53424', 'pm_score': 3, 'selected': False, 'text': '<p>The regular expression used in the ASP.net AJAX deserialize method looks for a string that looks like "/Date(1234)/" (The string itself actually needs to contain the quotes and slashes). To get such a string, you will need to escape the quote and back slash characters, so the javascript code to create the string looks like "\\"\\/Date(1234)\\/\\"".</p>\n\n<p>This will work.</p>\n\n<pre><code>Sys.Serialization.JavaScriptSerializer.deserialize("\\"\\\\/Date(1221644506800)\\\\/\\"")\n</code></pre>\n\n<p>It\'s kind of weird, but I found I had to serialize a date, then serialize the string returned from that, then deserialize on the client side once.</p>\n\n<p>Something like this.</p>\n\n<pre><code>Script.Serialization.JavaScriptSerializer jss = new Script.Serialization.JavaScriptSerializer();\nstring script = string.Format("alert(Sys.Serialization.JavaScriptSerializer.deserialize({0}));", jss.Serialize(jss.Serialize(DateTime.Now)));\nPage.ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", script, true);\n</code></pre>\n'}, {'answer_id': 959092, 'author': 'Simon_Weaver', 'author_id': 16940, 'author_profile': 'https://Stackoverflow.com/users/16940', 'pm_score': 6, 'selected': True, 'text': '<p>Provided you know the string is definitely a date I prefer to do this :</p>\n\n<pre><code> new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))\n</code></pre>\n'}, {'answer_id': 1646987, 'author': 'Alex Nolasco', 'author_id': 65694, 'author_profile': 'https://Stackoverflow.com/users/65694', 'pm_score': 2, 'selected': False, 'text': '<p>For those who don\'t want to use Microsoft Ajax, simply add a prototype function to the string class.</p>\n\n<p>E.g.</p>\n\n<pre><code> String.prototype.dateFromJSON = function () {\n return eval(this.replace(/\\/Date\\((\\d+)\\)\\//gi, "new Date($1)"));\n};\n</code></pre>\n\n<p>Don\'t want to use eval? Try something simple like</p>\n\n<pre><code>var date = new Date(parseInt(jsonDate.substr(6)));\n</code></pre>\n\n<p>As a side note, I used to think Microsoft was misleading by using this format. However, the JSON specification is not very clear when it comes to defining a way to describe dates in JSON.</p>\n'}, {'answer_id': 2654571, 'author': 'ESV', 'author_id': 150, 'author_profile': 'https://Stackoverflow.com/users/150', 'pm_score': 4, 'selected': False, 'text': '<p>Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, <a href="http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx" rel="noreferrer">described the design of the JavaScriptSerializer DateTime output</a> and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation:</p>\n\n<blockquote>\n <p>run a simple search for "\\/Date((\\d+))\\/" and replace with "new Date($1)" before the eval\n (but after validation)</p>\n</blockquote>\n\n<p>I implemented that as:</p>\n\n<pre><code>var serializedDateTime = "\\/Date(1271389496563)\\/";\ndocument.writeln("Serialized: " + serializedDateTime + "<br />");\n\nvar toDateRe = new RegExp("^/Date\\\\((\\\\d+)\\\\)/$");\nfunction toDate(s) {\n if (!s) {\n return null;\n }\n var constructor = s.replace(toDateRe, "new Date($1)");\n if (constructor == s) {\n throw \'Invalid serialized DateTime value: "\' + s + \'"\';\n }\n return eval(constructor);\n}\n\ndocument.writeln("Deserialized: " + toDate(serializedDateTime) + "<br />");\n</code></pre>\n\n<p>This is very close to the many of the other answers:</p>\n\n<ul>\n<li>Use an anchored RegEx as Sjoerd Visscher did -- don\'t forget the ^ and $.</li>\n<li>Avoid string.replace, and the \'g\' or \'i\' options on your RegEx. "/Date(1271389496563)//Date(1271389496563)/" shouldn\'t work at all.</li>\n</ul>\n'}, {'answer_id': 41367697, 'author': 'tavo', 'author_id': 3545581, 'author_profile': 'https://Stackoverflow.com/users/3545581', 'pm_score': 2, 'selected': False, 'text': '<p>Actually, momentjs supports this kind of format, you might do something like:</p>\n\n<pre><code> var momentValue = moment(value);\n\n momentValue.toDate();\n</code></pre>\n\n<p>This returns the value in a javascript date format</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9275/'] |
82,064 | <p>I have a version number of the following form:</p>
<p>version.release.modification</p>
<p>where version, release and modification are either a set of digits or the '*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing.</p>
<p>So the following are valid and parse as:</p>
<pre><code>1.23.456 = version 1, release 23, modification 456
1.23 = version 1, release 23, any modification
1.23.* = version 1, release 23, any modification
1.* = version 1, any release, any modification
1 = version 1, any release, any modification
* = any version, any release, any modification
</code></pre>
<p>But these are not valid:</p>
<pre><code>*.12
*123.1
12*
12.*.34
</code></pre>
<p>Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers?</p>
| [{'answer_id': 82104, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 4, 'selected': False, 'text': '<p>This might work:</p>\n\n<pre><code>^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$\n</code></pre>\n\n<p>At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.</p>\n\n<p>The code for retrieving the matched sequences, especially the <code>(\\.\\d+){0,2}</code> part, will depend on your particular regex library.</p>\n'}, {'answer_id': 82152, 'author': 'Paweł Hajdan', 'author_id': 9403, 'author_profile': 'https://Stackoverflow.com/users/9403', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Use regex and now you have two problems.</strong> I would split the thing on dots ("."), then make sure that each part is either a wildcard or set of digits (regex is perfect now). If the thing is valid, you just return correct chunk of the split.</p>\n'}, {'answer_id': 82205, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 8, 'selected': True, 'text': '<p>I\'d express the format as:</p>\n\n<blockquote>\n <p>"1-3 dot-separated components, each numeric except that the last one may be *"</p>\n</blockquote>\n\n<p>As a regexp, that\'s:\n</p>\n\n<pre><code>^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>[Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It\'s a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups. </p>\n\n<p>In my solution, the groups capture the <code>"."</code> characters. This can be dealt with using non-capturing groups as in ajborley\'s answer.</p>\n\n<p>Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported.</p>\n\n<p>Perl code to deal with both issues after the regexp could be something like this:</p>\n\n<pre><code>@version = ();\n@groups = ($1, $2, $3);\nforeach (@groups) {\n next if !defined;\n s/\\.//;\n push @version, $_;\n}\n($major, $minor, $mod) = (@version, "*", "*");\n</code></pre>\n\n<p>Which isn\'t really any shorter than splitting on <code>"."</code>\n]</p>\n'}, {'answer_id': 82237, 'author': 'FrankS', 'author_id': 3134, 'author_profile': 'https://Stackoverflow.com/users/3134', 'pm_score': 2, 'selected': False, 'text': '<p>Keep in mind regexp are greedy, so if you are just searching within the version number string and not within a bigger text, use ^ and $ to mark start and end of your string.\nThe regexp from Greg seems to work fine (just gave it a quick try in my editor), but depending on your library/language the first part can still match the "*" within the wrong version numbers. Maybe I am missing something, as I haven\'t used Regexp for a year or so.</p>\n\n<p>This should make sure you can only find correct version numbers:</p>\n\n<p>^(\\*|\\d+(\\.\\d+)*(\\.\\*)?)$</p>\n\n<p>edit: actually greg added them already and even improved his solution, I am too slow :)</p>\n'}, {'answer_id': 82262, 'author': 'svrist', 'author_id': 86, 'author_profile': 'https://Stackoverflow.com/users/86', 'pm_score': 3, 'selected': False, 'text': '<p>I tend to agree with split suggestion.</p>\n\n<p>Ive created a "tester" for your problem in perl</p>\n\n<pre><code>#!/usr/bin/perl -w\n\n\n@strings = ( "1.2.3", "1.2.*", "1.*","*" );\n\n%regexp = ( svrist => qr/(?:(\\d+)\\.(\\d+)\\.(\\d+)|(\\d+)\\.(\\d+)|(\\d+))?(?:\\.\\*)?/,\n onebyone => qr/^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$/,\n greg => qr/^(\\*|\\d+(\\.\\d+){0,2}(\\.\\*)?)$/,\n vonc => qr/^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$/,\n ajb => qr/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/,\n jrudolph => qr/^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$/\n );\n\n foreach my $r (keys %regexp){\n my $reg = $regexp{$r};\n print "Using $r regexp\\n";\nforeach my $s (@strings){\n print "$s : ";\n\n if ($s =~m/$reg/){\n my ($main, $maj, $min,$rev,$ex1,$ex2,$ex3) = ("any","any","any","any","any","any","any");\n $main = $1 if ($1 && $1 ne "*") ;\n $maj = $2 if ($2 && $2 ne "*") ;\n $min = $3 if ($3 && $3 ne "*") ;\n $rev = $4 if ($4 && $4 ne "*") ;\n $ex1 = $5 if ($5 && $5 ne "*") ;\n $ex2 = $6 if ($6 && $6 ne "*") ;\n $ex3 = $7 if ($7 && $7 ne "*") ;\n print "$main $maj $min $rev $ex1 $ex2 $ex3\\n";\n\n }else{\n print " nomatch\\n";\n }\n }\nprint "------------------------\\n";\n}\n</code></pre>\n\n<p>Current output:</p>\n\n<pre><code>> perl regex.pl\nUsing onebyone regexp\n1.2.3 : 1. 2. 3 any any any any\n1.2.* : 1. 2. any any any any any\n1.* : 1. any any any any any any\n* : any any any any any any any\n------------------------\nUsing svrist regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : any any any 1 2 any any\n1.* : any any any any any 1 any\n* : any any any any any any any\n------------------------\nUsing vonc regexp\n1.2.3 : 1.2. 3 any any any any any\n1.2.* : 1. 2 .* any any any any\n1.* : any any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing ajb regexp\n1.2.3 : 1 2 3 any any any any\n1.2.* : 1 2 any any any any any\n1.* : 1 any any any any any any\n* : any any any any any any any\n------------------------\nUsing jrudolph regexp\n1.2.3 : 1.2. 1. 1 2 3 any any\n1.2.* : 1.2. 1. 1 2 any any any\n1.* : 1. any any 1 any any any\n* : any any any any any any any\n------------------------\nUsing greg regexp\n1.2.3 : 1.2.3 .3 any any any any any\n1.2.* : 1.2.* .2 .* any any any any\n1.* : 1.* any .* any any any any\n* : any any any any any any any\n------------------------\n</code></pre>\n'}, {'answer_id': 82271, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 2, 'selected': False, 'text': '<pre><code>(?ms)^((?:\\d+(?!\\.\\*)\\.)+)(\\d+)?(\\.\\*)?$|^(\\d+)\\.\\*$|^(\\*|\\d+)$\n</code></pre>\n\n<p>Does exactly match your 6 first examples, and rejects the 4 others</p>\n\n<ul>\n<li>group 1: major or major.minor or \'*\'</li>\n<li>group 2 if exists: minor or *</li>\n<li>group 3 if exists: *</li>\n</ul>\n\n<p>You can remove \'(?ms)\'<br>\nI used it to indicate to this regexp to be applied on multi-lines through <a href="http://bastian-bergerhoff.com/eclipse/features/web/QuickREx/toc.html" rel="nofollow noreferrer">QuickRex</a></p>\n'}, {'answer_id': 82296, 'author': 'Duncan Smart', 'author_id': 1278, 'author_profile': 'https://Stackoverflow.com/users/1278', 'pm_score': 3, 'selected': False, 'text': '<p>Don\'t know what platform you\'re on but in .NET there\'s the System.Version class that will parse "n.n.n.n" version numbers for you.</p>\n'}, {'answer_id': 82328, 'author': 'Victor', 'author_id': 14514, 'author_profile': 'https://Stackoverflow.com/users/14514', 'pm_score': 2, 'selected': False, 'text': '<p>This matches 1.2.3.* too</p>\n\n<blockquote>\n <p>^(*|\\d+(.\\d+){0,2}(.*)?)$</p>\n</blockquote>\n\n<p>I would propose the less elegant:</p>\n\n<p>(*|\\d+(.\\d+)?(.*)?)|\\d+.\\d+.\\d+)</p>\n'}, {'answer_id': 82427, 'author': 'Andrew Borley', 'author_id': 7271, 'author_profile': 'https://Stackoverflow.com/users/7271', 'pm_score': 4, 'selected': False, 'text': "<p>Thanks for all the responses! This is ace :)</p>\n\n<p>Based on OneByOne's answer (which looked the simplest to me), I added some non-capturing groups (the '(?:' parts - thanks to VonC for introducing me to non-capturing groups!), so the groups that do capture only contain the digits or * character. </p>\n\n<pre><code>^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>Many thanks everyone!</p>\n"}, {'answer_id': 82472, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 2, 'selected': False, 'text': '<p>Another try:</p>\n\n<pre><code>^(((\\d+)\\.)?(\\d+)\\.)?(\\d+|\\*)$\n</code></pre>\n\n<p>This gives the three parts in groups 4,5,6 BUT:\nThey are aligned to the right. So the first non-null one of 4,5 or 6 gives the version field.</p>\n\n<ul>\n<li>1.2.3 gives 1,2,3</li>\n<li>1.2.* gives 1,2,*</li>\n<li>1.2 gives null,1,2</li>\n<li>*** gives null,null,*</li>\n<li>1.* gives null,1,*</li>\n</ul>\n'}, {'answer_id': 82488, 'author': 'rslite', 'author_id': 15682, 'author_profile': 'https://Stackoverflow.com/users/15682', 'pm_score': 2, 'selected': False, 'text': "<p>It seems pretty hard to have a regex that does exactly what you want (i.e. accept only the cases that you need and reject <strong>all</strong> others <em>and</em> return some groups for the three components). I've give it a try and come up with this:</p>\n\n<pre><code>^(\\*|(\\d+(\\.(\\d+(\\.(\\d+|\\*))?|\\*))?))$\n</code></pre>\n\n<p>IMO (I've not tested extensively) this should work fine as a validator for the input, but the problem is that this regex doesn't offer a way of retrieving the components. For that you still have to do a split on period.</p>\n\n<p>This solution is not all-in-one, but most times in programming it doesn't need to. Of course this depends on other restrictions that you might have in your code.</p>\n"}, {'answer_id': 82598, 'author': 'ofaurax', 'author_id': 15209, 'author_profile': 'https://Stackoverflow.com/users/15209', 'pm_score': 3, 'selected': False, 'text': '<pre><code>^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$\n</code></pre>\n\n<p>Perhaps a more concise one could be :</p>\n\n<pre><code>^(?:(\\d+)\\.){0,2}(\\*|\\d+)$\n</code></pre>\n\n<p>This can then be enhanced to 1.2.3.4.5.* or restricted exactly to X.Y.Z using * or {2} instead of {0,2}</p>\n'}, {'answer_id': 2619727, 'author': 'nomuus', 'author_id': 314179, 'author_profile': 'https://Stackoverflow.com/users/314179', 'pm_score': 3, 'selected': False, 'text': '<p>This should work for what you stipulated. It hinges on the wild card position and is a nested regex:</p>\n\n<pre><code>^((\\*)|([0-9]+(\\.((\\*)|([0-9]+(\\.((\\*)|([0-9]+)))?)))?))$\n</code></pre>\n\n<p><img src="https://i.stack.imgur.com/wAazA.png" alt="http://imgur.com/3E492.png"></p>\n'}, {'answer_id': 16540907, 'author': 'Israel Romero', 'author_id': 1485676, 'author_profile': 'https://Stackoverflow.com/users/1485676', 'pm_score': 3, 'selected': False, 'text': "<p>I've seen a lot of answers, but... i have a new one. It works for me at least. I've added a new restriction. Version numbers can't start (major, minor or patch) with any zeros followed by others.</p>\n\n<blockquote>\n <p>01.0.0 is not valid\n 1.0.0 is valid\n 10.0.10 is valid \n 1.0.0000 is not valid</p>\n</blockquote>\n\n<pre><code>^(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+(?:(0\\\\.|([1-9]+\\\\d*)\\\\.))+((0|([1-9]+\\\\d*)))$\n</code></pre>\n\n<p>It's based in a previous one. But i see this solution better... for me ;)</p>\n\n<p>Enjoy!!!</p>\n"}, {'answer_id': 27540795, 'author': 'Sudhanshu Mishra', 'author_id': 190476, 'author_profile': 'https://Stackoverflow.com/users/190476', 'pm_score': 4, 'selected': False, 'text': '<p>My 2 cents: I had this scenario: I had to parse version numbers out of a string literal.\n(I know this is very different from the original question, but googling to find a regex for parsing version number showed this thread at the top, so adding this answer here)</p>\n\n<p>So the string literal would be something like: "Service version 1.2.35.564 is running!"</p>\n\n<p>I had to parse the 1.2.35.564 out of this literal. Taking a cue from @ajborley, my regex is as follows:</p>\n\n<pre><code>(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)\n</code></pre>\n\n<p>A small C# snippet to test this looks like below:</p>\n\n<pre><code>void Main()\n{\n Regex regEx = new Regex(@"(?:(\\d+)\\.)?(?:(\\d+)\\.)?(?:(\\d+)\\.\\d+)", RegexOptions.Compiled);\n\n Match version = regEx.Match("The Service SuperService 2.1.309.0) is Running!");\n version.Value.Dump("Version using RegEx"); // Prints 2.1.309.0 \n}\n</code></pre>\n'}, {'answer_id': 39345000, 'author': 'Oleksandr Yarushevskyi', 'author_id': 4262975, 'author_profile': 'https://Stackoverflow.com/users/4262975', 'pm_score': 2, 'selected': False, 'text': '<p>One more solution:</p>\n\n<pre><code>^[1-9][\\d]*(.[1-9][\\d]*)*(.\\*)?|\\*$\n</code></pre>\n'}, {'answer_id': 41364868, 'author': 'Emmerson', 'author_id': 3159257, 'author_profile': 'https://Stackoverflow.com/users/3159257', 'pm_score': 2, 'selected': False, 'text': '<p>Specifying XSD elements:</p>\n\n<pre><code><xs:simpleType>\n <xs:restriction base="xs:string">\n <xs:pattern value="[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}(\\..*)?"/>\n </xs:restriction>\n</xs:simpleType>\n</code></pre>\n'}, {'answer_id': 44088487, 'author': 'vitaly-t', 'author_id': 1102051, 'author_profile': 'https://Stackoverflow.com/users/1102051', 'pm_score': 2, 'selected': False, 'text': '<p>My take on this, as a good exercise - <a href="https://github.com/vitaly-t/vparse" rel="nofollow noreferrer">vparse</a>, which has a <a href="https://github.com/vitaly-t/vparse/blob/master/index.js" rel="nofollow noreferrer">tiny source</a>, with a simple function:</p>\n\n<pre><code>function parseVersion(v) {\n var m = v.match(/\\d*\\.|\\d+/g) || [];\n v = {\n major: +m[0] || 0,\n minor: +m[1] || 0,\n patch: +m[2] || 0,\n build: +m[3] || 0\n };\n v.isEmpty = !v.major && !v.minor && !v.patch && !v.build;\n v.parsed = [v.major, v.minor, v.patch, v.build];\n v.text = v.parsed.join(\'.\');\n return v;\n}\n</code></pre>\n'}, {'answer_id': 44500980, 'author': 'Shiva', 'author_id': 2068802, 'author_profile': 'https://Stackoverflow.com/users/2068802', 'pm_score': 3, 'selected': False, 'text': "<p>I had a requirement to search/match for version numbers, that follows maven convention or even just single digit. But no qualifier in any case. It was peculiar, it took me time then I came up with this:</p>\n\n<pre><code>'^[0-9][0-9.]*$'\n</code></pre>\n\n<p>This makes sure the version,</p>\n\n<ol>\n<li>Starts with a digit</li>\n<li>Can have any number of digit</li>\n<li>Only digits and '.' are allowed</li>\n</ol>\n\n<p>One drawback is that version can even end with '.' But it can handle indefinite length of version (crazy versioning if you want to call it that)</p>\n\n<p>Matches:</p>\n\n<ul>\n<li>1.2.3</li>\n<li>1.09.5</li>\n<li>3.4.4.5.7.8.8.</li>\n<li>23.6.209.234.3</li>\n</ul>\n\n<p>If you are not unhappy with '.' ending, may be you can combine with endswith logic</p>\n"}, {'answer_id': 62344454, 'author': 'Pau Ballada', 'author_id': 1542507, 'author_profile': 'https://Stackoverflow.com/users/1542507', 'pm_score': 3, 'selected': False, 'text': '<p>For parsing version numbers that follow these rules:\n - Are only digits and dots\n - Cannot start or end with a dot\n - Cannot be two dots together</p>\n\n<p>This one did the trick to me.</p>\n\n<pre><code>^(\\d+)((\\.{1}\\d+)*)(\\.{0})$\n</code></pre>\n\n<p>Valid cases are:</p>\n\n<p>1, 0.1, 1.2.1</p>\n'}, {'answer_id': 64274924, 'author': 'Marc Ruef', 'author_id': 6424520, 'author_profile': 'https://Stackoverflow.com/users/6424520', 'pm_score': 2, 'selected': False, 'text': '<p>Sometimes version numbers might contain alphanumeric minor information (e.g. <em>1.2.0b</em> or <em>1.2.0-beta</em>). In this case I am using this regex:</p>\n<pre><code>([0-9]{1,4}(\\.[0-9a-z]{1,6}){1,5})\n</code></pre>\n'}, {'answer_id': 64784354, 'author': 'Or Assayag', 'author_id': 4442606, 'author_profile': 'https://Stackoverflow.com/users/4442606', 'pm_score': 1, 'selected': False, 'text': '<p>I found this, and it works for me:</p>\n<pre><code>/(\\^|\\~?)(\\d|x|\\*)+\\.(\\d|x|\\*)+\\.(\\d|x|\\*)+\n</code></pre>\n'}, {'answer_id': 70575435, 'author': '山茶树和葡萄树', 'author_id': 5819157, 'author_profile': 'https://Stackoverflow.com/users/5819157', 'pm_score': 1, 'selected': False, 'text': '<pre><code>/^([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\-(alpha|beta|rc|HP|CP|SP|hp|cp|sp)[1-9]\\d*)?(\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)?(\\.[0-9a-zA-Z]+)?$/\n</code></pre>\n<ul>\n<li>A normal version: <code>([1-9]{1}\\d{0,3})(\\.)([0-9]|[1-9]\\d{1,3})(\\.)([0-9]|[1-9]\\d{1,3})</code></li>\n<li>A Pre-release or patched version: <code>(\\-(alpha|beta|rc|EP|HP|CP|SP|ep|hp|cp|sp)[1-9]\\d*)?</code> (Extension Pack, Hotfix Pack, Coolfix Pack, Service Pack)</li>\n<li>Customized version: <code>(\\.C[0-9a-zA-Z]+(-U[1-9]\\d*)?)?</code></li>\n<li>Internal version: <code>(\\.[0-9a-zA-Z]+)?</code></li>\n</ul>\n<p><a href="https://i.stack.imgur.com/Qnquk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qnquk.png" alt="enter image description here" /></a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7271/'] |
82,074 | <p>In a digital signal acquisition system, often data is pushed into an observer in the system by one thread. </p>
<p>example from <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Wikipedia/Observer_pattern</a>:</p>
<pre><code>foreach (IObserver observer in observers)
observer.Update(message);
</code></pre>
<p>When e.g. a user action from e.g. a GUI-thread requires the data to stop flowing, you want to break the subject-observer connection, and even dispose of the observer alltogether.</p>
<p>One may argue: you should just stop the data source, and wait for a sentinel value to dispose of the connection. But that would incur more latency in the system.</p>
<p>Of course, if the data pumping thread has just asked for the address of the observer, it might find it's sending a message to a destroyed object.</p>
<p>Has someone created an 'official' Design Pattern countering this situation? Shouldn't they?</p>
| [{'answer_id': 82116, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 0, 'selected': False, 'text': '<p>You could send a message to all observers informing them the data source is terminating and let the observers remove themselves from the list.</p>\n\n<p>In response to the comment, the implementation of the subject-observer pattern should allow for dynamic addition / removal of observers. In C#, the event system is a subject/observer pattern where observers are added using <code>event += observer</code> and removed using <code>event -= observer</code>.</p>\n'}, {'answer_id': 102984, 'author': 'QBziZ', 'author_id': 11572, 'author_profile': 'https://Stackoverflow.com/users/11572', 'pm_score': 3, 'selected': True, 'text': "<p>If you want to have the data source to always be on the safe side of concurrency, you should have at least one pointer that is always safe for him to use. \nSo the Observer object should have a lifetime that isn't ended before that of the data source.</p>\n\n<p>This can be done by only adding Observers, but never removing them. \nYou could have each observer not do the core implementation itself, but have it delegate this task to an ObserverImpl object. \nYou lock access to this impl object. This is no big deal, it just means the GUI unsubscriber would be blocked for a little while in case the observer is busy using the ObserverImpl object. If GUI responsiveness would be an issue, you can use some kind of concurrent job-queue mechanism with an unsubscription job pushed onto it. ( like PostMessage in Windows )</p>\n\n<p>When unsubscribing, you just substitute the core implementation for a dummy implementation. Again this operation should grab the lock. This would indeed introduce some waiting for the data source, but since it's just a [ lock - pointer swap - unlock ] you could say that this is fast enough for real-time applications.</p>\n\n<p>If you want to avoid stacking Observer objects that just contain a dummy, you have to do some kind of bookkeeping, but this could boil down to something trivial like an object holding a pointer to the Observer object he needs from the list.</p>\n\n<p>Optimization :\nIf you also keep the implementations ( the real one + the dummy ) alive as long as the Observer itself, you can do this without an actual lock, and use something like InterlockedExchangePointer to swap the pointers.\nWorst case scenario : delegating call is going on while pointer is swapped --> no big deal all objects stay alive and delegating can continue. Next delegating call will be to new implementation object. ( Barring any new swaps of course )</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6610/'] |
82,099 | <p>I have create a WCF service and am utilising netMsmqBinding binding.</p>
<p>This is a simple service that passes a Dto to my service method and does not expect a response. The message is placed in an MSMQ, and once picked up inserted into a database.</p>
<p>What is the best method to make sure no data is being lost.</p>
<p>I have tried the 2 following methods:</p>
<ol>
<li><p>Throw an exception</p>
<p>This places the message in a dead letter queue for manual perusal. I can process this when my strvice starts</p>
</li>
<li><p>set the receiveRetryCount="3" on the binding</p>
<p>After 3 tries - which happen instantanously, this seems to leave the message in queue, but fault my service. Restarting my service repeats this process.</p>
</li>
</ol>
<p>Ideally I would like to do the follow:</p>
<p>Try process the message</p>
<ul>
<li>If this fails, wait 5 minutes for that message and try again.</li>
<li>If that process fails 3 times, move the message to a dead letter queue.</li>
<li>Restarting the service will push all messages from the dead letter queue back into the queue so that it can be processed.</li>
</ul>
<p>Can I achieve this? If so how?
Can you point me to any good articles on how best to utilize WCF and MSMQ for my given sceneria.</p>
<p>Any help would be much appreciated. Thanks!</p>
<p><strong>Some additional information</strong></p>
<p>I am using MSMQ 3.0 on Windows XP and Windows Server 2003.
Unfortunately I can't use the built in poison message support targeted at MSMQ 4.0 and Vista/2008.</p>
| [{'answer_id': 82586, 'author': 'aogan', 'author_id': 4795, 'author_profile': 'https://Stackoverflow.com/users/4795', 'pm_score': 4, 'selected': False, 'text': '<p>I think with MSMQ (avaiable only on Vista) you might be able to to do like this:</p>\n\n<pre><code><bindings>\n <netMsmqBinding>\n <binding name="PosionMessageHandling"\n receiveRetryCount="3"\n retryCycleDelay="00:05:00"\n maxRetryCycles="3"\n receiveErrorHandling="Move" />\n </netMsmqBinding>\n</bindings>\n</code></pre>\n\n<p>WCF will immediately retry for ReceiveRetryCount times after the first call failure. After the batch has failed the message is moved\nto the retry queue. After a delay of RetryCycleDelay minute, the message moved from the retry queue to the endpoint queue and the batch is retried. This will be repeated \nMaxRetryCycle time. If all that fails the message is handled according to receiveErrorHandling which can be move \n(to poison queue), reject, drop or fault</p>\n\n<p>By the way a good text about WCF and MSMQ is the chapther 9 of Progammig WCF book from Juval Lowy</p>\n'}, {'answer_id': 82715, 'author': 'WebDude', 'author_id': 15360, 'author_profile': 'https://Stackoverflow.com/users/15360', 'pm_score': 1, 'selected': False, 'text': "<p>Unfortunately I'm stuck on Windows XP and Windows Server 2003 so that isn't an option for me. - (I will re-clarify that in my question as I found this solution after posting and realised i couldn't use it)</p>\n\n<p>I found that one solution was to setup a custom handler which would move my message onto another queue or poison queue and restart my service.\nThis seemed crazy to me. Imagine my Sql Server was down how often the service would be restarted.</p>\n\n<p>SO what I've ended up doing is allowing the Line to fault and leave messages on the queue.\nI also log a fatal message to my system logging service that this has happened.\nOnce our issue is resolved, I restart the service and all the messages start getting processed again.</p>\n\n<p>I realised re-processing this message or any other will all fail, so why the need to move this message and the others to another queue. I may as well stop my service, and start it again when all is operating as expected.</p>\n\n<p>aogan, you had the perfect answer for MSMQ 4.0, but unfortunately not for me</p>\n"}, {'answer_id': 82822, 'author': 'Chris Wenham', 'author_id': 5548, 'author_profile': 'https://Stackoverflow.com/users/5548', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re using SQL-Server then you should use a distributed transaction, since both MSMQ and SQL-Server support it. What happens is you wrap your database write in a TransactionScope block and call scope.Complete() only if it succeeds. If it fails, then when your WCF method returns the message will be placed back into the queue to be tried again. Here\'s a trimmed version of code I use:</p>\n\n<pre><code> [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]\n public void InsertRecord(RecordType record)\n {\n try\n {\n using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))\n {\n SqlConnection InsertConnection = new SqlConnection(ConnectionString);\n InsertConnection.Open();\n\n // Insert statements go here\n\n InsertConnection.Close();\n\n // Vote to commit the transaction if there were no failures\n scope.Complete();\n }\n }\n catch (Exception ex)\n {\n logger.WarnException(string.Format("Distributed transaction failure for {0}", \n Transaction.Current.TransactionInformation.DistributedIdentifier.ToString()),\n ex);\n }\n }\n</code></pre>\n\n<p>I test this by queueing up a large but known number of records, let WCF start lots of threads to handle many of them simultaneously (reaches 16 threads--16 messages off the queue at once), then kill the process in the middle of operations. When the program is restarted the messages are read back from the queue and processed again as if nothing happened, and at the conclusion of the test the database is consistent and has no missing records.</p>\n\n<p>The Distributed Transaction Manager has an ambient presence, and when you create a new instance of TransactionScope it automatically searches for the current transaction within the scope of the method invokation--which should have been created already by WCF when it popped the message off the queue and invoked your method.</p>\n'}, {'answer_id': 85683, 'author': 'tomasr', 'author_id': 10292, 'author_profile': 'https://Stackoverflow.com/users/10292', 'pm_score': 4, 'selected': True, 'text': '<p>There\'s a sample in the SDK that might be useful in your case. Basically, what it does is attach an IErrorHandler implementation to your service that will catch the error when WCF declares the message to be "poison" (i.e. when all configured retries have been exhausted). What the sample does is move the message to another queue and then restart the ServiceHost associated with the message (since it will have faulted when the poison message was found).</p>\n\n<p>It\'s not a very pretty sample, but it can be useful. There are a couple of limitations, though:</p>\n\n<p>1- If you have multiple endpoints associated with your service (i.e. exposed through several queues), there\'s no way to know which queue the poison message arrived in. If you only have a single queue, this won\'t be a problem. I haven\'t seen any official workaround for this, but I\'ve experimented with one possible alternative which I\'ve documented here: <a href="http://winterdom.com/weblog/2008/05/27/NetMSMQAndPoisonMessages.aspx" rel="noreferrer">http://winterdom.com/weblog/2008/05/27/NetMSMQAndPoisonMessages.aspx</a></p>\n\n<p>2- Once the problem message is moved to another queue, it becomes your responsibility, so it\'s up to you to move it back to the processing queue once the timeout is done (or attach a new service to that queue to handle it).</p>\n\n<p>To be honest, in either case, you\'re looking at some "manual" work here that WCF just doesn\'t cover on it\'s own. </p>\n\n<p>I\'ve been recently working on a different project where I have a requirement to explicitly control how often retries happen, and my current solution was to create a set of retry queues and manually move messages between the retry queues and the main processing queue based on a set of timers and some heuristics, just using the raw System.Messaging stuff to handle the MSMQ queues. It seems to work pretty nicely, though there are a couple of gotchas if you go this way.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15360/'] |
82,109 | <p>I am using Java 1.4 with Log4J. </p>
<p>Some of my code involves serializing and deserializing value objects (POJOs). </p>
<p>Each of my POJOs declares a logger with</p>
<pre><code>private final Logger log = Logger.getLogger(getClass());
</code></pre>
<p>The serializer complains of org.apache.log4j.Logger not being Serializable.</p>
<p>Should I use</p>
<pre><code>private final transient Logger log = Logger.getLogger(getClass());
</code></pre>
<p>instead?</p>
| [{'answer_id': 82130, 'author': 'mindas', 'author_id': 7345, 'author_profile': 'https://Stackoverflow.com/users/7345', 'pm_score': 4, 'selected': False, 'text': "<p>The logger must be static; this would make it non-serializable.</p>\n\n<p>There's no reason to make logger non-static, unless you have a strong reason to do it so.</p>\n"}, {'answer_id': 82132, 'author': 'Aleksi Yrttiaho', 'author_id': 11427, 'author_profile': 'https://Stackoverflow.com/users/11427', 'pm_score': 6, 'selected': True, 'text': '<p>How about using a static logger? Or do you need a different logger reference for each instance of the class? Static fields are not serialized by default; you can explicitly declare fields to serialize with a private, static, final array of <code>ObjectStreamField</code> named <code>serialPersistentFields</code>. <a href="http://java.sun.com/developer/technicalArticles/ALT/serialization/#2" rel="noreferrer">See Oracle documentation</a></p>\n\n<p>Added content: \nAs you use <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.String)" rel="noreferrer">getLogger(getClass())</a>, you will use the same logger in each instance. If you want to use separate logger for each instance you have to differentiate on the name of the logger in the getLogger() -method. e.g. getLogger(getClass().getName() + hashCode()). You should then use the transient attribute to make sure that the logger is not serialized. </p>\n'}, {'answer_id': 82138, 'author': 'Philip Helger', 'author_id': 15254, 'author_profile': 'https://Stackoverflow.com/users/15254', 'pm_score': 2, 'selected': False, 'text': "<p>Try making the Logger static instead. Than you don't have to care about serialization because it is handled by the class loader.</p>\n"}, {'answer_id': 82275, 'author': 'MB.', 'author_id': 11961, 'author_profile': 'https://Stackoverflow.com/users/11961', 'pm_score': 0, 'selected': False, 'text': "<p>If you want the Logger to be per-instance then yes, you would want to make it transient if you're going to serialize your objects. Log4J Loggers aren't serializable, not in the version of Log4J that I'm using anyway, so if you don't make your Logger fields transient you'll get exceptions on serialization.</p>\n"}, {'answer_id': 82304, 'author': 'Glever', 'author_id': 15504, 'author_profile': 'https://Stackoverflow.com/users/15504', 'pm_score': 0, 'selected': False, 'text': '<p>Loggers are not serializable so you must use transient when storing them in instance fields.\nIf you want to restore the logger after deserialization you can store the Level (String) indide your object which does get serialized.</p>\n'}, {'answer_id': 82551, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>These kinds of cases, particularly in EJB, are generally best handled via thread local state. Usually the use case is something like you have a particular transaction which is encountering a problem and you need to elevate logging to debug for that operation so you can generate detailed logging on the problem operation. Carry some thread local state across the transaction and use that to select the correct logger. Frankly I don't know where it would be beneficial to set the level on an INSTANCE in this environment because the mapping of instances into the transaction should be a container level function, you won't actually have control of which instance is used in a given transaction anyway.</p>\n\n<p>Even in cases where you're dealing with a DTO it is not generally a good idea to design your system in such a way that a given specific instance is required because the design can easily evolve in ways that make that a bad choice. You could come along a month from now and decide that efficiency considerations (caching or some other life cycle changing optimization) will break your assumption about the mapping of instances into units of work. </p>\n"}, {'answer_id': 82552, 'author': 'user9189', 'author_id': 9189, 'author_profile': 'https://Stackoverflow.com/users/9189', 'pm_score': 3, 'selected': False, 'text': '<p>Either declare your logger field as static or as transient. </p>\n\n<p>Both ways ensure the writeObject() method will not attempt to write the field to the output stream during serialization.</p>\n\n<p>Usually logger fields are declared static, but if you need it to be an instance field just declare it transient, as its usually done for any non-serializable field. Upon deserialization the logger field will be null, though, so you have to implement a readObject() method to initialize it properly.</p>\n'}, {'answer_id': 82565, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 3, 'selected': False, 'text': '<p>If you <em>really</em> want to go the transient approach you will need to reset the log when your object is deserialized. The way to do that is to implement the method:</p>\n\n<pre><code> private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException;\n</code></pre>\n\n<p>The javadocs for <a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html" rel="noreferrer">Serializable</a> has information on this method. </p>\n\n<p>Your implementation of it will look something like:</p>\n\n<pre><code> private void readObject(java.io.ObjectInputStream in) \n throws IOException, ClassNotFoundException {\n log = Logger.getLogger(...);\n in.defaultReadObject();\n }\n</code></pre>\n\n<p>If you do not do this then log will be null after deserializing your object.</p>\n'}, {'answer_id': 84187, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 0, 'selected': False, 'text': '<p>There are good reasons to use an instance logger. One very good use case is so you can declare the logger in a super-class and use it in all sub-classes (the only downside is that logs from the super-class are attributed to the sub-class but it is usually easy to see that).</p>\n\n<p>(Like others have mentioned use static or transient).</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15452/'] |
82,113 | <p>My guess is that class variables ("class var") are truly global in storage (that is, one instance for the entire application).</p>
<p>But I am wondering whether this is the case, or whether they are thread in storage (eg similar to a "threadvar") - once instance per thread.</p>
<p>Anyone know?</p>
<p><em>Edit: changed "scope" to "storage" as this is in fact the correct terminology, and what I am after (thanks Barry)</em></p>
| [{'answer_id': 82148, 'author': 'Daniel', 'author_id': 6852, 'author_profile': 'https://Stackoverflow.com/users/6852', 'pm_score': 4, 'selected': True, 'text': '<p>Yes, class variables are globally scoped. Have a look in the RTL source for details of how threadvars are implemented. Under Win32 each thread can have a block of memory allocated automatically to it on thread creation. This extra data area is what is used to contain your threadvars.</p>\n'}, {'answer_id': 83026, 'author': 'Barry Kelly', 'author_id': 3712, 'author_profile': 'https://Stackoverflow.com/users/3712', 'pm_score': 4, 'selected': False, 'text': '<p>Class variables are scoped according to their member visibility attributes, and have global storage, not thread storage.</p>\n\n<p>Scope is a syntactic concept, and relates to what identifiers are visible from where. It is the storage of the variable that is of concern here.</p>\n'}, {'answer_id': 88987, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Class variables are just like classes: global and unique for the application.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11820/'] |
82,123 | <p>I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in <a href="http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php" rel="nofollow noreferrer">http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php</a></p>
<p>But I have a strange exception:</p>
<blockquote>
<p>java.lang.AssertionError
at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86)</p>
</blockquote>
<p>and nothing in the log file.</p>
<p>Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running?</p>
<p>Here is the code I'm using:</p>
<pre><code>public static void executeReport()
{
IReportEngine engine=null;
EngineConfig config = null;
try{
config = new EngineConfig( );
config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine");
config.setLogConfig("d:/temp", Level.FINEST);
Platform.startup( config );
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
engine = factory.createReportEngine( config );
IReportRunnable design = null;
//Open the report design
design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign");
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFileName("output/resample/Parmdisp.html");
options.setOutputFormat("html");
task.setRenderOption(options);
task.run();
task.close();
engine.destroy();
}catch( Exception ex){
ex.printStackTrace();
}
finally
{
Platform.shutdown( );
}
}
</code></pre>
| [{'answer_id': 82229, 'author': 'cH1cK3n', 'author_id': 15615, 'author_profile': 'https://Stackoverflow.com/users/15615', 'pm_score': 2, 'selected': False, 'text': '<p>I had the same mistake a couple of month ago. I\'m not quite sure what actually fixed it but my code looks like the following:</p>\n\n<pre><code> IDesignEngine engine = null;\n DesignConfig dConfig = new DesignConfig();\n EngineConfig config = new EngineConfig();\n IDesignEngineFactory factory = null;\n config.setLogConfig(LOG_DIRECTORY, Level.FINE);\n HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()\n .getExternalContext().getRequest();\n\n String u = servletRequest.getSession().getServletContext().getRealPath("/");\n File f = new File(u + PATH_TO_ENGINE_HOME);\n\n log.debug("setting engine home to:"+f.getAbsolutePath());\n config.setEngineHome(f.getAbsolutePath());\n\n Platform.startup(config);\n factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);\n engine = factory.createDesignEngine(dConfig);\n SessionHandle session = engine.newSessionHandle(null);\n\n this.design = session.openDesign(u + PATH_TO_MAIN_DESIGN);\n</code></pre>\n\n<p>Perhaps you can solve your problem by comparing this code snippet and your own code. btw my PATH_TO_ENGINE_HOME is "/WEB-INF/platform". [edit]I used the complete "platform"-folder from the WebViewerExample of the birt-runtime-2_1_1. atm birt-runtime-2_3_0 is actual.[/edit]</p>\n\n<p>If this doesn\'t help please give a few more details (for example a code snippet).</p>\n'}, {'answer_id': 93278, 'author': 'Scott Rosenbaum', 'author_id': 5412, 'author_profile': 'https://Stackoverflow.com/users/5412', 'pm_score': 2, 'selected': True, 'text': '<p>Just a thought, but I wonder if your use of a forward slash when setting the logger is causing a problem? instead of</p>\n\n<pre><code>config.setLogConfig("d:/temp", Level.FINEST);\n</code></pre>\n\n<p>you should use </p>\n\n<pre><code> config.setLogConfig("/temp", Level.FINEST);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> config.setLogConfig("d:\\\\temp", Level.FINEST);\n</code></pre>\n\n<p>Finally, I realize that this is just some sample code, but you will certainly want to split your platform startup code out from your run and render task. The platform startup is very expensive and should only be done once per session. </p>\n\n<p>I have a couple of Eclipse projects that are setup in a Subversion server that demonstrate how to use the Report Engine API (REAPI) and the Design Engine API (DEAPI) that you may find useful as your code gets more complicated. </p>\n\n<p>To get the examples you will need either the Subclipse or the Subversive plugins and then you will need to connect to the following repository:</p>\n\n<pre><code>http://longlake.minnovent.com/repos/birt_example\n</code></pre>\n\n<p>The projects that you need are:</p>\n\n<pre><code>birt_api_example\nbirt_runtime_lib\nscript.lib\n</code></pre>\n\n<p>You may need to adjust some of the file locations in the BirtUtil class, but I think that most file locations are relative path. There is more information about how to use the examples projects on my blog at http:/birtworld.blogspot.com. In particular this article should help: <a href="http://birtworld.blogspot.com/2008/04/testing-and-debug-of-reports.html" rel="nofollow noreferrer">Testing And Debug of Reports</a></p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446104/'] |
82,128 | <p>Our build server is taking too long to build one of our C++ projects. It uses <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2008" rel="nofollow noreferrer">Visual Studio 2008</a>, running <code>devenv.com MyApp.sln /Build</code> -- see <a href="https://learn.microsoft.com/en-us/visualstudio/ide/reference/devenv-command-line-switches?view=vs-2022" rel="nofollow noreferrer">devenv command-line switches</a> (although that's for a newer version of VS). Is there a way to get devenv.com to log the time taken to build each project in the solution, so that I know where to focus my efforts?</p>
<p>Improved hardware is not an option in this case.</p>
<p>I've tried setting the output verbosity (under menu <em>Tools</em> → <em>Options</em> → <em>Projects and Solutions</em> → <em>Build and Run</em> → <em>MSBuild project build output verbosity</em>). This doesn't seem to have any effect in the IDE.</p>
<p>When running MSBuild from the command line (and, for Visual Studio 2008, it needs to be MSBuild v3.5), it displays the total time elapsed at the end, but not in the IDE.</p>
<p>I really wanted a time-taken report for each project in the solution, so that I could figure out where the build process was taking its time.</p>
| [{'answer_id': 82140, 'author': 'Dave Moore', 'author_id': 6996, 'author_profile': 'https://Stackoverflow.com/users/6996', 'pm_score': 7, 'selected': False, 'text': '<p>Go to menu <em>Tools</em> → <em>Options</em> → <em>Projects and Solutions</em> → <em>Build and Run</em> → <em>MSBuild project build output verbosity</em>. Set to "Normal" or "Detailed", and the build time will appear in the output window.</p>\n'}, {'answer_id': 82218, 'author': 'Dave Moore', 'author_id': 6996, 'author_profile': 'https://Stackoverflow.com/users/6996', 'pm_score': 3, 'selected': False, 'text': '<p>Since your question involves using DevEnv from the command line, I would also suggest using <a href="http://en.wikipedia.org/wiki/MSBuild" rel="nofollow noreferrer">MSBuild</a> (which can build .sln files without modification). </p>\n\n<pre><code>msbuild /fl /flp:Verbosity=diagnostic Your.sln\n</code></pre>\n\n<p><code>msbuild /?</code> will show you other useful options for the filelogger.</p>\n'}, {'answer_id': 132526, 'author': 'JesperE', 'author_id': 13051, 'author_profile': 'https://Stackoverflow.com/users/13051', 'pm_score': 9, 'selected': True, 'text': '<p>Menu <em>Tools</em> → <em>Options</em> → <em>Projects and Solutions</em> → <em>VC++ Project Settings</em> → <em>Build Timing</em> should work.</p>\n'}, {'answer_id': 2590002, 'author': 'MattyT', 'author_id': 7405, 'author_profile': 'https://Stackoverflow.com/users/7405', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re stuck on VS2005 you could use the <a href="http://code.google.com/p/vs-build-timer/" rel="noreferrer">vs-build-timer plugin</a>. At the completion of a build it shows the total time taken and a (optional) summary of each of the project durations.</p>\n\n<p>Disclaimer; I wrote it. And yes, I need to create an installer...one day!</p>\n'}, {'answer_id': 14358229, 'author': 'RaaFFC', 'author_id': 1983582, 'author_profile': 'https://Stackoverflow.com/users/1983582', 'pm_score': 3, 'selected': False, 'text': '<p>Menu <em>Tools</em> → <em>Options</em> → <em>Projects and Solutions</em> → <em>Build and Run</em> →</p>\n<p>Set "MSBuild project build output verbosity" from "Minimal" to "Normal".</p>\n'}, {'answer_id': 17526392, 'author': 'Oliver', 'author_id': 1529004, 'author_profile': 'https://Stackoverflow.com/users/1529004', 'pm_score': 3, 'selected': False, 'text': '<p>For Visual Studio 2012 you could use the <a href="http://visualstudiogallery.msdn.microsoft.com/b0c87e47-f4ee-4935-9a59-f2c81ce692ab" rel="noreferrer">Build Monitor</a> extension.</p>\n'}, {'answer_id': 25203748, 'author': 'Sebastian', 'author_id': 3111930, 'author_profile': 'https://Stackoverflow.com/users/3111930', 'pm_score': 5, 'selected': False, 'text': '<h2>Visual Studio 2012 - 2019</h2>\n<ul>\n<li><p><strong>For MSBuild Projects (e.g., all .NET projects):</strong>\nClick <em>Tools</em> → <em>Options</em> and then select <em>Projects and Solutions</em> → <em>Build and Run</em>.\nChange <em>MSBuild project build output verbosity</em> to <em>Normal</em>. So it will display Time Elapsed in every Solution Project it builds.\nBut there is unfortunately no <em>Elapsed Time Sum</em> over all projects. You will also see the Build started Timestamp</p>\n</li>\n<li><p><strong>For C/C++ Projects:</strong></p>\n</li>\n</ul>\n<p>Click <em>Tools</em> → <em>Options</em> and then select <em>Projects and Solutions</em> → <em>VC++ Project Settings</em>.</p>\n<p>Change <em>Build Timing</em> to <em>Yes</em>.</p>\n'}, {'answer_id': 29146660, 'author': 'InbetweenWeekends', 'author_id': 902874, 'author_profile': 'https://Stackoverflow.com/users/902874', 'pm_score': 2, 'selected': False, 'text': "<p>I ended up here because I just wanted the date and time included in the build output. Should others be searching for something similar it's as simple as adding <code>echo %date% %time%</code> to the Pre-build and/or Post-build events under project, <em>Properties</em> → <em>Compile</em> → <em>Build Events</em>.</p>\n"}, {'answer_id': 31827370, 'author': 'Blue Clouds', 'author_id': 1501191, 'author_profile': 'https://Stackoverflow.com/users/1501191', 'pm_score': 2, 'selected': False, 'text': '<p>Do a build first and see which project is appearing first in the build output (<kbd>Ctrl</kbd> + <kbd>Home</kbd> in the output window). Right click that project → <em>Project Properties</em> → <em>Compile</em> → <em>Build Events</em> → <em>Pre-build</em>. And <code>echo ###########%date% %time%#############</code>.</p>\n\n<p>So every time you see build results (or during build) do <kbd>Ctrl</kbd> + <kbd>Home</kbd> in the output window. And somewhere in that area the time and date stares at your face!</p>\n\n<p>Oh and you might end up adding these details to many projects as the build order can change :)</p>\n\n<hr>\n\n<p>I found a better solution! ###</p>\n\n<p><em>Tools</em> → <em>Options</em> → <em>Projects & Solutions</em> → <em>Build and Run</em> → <em>MSBuild project build output verbosity</em> = Normal (or above <em>Minimal</em>). This adds the time in the beginning/top of output window. <kbd>Ctrl</kbd> + <kbd>Home</kbd> in the output window should do.</p>\n\n<p>If we want to see how much time each projects take then <em>Projects & Solutions</em> → <em>VC++ Project Settings</em> → <em>Build Timing = yes</em>. It is applicable to all projects; "VC++" is misleading.</p>\n'}, {'answer_id': 34118584, 'author': 'buildops', 'author_id': 5603357, 'author_profile': 'https://Stackoverflow.com/users/5603357', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to visualize your build, you can use <a href="https://en.wikipedia.org/wiki/Incredibuild" rel="nofollow noreferrer">Incredibuild</a>. Incredibuild\'s now available in standalone-mode (not distributed, but for use only on 8 cores on your local machine) for free as part of Visual Studio 2015 Update 1.</p>\n<p><strong>Disclaimer: I work for Incredibuild</strong></p>\n'}, {'answer_id': 37139065, 'author': 'Andreas Haferburg', 'author_id': 872616, 'author_profile': 'https://Stackoverflow.com/users/872616', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to invoke an external program that can track your total build times, you can use the following solution for <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2010" rel="nofollow noreferrer">Visual\xa0Studio\xa02010</a> (and maybe older). The code below uses CTime by Casey Muratori. Of course, you can also use it to simply print the build time.</p>\n<p>Open up the macro explorer, and paste the following before <code>End Module</code>:</p>\n<pre><code>Dim buildStart As Date\n\nPrivate Sub RunCtime(ByVal StartRatherThanEnd As Boolean)\n Dim Arg As String\n Dim psi As New System.Diagnostics.ProcessStartInfo("ctime.exe")\n If StartRatherThanEnd Then\n psi.Arguments = "-begin"\n Else\n psi.Arguments = "-end"\n End If\n psi.Arguments += " c:\\my\\path\\build.ctm"\n psi.RedirectStandardOutput = False\n psi.WindowStyle = ProcessWindowStyle.Hidden\n psi.UseShellExecute = False\n psi.CreateNoWindow = True\n Dim process As System.Diagnostics.Process\n process = System.Diagnostics.Process.Start(psi)\n Dim myOutput As System.IO.StreamReader = process.StandardOutput\n process.WaitForExit(2000)\n If process.HasExited Then\n Dim output As String = myOutput.ReadToEnd\n WriteToBuildWindow("CTime output: " + output)\n End If\nEnd Sub\n\nPrivate Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin\n WriteToBuildWindow("Build started!")\n buildStart = Date.Now\n RunCtime(True)\nEnd Sub\n\nPrivate Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone\n Dim buildTime = Date.Now - buildStart\n WriteToBuildWindow(String.Format("Total build time: {0} seconds", buildTime.ToString))\n RunCtime(False)\nEnd Sub\n\nPrivate Sub WriteToBuildWindow(ByVal message As String)\n Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)\n Dim ow As OutputWindow = CType(win.Object, OutputWindow)\n If (Not message.EndsWith(vbCrLf)) Then\n message = message + vbCrLf\n End If\n ow.OutputWindowPanes.Item("Build").OutputString(message)\nEnd Sub\n</code></pre>\n<p>The answer was taken from <a href="https://stackoverflow.com/questions/523220/awesome-visual-studio-macros/2112181#2112181">here</a> and <a href="https://blogs.msdn.microsoft.com/vbfaq/2004/05/30/how-can-i-run-another-application-or-batch-file-from-my-visual-basic-net-code/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 51152492, 'author': 'Wesam', 'author_id': 5723127, 'author_profile': 'https://Stackoverflow.com/users/5723127', 'pm_score': 1, 'selected': False, 'text': '<p>Options -> Projects and Solutions -> VC++ Project Settings -> Build Timing</p>\n\n<p><a href="https://i.stack.imgur.com/t4ZxA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t4ZxA.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 54144991, 'author': 'opetroch', 'author_id': 779446, 'author_profile': 'https://Stackoverflow.com/users/779446', 'pm_score': 5, 'selected': False, 'text': '<p>I have created an extension to measure the build times and present the order of events in a graph: <a href="https://marketplace.visualstudio.com/items?itemName=OdysseasPetrocheilos.VisualStudioBuildTimer" rel="nofollow noreferrer">Visual Studio Build Timer</a>.</p>\n<p><a href="https://i.stack.imgur.com/KC8EI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KC8EI.png" alt="Enter image description here" /></a></p>\n<p>It is available on the Visual\xa0Studio market place and works for <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2015" rel="nofollow noreferrer">Visual\xa0Studio\xa02015</a>, <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2017" rel="nofollow noreferrer">Visual\xa0Studio\xa02017</a> and <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#2019" rel="nofollow noreferrer">Visual\xa0Studio\xa02019</a>.</p>\n<p>Apart from showing which projects take longer, the chart displays effective dependencies between them, i.e., projects that need to wait for others, which helps figuring out what dependencies need to break to increase the parallelization of your build.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8446/'] |
82,141 | <p>I have 6 sound files (1.wav 2.wav etc..) of which 3 different ones have to be heard each time the web page opens. The numbers are selected randomly.
I have tried multiple "embeds" but only the last sound selected gets produced.
I have also tried javascript routines that fiddle the bgsound attribute, however, I was not able to produce more than one sound at a time.
The sounds are required to play either automatically on page open or they can be triggered by a click on a button or link, however, only one click is acceptable for the three sounds.
Is there another way to do this? suggestions very welcome.</p>
| [{'answer_id': 82154, 'author': 'Cetra', 'author_id': 15087, 'author_profile': 'https://Stackoverflow.com/users/15087', 'pm_score': 2, 'selected': False, 'text': "<p>I would use Flash if i'm trying to add sound into a webpage, you can embed a flash document with no width or height so it will be invisible but still play noise.</p>\n"}, {'answer_id': 82157, 'author': 'Paul Tomblin', 'author_id': 3333, 'author_profile': 'https://Stackoverflow.com/users/3333', 'pm_score': 1, 'selected': False, 'text': "<p>I've got a good idea: <strong>DON'T</strong>!</p>\n\n<p>I hate web sites that play sounds without my telling them to. I use a multi-tabbed browser, and a multi-tasking operating system, and you don't have control of my computer, so don't assume you can play a sound without interfering with other things I'm doing.</p>\n"}, {'answer_id': 82159, 'author': 'diciu', 'author_id': 2811, 'author_profile': 'https://Stackoverflow.com/users/2811', 'pm_score': 0, 'selected': False, 'text': "<p>A browser will split page loading into multiple items and thus it's likely to load all sounds at once using multiple threads. I think what you're trying to accomplish is impossible.</p>\n"}, {'answer_id': 82181, 'author': 'Ilya Kochetov', 'author_id': 15329, 'author_profile': 'https://Stackoverflow.com/users/15329', 'pm_score': 3, 'selected': False, 'text': '<p>A simple Flash would do the trick better than anything else.\nHowever please consider that unless you develop your page for the Intranet application and the feature was specifically requested by the users it will most likely go against the best usability practices for web.\nMost users consider the pages which produce sounds to be very distractive and if the sound is produced on the page load the most likely will not be able to turn it off.\nIf you want to embed some sound in your page you may allow the user to turn it on explicitely.</p>\n'}, {'answer_id': 82222, 'author': 'Kent Fredric', 'author_id': 15614, 'author_profile': 'https://Stackoverflow.com/users/15614', 'pm_score': 0, 'selected': False, 'text': '<p>I know this is a bit exorbitant, but the number of combinations are not overly excessive. If you pre-blend the wav files into a series of files and just name them as follows</p>\n\n<pre><code>1_2_3, 1_2_3, 1_2_5, 1_2_6 \n1_3_4, 1_3_5, 1_3_6\n1_4_5, 1_4_6\n2_3_4, 2_3_5, 2_3_6, \n2_4_5, 2_4_6,\n2_5_6\n3_4_5, 3_4_6,\n3_5_6,\n4_5_6\n</code></pre>\n\n<p>( fortunately not too many combinations )</p>\n\n<p>and then as long as you do:</p>\n\n<pre><code> $n = [ randomnumber , randomnumber , randomnumber ]; \n $n = sort $n; \n file = "$n[0]_$n[1]_$n[2].wav" \n</code></pre>\n\n<p>that should get it working. </p>\n\n<p>Noted many people are opposed to sound and depending on what technique you use to play it it may/may not work for all, but that\'s probably a feature we should get browsers to enforce, because some people like being able to hear sounds ( shocking, but true ). </p>\n'}, {'answer_id': 82255, 'author': 'Eric DeLabar', 'author_id': 7556, 'author_profile': 'https://Stackoverflow.com/users/7556', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re not against using a JavaScript framework to play a sound scriptaculous provides an API for playing sounds.</p>\n\n<p><a href="http://github.com/madrobby/scriptaculous/wikis/sound" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/sound</a></p>\n'}, {'answer_id': 231416, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Adding Sounds - HTML Lessons\nHTML MUSIC / MEDIA CODE - Sound\n<a href="http://html-lesson.blogspot.com/2008/06/music-media-code-sound.html" rel="nofollow noreferrer">http://html-lesson.blogspot.com/2008/06/music-media-code-sound.html</a></p>\n'}, {'answer_id': 231465, 'author': 'Karl', 'author_id': 2932, 'author_profile': 'https://Stackoverflow.com/users/2932', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://www.schillmania.com/projects/soundmanager2/" rel="nofollow noreferrer">Sound Manager 2</a> an invisible flash movie that you can use to play sounds. It allows you to load and play multiple sounds.</p>\n\n<p>To do what you wish to accomplish I would re-encode the wav files as mp3s (so that they download faster and Sound Manager can play them). Then use javascript to get sound manager to create the sounds and play them in a random order. You can listen to the onfinish event of each sound to start playing the next sound.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15588/'] |
82,151 | <p>I've been using the (Java) <a href="http://lucene.apache.org/java/2_4_1/lucene-sandbox/index.html#Term%20Highlighter" rel="nofollow noreferrer">Highlighter for Lucene</a> (in the Sandbox package) for some time. However, this isn't really very accurate when it comes to matching the correct terms in search results - it works well for simple queries, for example searching for two separate words will highlight both code fragments in the results.</p>
<p>However, it doesn't act well with more complicated queries. In the simplest case, phrase queries such as "Stack Overflow" will match all occurrences of Stack or Overflow in the highlighting, which gives the impression to the user that it isn't working very well.</p>
<p>I tried applying the fix <a href="http://www.gossamer-threads.com/lists/lucene/java-user/15528" rel="nofollow noreferrer">here</a> but that came with a lot of performance caveats, and at the end of the day was just plain unusable. The performance is especially an issue on wildcard queries. This is due to the way that the highlighting works; instead of just working on the querystring and the text it parses it as Lucene would and then looks for all the matches that Lucene has made; unfortunately this means that for certain wildcard queries it can be looking for matches to 2000+ clauses on large documents, and it's simply not fast enough.</p>
<p>Is there any faster implementation of an accurate highlighter?</p>
| [{'answer_id': 84993, 'author': 'Sindri Traustason', 'author_id': 1113, 'author_profile': 'https://Stackoverflow.com/users/1113', 'pm_score': 1, 'selected': False, 'text': '<p>You could look into using Solr. <a href="http://lucene.apache.org/solr" rel="nofollow noreferrer">http://lucene.apache.org/solr</a></p>\n\n<p>Solr is a sort of generic search application that uses Lucene and supports highlighting. It\'s possible that the highlighting in Solr is usable as an API outside of Solr. You could also look at how Solr does it for inspiration.</p>\n'}, {'answer_id': 164764, 'author': 'dlamblin', 'author_id': 459, 'author_profile': 'https://Stackoverflow.com/users/459', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve been reading on the subject and came across <a href="http://lucene.apache.org/java/2_3_1/api/org/apache/lucene/search/spans/SpanQuery.html" rel="nofollow noreferrer">spanQuery</a> which would return to you the span of the matched term or terms in the field that matched.</p>\n'}, {'answer_id': 651662, 'author': 'pro', 'author_id': 352728, 'author_profile': 'https://Stackoverflow.com/users/352728', 'pm_score': 3, 'selected': True, 'text': '<p>There is a new faster highlighter (needs to be patched in but will be part of release 2.9)</p>\n\n<p><a href="https://issues.apache.org/jira/browse/LUCENE-1522" rel="nofollow noreferrer">https://issues.apache.org/jira/browse/LUCENE-1522</a></p>\n\n<p>and a <a href="https://issues.apache.org/jira/browse/LUCENE-1522?focusedCommentId=12688408&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12688408" rel="nofollow noreferrer">back-reference</a> to this question</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6282/'] |
82,169 | <p>I've already got a NAnt build script that builds/runs tests/zips web project together, etc. but I'm working on a basic desktop application. How would I go about building the setup project using NAnt so I can include it with the build report on TeamCity.</p>
<p>Edit: The setup is the basic Setup Project supplied with Visual Studio. It's for internal to a company so it doesn't do anything fancy.</p>
| [{'answer_id': 82195, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 2, 'selected': False, 'text': '<p>The only way to build a Visual Studio setup project is through Visual Studio. You will need to have a copy of VS installed on the build machine and run it as a command line tool (exec devenv.exe) with the appropriate parameters (which should be the build mode (release or debug) and the project name to build, there might be a few others but you can run devenv /? to get a list of the different command line options).</p>\n'}, {'answer_id': 82224, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': "<p>It's been a few years, but the last time I had to do this, I used a tool called Wix, which had utilities named Candle and Light. I used these tools in my NAnt script to create an MSI Installer.</p>\n"}, {'answer_id': 82240, 'author': 'EggyBach', 'author_id': 15475, 'author_profile': 'https://Stackoverflow.com/users/15475', 'pm_score': 0, 'selected': False, 'text': "<p>Instead of trying to build using MSBUILD (assumption), build the solution or project using DEVENV.EXE. The command line is something along the lines of:</p>\n\n<p>DEVENV MySolutionFile.sln /build DEBUG /project SetupProject.vdproj</p>\n\n<p>You can change the DEBUG to RELEASE or any other build configuration you've set up. You can also leave out the /project... part to build the whole solution.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5802/'] |
82,180 | <p>I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?</p>
| [{'answer_id': 82258, 'author': 'zgoda', 'author_id': 12138, 'author_profile': 'https://Stackoverflow.com/users/12138', 'pm_score': 4, 'selected': True, 'text': '<p>Qt\'s own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo. Might you explain why you want specifically Cairo in Qt?</p>\n\n<p>For the basics of using QPainter see <a href="http://www.informit.com/articles/article.aspx?p=1174421" rel="noreferrer">this excerpt</a> from the book "C++ GUI Programming with Qt4", and while it\'s C++ code, the PyQt implementation will be parallel.</p>\n\n<p>As for joining Cairo with Qt... <a href="http://arstechnica.com/news.ars/post/20080818-nokia-helps-port-firefox-to-qt.html" rel="noreferrer">This article in ArsTechnica</a> sheds some light - it seems nothing that could help you exists currently (iow., nobody tried such marriage).</p>\n'}, {'answer_id': 453179, 'author': 'Eli Bendersky', 'author_id': 8206, 'author_profile': 'https://Stackoverflow.com/users/8206', 'pm_score': 0, 'selected': False, 'text': '<p>For plotting with you should also consider matplotlib, which provides a higher level API and integrates well with PyQT.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14006/'] |
82,191 | <p>I'm creating a plugin, and am looking to use RSpec so I can build it using BDD. </p>
<p>Is there a recommended method of doing this?</p>
| [{'answer_id': 82680, 'author': 'Dan Harper', 'author_id': 14530, 'author_profile': 'https://Stackoverflow.com/users/14530', 'pm_score': 0, 'selected': False, 'text': '<p>For an example of an existing plugin that uses rspec, check out the <a href="http://github.com/technoweenie/restful-authentication/tree/master" rel="nofollow noreferrer">restful_authentication plugin</a>. Maybe it will help.</p>\n'}, {'answer_id': 83039, 'author': 'Codebeef', 'author_id': 12037, 'author_profile': 'https://Stackoverflow.com/users/12037', 'pm_score': 2, 'selected': True, 'text': "<p>OK, I think I have a solution:</p>\n\n<ul>\n<li>Generate the plugin via script/generate plugin</li>\n<li>change the Rakefile, and add</li>\n</ul>\n\n<p><code>\n require 'spec/rake/spectask'</p>\n\n<pre><code>desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n</code></pre>\n\n<p></code></p>\n\n<ul>\n<li>Create a spec directory, and begin adding specs in *_spec.rb files, as normal</li>\n</ul>\n\n<p>You can also modify the default task to run spec instead of test, too.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12037/'] |
82,214 | <p>In the early days of SharePoint 2007 beta, I've come across the ability to customize the template used to emit the RSS feeds from lists. I can't find it again. Anybody know where it is?</p>
| [{'answer_id': 82680, 'author': 'Dan Harper', 'author_id': 14530, 'author_profile': 'https://Stackoverflow.com/users/14530', 'pm_score': 0, 'selected': False, 'text': '<p>For an example of an existing plugin that uses rspec, check out the <a href="http://github.com/technoweenie/restful-authentication/tree/master" rel="nofollow noreferrer">restful_authentication plugin</a>. Maybe it will help.</p>\n'}, {'answer_id': 83039, 'author': 'Codebeef', 'author_id': 12037, 'author_profile': 'https://Stackoverflow.com/users/12037', 'pm_score': 2, 'selected': True, 'text': "<p>OK, I think I have a solution:</p>\n\n<ul>\n<li>Generate the plugin via script/generate plugin</li>\n<li>change the Rakefile, and add</li>\n</ul>\n\n<p><code>\n require 'spec/rake/spectask'</p>\n\n<pre><code>desc 'Test the PLUGIN_NAME plugin.'\nSpec::Rake::SpecTask.new(:spec) do |t|\n t.libs << 'lib'\n t.verbose = true\nend\n</code></pre>\n\n<p></code></p>\n\n<ul>\n<li>Create a spec directory, and begin adding specs in *_spec.rb files, as normal</li>\n</ul>\n\n<p>You can also modify the default task to run spec instead of test, too.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1533/'] |
82,223 | <p>I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file. Since then, I've become fairly proficient at 'coding' my hbm.xml file. But all the cool kids are using annotations these days.</p>
<p>So, the question is: <strong>Is it worth the effort</strong> to refactor my code to use hibernate annotations? Will I gain anything, other than being hip and modern? Will I lose any of the control I have in my existing hand coded mapping file?</p>
<p>A sub-question is, <strong>how much effort will it be?</strong> I like my databases lean and mean. The mapping covers only a dozen domain objects, including two sets, some subclassing, and about 8 tables.</p>
<p>Thanks, dear SOpedians, in advance for your informed opinions.</p>
| [{'answer_id': 82265, 'author': 'entzik', 'author_id': 12297, 'author_profile': 'https://Stackoverflow.com/users/12297', 'pm_score': 2, 'selected': False, 'text': "<p>One thing you'll gain from using annotations instead of an external mapping file is that your mapping information will be on classes and fields which improves maintainability. You add a field, you immediately add the annotation. You remove one, you also remove the annotation. you rename a class or a field, the annotation is right there and you can rename the table or column as well. you make changes in class inheritance, it's taken into account. You don't have to go and edit an external file some time later. this makes the whole thing more efficient and less error prone.</p>\n\n<p>On the other side, you'll lose the global view your mapping file used to give you.</p>\n"}, {'answer_id': 82270, 'author': 'BigJump', 'author_id': 8542, 'author_profile': 'https://Stackoverflow.com/users/8542', 'pm_score': 4, 'selected': True, 'text': '<p>"If it ain\'t broke - don\'t fix it!"</p>\n\n<p>I\'m an old fashioned POJO/POCO kind of guy anyway, but why change to annotations just to be cool? To the best of my knowledge you can do most of the stuff as annotations, but the more complex mappings are sometimes expressed more clearly as XML.</p>\n'}, {'answer_id': 82277, 'author': 'Shimi Bandiel', 'author_id': 15100, 'author_profile': 'https://Stackoverflow.com/users/15100', 'pm_score': 0, 'selected': False, 'text': '<p>All the features are supported both in the XML and in annotations.\nYou will still be able to override your annotations with xml declaration.</p>\n\n<p>As for the effort, i think it is worth it as you will be able to see all in one place and not switch between your code and the xml file (unless of-course you are using two monitors ;) )</p>\n'}, {'answer_id': 82280, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>The only thing you'll gain from using\n annotations</p>\n</blockquote>\n\n<p>I would probably argue that this is <strong>the</strong> thing you want to gain from using annotations. Because you don't get compile time safety with NHibernate this is the next best thing.</p>\n"}, {'answer_id': 82287, 'author': 'Darren', 'author_id': 6065, 'author_profile': 'https://Stackoverflow.com/users/6065', 'pm_score': 2, 'selected': False, 'text': "<p>As much as I like to move on to new and potentially better things I need to remember to not mess with things that aren't broken. So if having the hibernate mappings in a separate file is working for you now I wouldn't change it.</p>\n"}, {'answer_id': 83633, 'author': 'Alex Miller', 'author_id': 7671, 'author_profile': 'https://Stackoverflow.com/users/7671', 'pm_score': 2, 'selected': False, 'text': "<p>I've recently done both in a project and found:</p>\n\n<ol>\n<li>I prefer writing annotations to XML (plays well with static typing of Java, auto-complete in IDE, refactoring, etc). I like seeing the stuff all woven together rather than going back and forth between code and XML. </li>\n<li>Encodes db information in your classes. Some people find that gross and unacceptable. I can't say it bothered me. It has to go somewhere and we're going to rebuild the WAR for a change regardless. </li>\n<li>We actually went all the way to JPA annotations but there are definitely cases where the JPA annotations are not enough, so then had to use either Hibernate annotations or config to tweak.</li>\n<li>Note that you can actually use both annotations AND hbm files. Might be a nice hybrid that specifies the O part in annotations and R part in hbm files but sounds like more trouble than it's worth.</li>\n</ol>\n"}, {'answer_id': 89781, 'author': 'user17163', 'author_id': 17163, 'author_profile': 'https://Stackoverflow.com/users/17163', 'pm_score': 1, 'selected': False, 'text': "<p>I definitely prefer annotations, having used them both. They are much more maintainable and since you aren't dealing with that many classes to re-map, I would say it's worth it. The annotations make refactoring much easier.</p>\n"}, {'answer_id': 92949, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>"If it ain\'t broke - don\'t fix it!"</p>\n</blockquote>\n\n<p>@Macka - Thanks, I needed to hear that. And thanks to everyone for your answers. </p>\n\n<p>While I am in the very fortunate position of having an <strong><em>insane</em></strong> amount of professional and creative control over my work, and can bring in just about any technology, library, or tool for just about any reason (baring expensive stuff) including <em>"because all the cool kids are using it"</em>...It does not really make sense to port what amounts to a significant portion of the core of an existing project. </p>\n\n<p>I\'ll try out Hibernate or JPA annotations with a green-field project some time. Unfortunately, I rarely get new completely independent projects. </p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2961/'] |
82,232 | <p>Problem:<br/></p>
<ol>
<li>html file on local server (inside our organization) with link to an exe on the same server.</li>
<li>clicking the link runs the exe on the client. Instead I want it to offer downloading it.</li>
</ol>
<p>Tried so far:<br/></p>
<ol>
<li>Changed permissions on the exe's virtual directory to be read and script.</li>
<li>Added Content-disposition header on the exe's directory.</li>
<li>I can't change settings in the browser. It's intended for a lot of people to consume.</li>
</ol>
| [{'answer_id': 82246, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 2, 'selected': False, 'text': '<p>You need to set <code>content-disposition</code> in the HTTP header.</p>\n\n<p><a href="http://support.microsoft.com/kb/260519" rel="nofollow noreferrer">This Microsoft Knowledge Base entry</a> has more detail on how to do this.</p>\n'}, {'answer_id': 82251, 'author': 'Cetra', 'author_id': 15087, 'author_profile': 'https://Stackoverflow.com/users/15087', 'pm_score': -1, 'selected': False, 'text': '<p>Whether a file is downloaded or opened automatically is a browser, not a server, side setting.</p>\n\n<p>The other way of doing it would be to change the MIME type for the file to something like application/octet-stream or similar to try and force your browser to download it.</p>\n'}, {'answer_id': 82261, 'author': 'Duncan Smart', 'author_id': 1278, 'author_profile': 'https://Stackoverflow.com/users/1278', 'pm_score': 0, 'selected': False, 'text': "<p>Runs them where: on the server, or on the client? If on the server: set the handler mappings of the file so that CGI-exe is disabled. If on the client: then this is a web browser issue - it shouldn't be running EXEs directly! What browser is it? </p>\n\n<p>As Dave Webb mentions, you could use the <em>Content-Disposition</em> HTTP header: these can be added using <strong>HTTP Response Headers</strong> in IIS7 for that directory/file.</p>\n"}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11519/'] |
82,235 | <p>I'm experiencing the following very annoying behaviour when using JPA entitys in conjunction with Oracle 10g. </p>
<p>Suppose you have the following entity.</p>
<pre><code>@Entity
@Table(name = "T_Order")
public class TOrder implements Serializable {
private static final long serialVersionUID = 2235742302377173533L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "activationDate")
private Calendar activationDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Calendar getActivationDate() {
return activationDate;
}
public void setActivationDate(Calendar activationDate) {
this.activationDate = activationDate;
}
}
</code></pre>
<p>This entity is mapped to Oracle 10g, so in the DB there will be a table <code>T_ORDER</code> with a primary key <code>NUMBER</code> column <code>ID</code> and a <code>TIMESTAMP</code> column <code>activationDate</code>.</p>
<p>Lets suppose I create an instance of this class with the activation date <code>15. Sep 2008 00:00AM</code>. My local timezone is CEST which is <code>GMT+02:00</code>. When I persist this object and select the data from the table <code>T_ORDER</code> using sqlplus, I find out that in the table actually <code>14. Sep 2008 22:00</code> is stored, which is ok so far, because the oracle db timezone is GMT.</p>
<p>But now the annoying part. When I read this entity back into my JAVA program, I find out that the oracle time zone is ignored and I get <code>14. Sep 2008 22:00 CEST</code>, which is definitly wrong. </p>
<p>So basically, when writing to the DB the timezone information will be used, when reading it will be ignored.</p>
<p>Is there any solution for this out there? The most simple solution I guess would be to set the oracle dbs timezone to <code>GMT+02</code>, but unfortunatly I can't do this because there are other applications using the same server.</p>
<p>We use the following technology</p>
<p>MyEclipse 6.5
JPA with Hibernate 3.2
Oracle 10g thin JDBC Driver</p>
| [{'answer_id': 82416, 'author': 'Jeroen Wyseur', 'author_id': 15490, 'author_profile': 'https://Stackoverflow.com/users/15490', 'pm_score': 0, 'selected': False, 'text': '<p>I already had my share of problems with JPA and timestamps. I\'ve been reading in the <a href="http://forums.oracle.com/forums/thread.jspa?threadID=612075" rel="nofollow noreferrer">oracle forums</a> and please check the following:</p>\n\n<ul>\n<li>The field in the database should be TIMESTAMP_TZ and not just TIMESTAMP</li>\n<li>Try adding the annotation @Temporal(value = TemporalType.TIMESTAMP)</li>\n<li>If you don\'t really need the timezone, put in a date or timestamp field.</li>\n</ul>\n'}, {'answer_id': 85329, 'author': 'davetron5000', 'author_id': 3029, 'author_profile': 'https://Stackoverflow.com/users/3029', 'pm_score': 3, 'selected': True, 'text': '<p>You should not use a Calendar for accessing dates from the database, for this exact reason. You should use <code>java.util.Date</code> as so:</p>\n\n<pre><code>@Temporal(TemporalType.TIMESTAMP)\n@Column(name="activationDate")\npublic Date getActivationDate() {\n return this.activationDate;\n}\n</code></pre>\n\n<p><code>java.util.Date</code> points to a moment in time, irrespective of any timezones. Calendar can be used to format a date for a particular timezone or locale.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15657/'] |
82,256 | <p>I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.</p>
<p>The trouble is, this contrived example doesn't work:</p>
<pre><code>sudo ls -hal /root/ > /root/test.out
</code></pre>
<p>I just receive the response:</p>
<pre><code>-bash: /root/test.out: Permission denied
</code></pre>
<p>How can I get this to work?</p>
| [{'answer_id': 82274, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>How about writing a script?</p>\n\n<p>Filename: myscript</p>\n\n<pre><code>#!/bin/sh\n\n/bin/ls -lah /root > /root/test.out\n\n# end script\n</code></pre>\n\n<p>Then use sudo to run the script:</p>\n\n<pre><code>sudo ./myscript\n</code></pre>\n'}, {'answer_id': 82276, 'author': 'Penfold', 'author_id': 11952, 'author_profile': 'https://Stackoverflow.com/users/11952', 'pm_score': 5, 'selected': False, 'text': '<p>Make sudo run a shell, like this:</p>\n\n<pre><code>sudo sh -c "echo foo > ~root/out"\n</code></pre>\n'}, {'answer_id': 82278, 'author': 'Cristian Ciupitu', 'author_id': 12892, 'author_profile': 'https://Stackoverflow.com/users/12892', 'pm_score': 12, 'selected': True, 'text': '<p>Your command does not work because the redirection is performed by your shell which does not have the permission to write to <code>/root/test.out</code>. The redirection of the output <strong>is not</strong> performed by sudo.</p>\n\n<p>There are multiple solutions:</p>\n\n<ul>\n<li><p>Run a shell with sudo and give the command to it by using the <code>-c</code> option:</p>\n\n<pre><code>sudo sh -c \'ls -hal /root/ > /root/test.out\'\n</code></pre></li>\n<li><p>Create a script with your commands and run that script with sudo:</p>\n\n<pre><code>#!/bin/sh\nls -hal /root/ > /root/test.out\n</code></pre>\n\n<p>Run <code>sudo ls.sh</code>. See Steve Bennett\'s <a href="https://stackoverflow.com/a/16514624/12892">answer</a> if you don\'t want to create a temporary file.</p></li>\n<li><p>Launch a shell with <code>sudo -s</code> then run your commands:</p>\n\n<pre><code>[nobody@so]$ sudo -s\n[root@so]# ls -hal /root/ > /root/test.out\n[root@so]# ^D\n[nobody@so]$\n</code></pre></li>\n<li><p>Use <code>sudo tee</code> (if you have to escape a lot when using the <code>-c</code> option):</p>\n\n<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null\n</code></pre>\n\n<p>The redirect to <code>/dev/null</code> is needed to stop <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/tee.html" rel="noreferrer"><strong>tee</strong></a> from outputting to the screen. To <em>append</em> instead of overwriting the output file \n(<code>>></code>), use <code>tee -a</code> or <code>tee --append</code> (the last one is specific to <a href="https://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer">GNU coreutils</a>).</p></li>\n</ul>\n\n<p>Thanks go to <a href="https://stackoverflow.com/a/82274/12892">Jd</a>, <a href="https://stackoverflow.com/a/82279/12892">Adam J. Forster</a> and <a href="https://stackoverflow.com/a/82553/12892">Johnathan</a> for the second, third and fourth solutions.</p>\n'}, {'answer_id': 82279, 'author': 'Adam J. Forster', 'author_id': 15676, 'author_profile': 'https://Stackoverflow.com/users/15676', 'pm_score': 3, 'selected': False, 'text': "<p>Whenever I have to do something like this I just become root:</p>\n\n<pre><code># sudo -s\n# ls -hal /root/ > /root/test.out\n# exit\n</code></pre>\n\n<p>It's probably not the best way, but it works.</p>\n"}, {'answer_id': 82331, 'author': 'user15453', 'author_id': 15453, 'author_profile': 'https://Stackoverflow.com/users/15453', 'pm_score': 1, 'selected': False, 'text': '<p>Maybe you been given sudo access to only some programs/paths? Then there is no way to do what you want. (unless you will hack it somehow)</p>\n\n<p>If it is not the case then maybe you can write bash script:</p>\n\n<pre><code>cat > myscript.sh\n#!/bin/sh\nls -hal /root/ > /root/test.out \n</code></pre>\n\n<p>Press <kbd>ctrl</kbd> + <kbd>d</kbd> :</p>\n\n<pre><code>chmod a+x myscript.sh\nsudo myscript.sh\n</code></pre>\n\n<p>Hope it help.</p>\n'}, {'answer_id': 82553, 'author': 'Jonathan', 'author_id': 6910, 'author_profile': 'https://Stackoverflow.com/users/6910', 'pm_score': 7, 'selected': False, 'text': '<p>Someone here has just suggested sudoing tee:</p>\n\n<pre><code>sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null\n</code></pre>\n\n<p>This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.</p>\n'}, {'answer_id': 120174, 'author': 'dsm', 'author_id': 7780, 'author_profile': 'https://Stackoverflow.com/users/7780', 'pm_score': 6, 'selected': False, 'text': "<p>The problem is that the <strong>command</strong> gets run under <code>sudo</code>, but the <strong>redirection</strong> gets run under your user. This is done by the shell and there is very little you can do about it.</p>\n<pre><code>sudo command > /some/file.log\n`-----v-----'`-------v-------'\n command redirection\n</code></pre>\n<p>The usual ways of bypassing this are:</p>\n<ul>\n<li><p>Wrap the commands in a script which you call under sudo.</p>\n<p>If the commands and/or log file changes, you can make the\nscript take these as arguments. For example:</p>\n<pre><code>sudo log_script command /log/file.txt\n</code></pre>\n</li>\n<li><p>Call a shell and pass the command line as a parameter with <code>-c</code></p>\n<p>This is especially useful for one off compound commands.\nFor example:</p>\n<pre><code>sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt"\n</code></pre>\n</li>\n<li><p>Arrange a pipe/subshell with required rights (i.e. sudo)</p>\n<pre><code># Read and append to a file\ncat ./'file1.txt' | sudo tee -a '/log/file.txt' > '/dev/null';\n\n# Store both stdout and stderr streams in a file\n{ command1 arg; command2 arg; } |& sudo tee -a '/log/file.txt' > '/dev/null';\n</code></pre>\n</li>\n</ul>\n"}, {'answer_id': 8213307, 'author': 'rhlee', 'author_id': 420540, 'author_profile': 'https://Stackoverflow.com/users/420540', 'pm_score': 7, 'selected': False, 'text': '<p>A trick I figured out myself was</p>\n\n<pre><code>sudo ls -hal /root/ | sudo dd of=/root/test.out\n</code></pre>\n'}, {'answer_id': 16131140, 'author': 'fardjad', 'author_id': 303270, 'author_profile': 'https://Stackoverflow.com/users/303270', 'pm_score': 3, 'selected': False, 'text': "<p>I would do it this way:</p>\n\n<pre><code>sudo su -c 'ls -hal /root/ > /root/test.out'\n</code></pre>\n"}, {'answer_id': 16514624, 'author': 'Steve Bennett', 'author_id': 263268, 'author_profile': 'https://Stackoverflow.com/users/263268', 'pm_score': 5, 'selected': False, 'text': "<p>Yet another variation on the theme:</p>\n\n<pre><code>sudo bash <<EOF\nls -hal /root/ > /root/test.out\nEOF\n</code></pre>\n\n<p>Or of course:</p>\n\n<pre><code>echo 'ls -hal /root/ > /root/test.out' | sudo bash\n</code></pre>\n\n<p>They have the (tiny) advantage that you don't need to remember any arguments to <code>sudo</code> or <code>sh</code>/<code>bash</code></p>\n"}, {'answer_id': 19738137, 'author': 'jg3', 'author_id': 2094009, 'author_profile': 'https://Stackoverflow.com/users/2094009', 'pm_score': 5, 'selected': False, 'text': '<p><em>Clarifying a bit on why the tee option is preferable</em></p>\n\n<p>Assuming you have appropriate permission to execute the command that creates the output, if you pipe the output of your command to tee, you only need to elevate tee\'s privledges with sudo and direct tee to write (or append) to the file in question.</p>\n\n<p>in the example given in the question that would mean:</p>\n\n<pre><code>ls -hal /root/ | sudo tee /root/test.out\n</code></pre>\n\n<p>for a couple more practical examples:</p>\n\n<pre><code># kill off one source of annoying advertisements\necho 127.0.0.1 ad.doubleclick.net | sudo tee -a /etc/hosts\n\n# configure eth4 to come up on boot, set IP and netmask (centos 6.4)\necho -e "ONBOOT=\\"YES\\"\\nIPADDR=10.42.84.168\\nPREFIX=24" | sudo tee -a /etc/sysconfig/network-scripts/ifcfg-eth4\n</code></pre>\n\n<p>In each of these examples you are taking the output of a non-privileged command and writing to a file that is usually only writable by root, which is the origin of your question.</p>\n\n<p>It is a good idea to do it this way because the command that generates the output is not executed with elevated privileges. It doesn\'t seem to matter here with <code>echo</code> but when the source command is a script that you don\'t completely trust, it is crucial.</p>\n\n<p>Note you can use the -a option to tee to append append (like <code>>></code>) to the target file rather than overwrite it (like <code>></code>).</p>\n'}, {'answer_id': 20234210, 'author': 'jamadagni', 'author_id': 1503120, 'author_profile': 'https://Stackoverflow.com/users/1503120', 'pm_score': 2, 'selected': False, 'text': '<p>This is based on the answer involving <code>tee</code>. To make things easier I wrote a small script (I call it <code>suwrite</code>) and put it in <code>/usr/local/bin/</code> with <code>+x</code> permission:</p>\n\n<pre><code>#! /bin/sh\nif [ $# = 0 ] ; then\n echo "USAGE: <command writing to stdout> | suwrite [-a] <output file 1> ..." >&2\n exit 1\nfi\nfor arg in "$@" ; do\n if [ ${arg#/dev/} != ${arg} ] ; then\n echo "Found dangerous argument ‘$arg’. Will exit."\n exit 2\n fi\ndone\nsudo tee "$@" > /dev/null\n</code></pre>\n\n<p>As shown in the <strong>USAGE</strong> in the code, all you have to do is to pipe the output to this script followed by the desired superuser-accessible filename and it will automatically prompt you for your password if needed (since it includes <code>sudo</code>).</p>\n\n<pre><code>echo test | suwrite /root/test.txt\n</code></pre>\n\n<p>Note that since this is a simple wrapper for <code>tee</code>, it will also accept tee\'s <code>-a</code> option to append, and also supports writing to multiple files at the same time.</p>\n\n<pre><code>echo test2 | suwrite -a /root/test.txt\necho test-multi | suwrite /root/test-a.txt /root/test-b.txt\n</code></pre>\n\n<p>It also has some simplistic protection against writing to <code>/dev/</code> devices which was a concern mentioned in one of the comments on this page.</p>\n'}, {'answer_id': 38021076, 'author': 'Nikola Petkanski', 'author_id': 581062, 'author_profile': 'https://Stackoverflow.com/users/581062', 'pm_score': 4, 'selected': False, 'text': '<p>The way I would go about this issue is:</p>\n\n<p>If you need to write/replace the file:</p>\n\n<pre><code>echo "some text" | sudo tee /path/to/file\n</code></pre>\n\n<p>If you need to append to the file:</p>\n\n<pre><code>echo "some text" | sudo tee -a /path/to/file\n</code></pre>\n'}, {'answer_id': 38632314, 'author': 'haridsv', 'author_id': 95750, 'author_profile': 'https://Stackoverflow.com/users/95750', 'pm_score': 4, 'selected': False, 'text': '<p>Don\'t mean to beat a dead horse, but there are too many answers here that use <code>tee</code>, which means you have to redirect <code>stdout</code> to <code>/dev/null</code> unless you want to see a copy on the screen. </p>\n\n<p>A simpler solution is to just use <code>cat</code> like this:</p>\n\n<pre><code>sudo ls -hal /root/ | sudo bash -c "cat > /root/test.out"\n</code></pre>\n\n<p>Notice how the redirection is put inside quotes so that it is evaluated by a shell started by <code>sudo</code> instead of the one running it.</p>\n'}, {'answer_id': 46342096, 'author': 'user8648126', 'author_id': 8648126, 'author_profile': 'https://Stackoverflow.com/users/8648126', 'pm_score': 2, 'selected': False, 'text': '<pre><code>sudo at now \nat> echo test > /tmp/test.out \nat> <EOT> \njob 1 at Thu Sep 21 10:49:00 2017 \n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6910/'] |
82,259 | <p>Ever wanted to have an HTML drag and drop sortable table in which you could sort both rows and columns? I know it's something I'd die for. There's a lot of sortable lists going around but finding a sortable table seems to be impossible to find. </p>
<p>I know that you can get pretty close with the tools that script.aculo.us provides but I ran into some cross-browser issues with them. </p>
| [{'answer_id': 82297, 'author': 'David Precious', 'author_id': 4040, 'author_profile': 'https://Stackoverflow.com/users/4040', 'pm_score': -1, 'selected': False, 'text': '<p>How about <a href="http://www.kryogenix.org/code/browser/sorttable/" rel="nofollow noreferrer">sorttable</a>? That would seem to fit your requirements nicely.</p>\n\n<p>It\'s rather easy to use - load the sorttable Javascript file, then, for each table you want it to make sortable, apply class="sortable" to the <table> tag.</p>\n\n<p>It will immediately understand how to sort most types of data, but if there\'s something it doesn\'t, you can add a custom sort key to tell it how to sort. The documentation explains it all pretty well.</p>\n'}, {'answer_id': 82347, 'author': 'Neall', 'author_id': 619, 'author_profile': 'https://Stackoverflow.com/users/619', 'pm_score': 3, 'selected': False, 'text': '<p>I recommend <a href="http://docs.jquery.com/UI/Sortables" rel="noreferrer">Sortables</a> in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>. You can use it on list items or pretty much anything, including tables.</p>\n\n<p>jQuery is very cross-browser friendly and I recommend it all the time.</p>\n'}, {'answer_id': 82448, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': 0, 'selected': False, 'text': '<p>If you don\'t mind Java, there is a very handy library for GWT called <a href="http://code.google.com/p/gwt-dnd/" rel="nofollow noreferrer">GWT-DND</a> check out the online demo to see how powerful it is.</p>\n'}, {'answer_id': 82816, 'author': 'msanders', 'author_id': 1002, 'author_profile': 'https://Stackoverflow.com/users/1002', 'pm_score': 3, 'selected': True, 'text': '<p>I\'ve used <a href="http://www.dhtmlx.com/docs/products/dhtmlxGrid/index.shtml" rel="nofollow noreferrer">dhtmlxGrid</a> in the past. Among other things it supports drag-and-drop rows/columns, client-side sorting (string, integer, date, custom) and multi-browser support.</p>\n\n<p>Response to comment:\nNo, not found anything better - just moved on from that project. :-)</p>\n'}, {'answer_id': 85082, 'author': 'Anutron', 'author_id': 10071, 'author_profile': 'https://Stackoverflow.com/users/10071', 'pm_score': 1, 'selected': False, 'text': '<p>Most frameworks (Yui, MooTools, jQuery, Prototype/Scriptaculous, etc.) have sortable list functionality. Do a little research into each and pick the one that suits your needs most.</p>\n'}, {'answer_id': 100514, 'author': 'David Heggie', 'author_id': 4309, 'author_profile': 'https://Stackoverflow.com/users/4309', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve used jQuery UI\'s sortable plugin with good results. Markup similar to this:</p>\n\n<pre><code><table id="myTable">\n<thead>\n<tr><th>ID</th><th>Name</th><th>Details</th></tr>\n</thead>\n<tbody class="sort">\n<tr id="1"><td>1</td><td>Name1</td><td>Details1</td></tr>\n<tr id="2"><td>2</td><td>Name1</td><td>Details2</td></tr>\n<tr id="3"><td>3</td><td>Name1</td><td>Details3</td></tr>\n<tr id="4"><td>4</td><td>Name1</td><td>Details4</td></tr>\n</tbody>\n</table>\n</code></pre>\n\n<p>and then in the javascript</p>\n\n<pre><code>$(\'.sort\').sortable({\n cursor: \'move\',\n axis: \'y\',\n update: function(e, ui) {\n href = \'/myReorderFunctionURL/\';\n $(this).sortable("refresh");\n sorted = $(this).sortable("serialize", \'id\');\n $.ajax({\n type: \'POST\',\n url: href,\n data: sorted,\n success: function(msg) {\n //do something with the sorted data\n }\n });\n }\n});\n</code></pre>\n\n<p>This POSTs a serialized version of the items\' IDs to the URL given. This function (PHP in my case) then updates the items\' orders in the database.</p>\n'}, {'answer_id': 362459, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>David Heggie\'s answer was the most useful to me. It can be slightly more concise:</p>\n\n<pre><code>var sort = function(event, ui) {\n var url = "/myReorderFunctionURL/" + $(this).sortable(\'serialize\');\n $.post(url, null,null,"script"); // sortable("refresh") is automatic\n}\n\n$(".sort").sortable({\n cursor: \'move\',\n axis: \'y\',\n stop: sort\n});\n</code></pre>\n\n<p>works for me, with the same markup.</p>\n'}, {'answer_id': 11133174, 'author': 'CDR', 'author_id': 50542, 'author_profile': 'https://Stackoverflow.com/users/50542', 'pm_score': 0, 'selected': False, 'text': '<p>If you find .serialize() returning null in David Heggie\'s solution then set the id values for the TRs as \'id_1\' instead of simply \'1\'</p>\n\n<p>Example:</p>\n\n<pre><code><tr id="id_1"><td>1</td><td>Name1</td><td>Details1</td></tr>\n<tr id="id_2"><td>2</td><td>Name1</td><td>Details2</td></tr>\n<tr id="id_3"><td>3</td><td>Name1</td><td>Details3</td></tr>\n<tr id="id_4"><td>4</td><td>Name1</td><td>Details4</td></tr>\n</code></pre>\n\n<p>The above will serialize as "id[]=1&id[]=2&id[]=3"</p>\n\n<p>You can use \'=\', \'-\' or \'_\' instead of \'_\'.\nAnd any other word besides "id".</p>\n'}, {'answer_id': 54500687, 'author': 'PirateApp', 'author_id': 5371505, 'author_profile': 'https://Stackoverflow.com/users/5371505', 'pm_score': 0, 'selected': False, 'text': '<p>I am using JQuery Sortable to do so but in case, you are using Vue.js like me, here is a solution that creates a custom Vue directive to encapsulate the Sortable functionality, I am aware of Vue draggable but it doesnt sort table columns as per the issue <a href="https://github.com/SortableJS/Vue.Draggable/issues/456" rel="nofollow noreferrer">HERE</a> To see this in action, <a href="https://codepen.io/zupkode/pen/VgbRdQ" rel="nofollow noreferrer">CHECK THIS</a></p>\n\n<p><strong>JS Code</strong></p>\n\n<pre><code>Vue.directive("draggable", {\n //adapted from https://codepen.io/kminek/pen/pEdmoo\n inserted: function(el, binding, a) {\n Sortable.create(el, {\n draggable: ".draggable",\n onEnd: function(e) {\n /* vnode.context is the context vue instance: "This is not documented as it\'s not encouraged to manipulate the vm from directives in Vue 2.0 - instead, directives should be used for low-level DOM manipulation, and higher-level stuff should be solved with components instead. But you can do this if some usecase needs this. */\n // fixme: can this be reworked to use a component?\n // https://github.com/vuejs/vue/issues/4065\n // https://forum.vuejs.org/t/how-can-i-access-the-vm-from-a-custom-directive-in-2-0/2548/3\n // https://github.com/vuejs/vue/issues/2873 "directive interface change"\n // `binding.expression` should be the name of your array from vm.data\n // set the expression like v-draggable="items"\n\n var clonedItems = a.context[binding.expression].filter(function(item) {\n return item;\n });\n clonedItems.splice(e.newIndex, 0, clonedItems.splice(e.oldIndex, 1)[0]);\n a.context[binding.expression] = [];\n Vue.nextTick(function() {\n a.context[binding.expression] = clonedItems;\n });\n\n }\n });\n }\n});\n\nconst cols = [\n {name: "One", id: "one", canMove: false},\n {name: "Two", id: "two", canMove: true},\n {name: "Three", id: "three", canMove: true},\n {name: "Four", id: "four", canMove: true},\n]\n\nconst rows = [\n {one: "Hi there", two: "I am so excited to test", three: "this column that actually drags and replaces", four: "another column in its place only if both can move"},\n {one: "Hi", two: "I", three: "am", four: "two"},\n {one: "Hi", two: "I", three: "am", four: "three"},\n {one: "Hi", two: "I", three: "am", four: "four"},\n {one: "Hi", two: "I", three: "am", four: "five"},\n {one: "Hi", two: "I", three: "am", four: "six"},\n {one: "Hi", two: "I", three: "am", four: "seven"}\n]\n\nVue.component("datatable", {\n template: "#datatable",\n data() {\n return {\n cols: cols,\n rows: rows\n }\n }\n})\n\nnew Vue({\n el: "#app"\n})\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.draggable {\n cursor: move;\n}\n\ntable.table tbody td {\n white-space: nowrap;\n}\n</code></pre>\n\n<p><strong>Pug Template HTML</strong></p>\n\n<pre><code>#app\n datatable\n\nscript(type="text/x-template" id="datatable")\n table.table\n thead(v-draggable="cols")\n template(v-for="c in cols")\n th(:class="{draggable: c.canMove}")\n b-dropdown#ddown1.m-md-2(:text=\'c.name\')\n b-dropdown-item First Action\n b-dropdown-item Second Action\n b-dropdown-item Third Action\n b-dropdown-divider\n b-dropdown-item Something else here...\n b-dropdown-item(disabled=\'\') Disabled action\n\n tbody\n template(v-for="row in rows")\n tr\n template(v-for="(col, index) in cols")\n td {{row[col.id]}}\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7382/'] |
82,264 | <p>Is it possible to do pseudo-streaming(eg start playback at any point) with wmv files and silverlight? </p>
<p>This is possible using Flash in a progressive download setup but can it be done on the Microsoft track?</p>
| [{'answer_id': 86404, 'author': 'artur02', 'author_id': 13937, 'author_profile': 'https://Stackoverflow.com/users/13937', 'pm_score': 1, 'selected': False, 'text': '<p>You can <strong>use <a href="http://www.microsoft.com/windows/windowsmedia/forpros/server/version.aspx" rel="nofollow noreferrer">Windows Media Services 2008</a></strong>. It enables you to actually stream WMV to Silverlight interface.</p>\n'}, {'answer_id': 1235586, 'author': 'Robert Fraser', 'author_id': 125601, 'author_profile': 'https://Stackoverflow.com/users/125601', 'pm_score': 0, 'selected': False, 'text': "<p>No reason you couldn't stream it like any other HTTP video; it basically just expects the file to be a correct WMV file. You would need to have a server that supports the seeking, though.</p>\n"}, {'answer_id': 1492230, 'author': 'Geoff Appleford', 'author_id': 7793, 'author_profile': 'https://Stackoverflow.com/users/7793', 'pm_score': 1, 'selected': True, 'text': '<p>Since asking this question, Microsoft has released <a href="http://www.iis.net/extensions/SmoothStreaming" rel="nofollow noreferrer">Smooth Streaming</a>, which is exactly what I was asking for and more.</p>\n\n<p>Clearly this is the best Silverlight solution although you do need Windows Server 2008 on the backend.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7793/'] |
82,268 | <p>I have to deal with text files in a motley selection of formats. Here's an example (Columns <strong>A</strong> and <strong>B</strong> are tab delimited):</p>
<pre><code>A B
a Name1=Val1, Name2=Val2, Name3=Val3
b Name1=Val4, Name3=Val5
c Name1=Val6, Name2=Val7, Name3=Val8
</code></pre>
<p>The files could have headers or not, have mixed delimiting schemes, have columns with name/value pairs as above etc.<br>
I often have the ad-hoc need to extract data from such files in various ways. For example from the above data I might want the value associated with Name2 where it is present. i.e.</p>
<pre><code>A B
a Val2
c Val7
</code></pre>
<p>What tools/techniques are there for performing such manipulations as one line commands, using the above as an example but extensible to other cases?</p>
| [{'answer_id': 82282, 'author': 'auramo', 'author_id': 4110, 'author_profile': 'https://Stackoverflow.com/users/4110', 'pm_score': 1, 'selected': False, 'text': '<p>You have all the basic bash shell commands, for example grep, cut, sed and awk at your disposal. You can also use Perl or Ruby for more complex things.</p>\n'}, {'answer_id': 82293, 'author': 'Onorio Catenacci', 'author_id': 2820, 'author_profile': 'https://Stackoverflow.com/users/2820', 'pm_score': 0, 'selected': False, 'text': "<p>From what I've seen I'd start with Awk for this sort of thing and then if you need something more complex, I'd progress to Python.</p>\n"}, {'answer_id': 82300, 'author': 'Cetra', 'author_id': 15087, 'author_profile': 'https://Stackoverflow.com/users/15087', 'pm_score': 0, 'selected': False, 'text': "<p>I would use sed:</p>\n\n<pre><code> # print section of file between two regular expressions (inclusive)\n sed -n '/Iowa/,/Montana/p' # case sensitive\n</code></pre>\n"}, {'answer_id': 82330, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Since you have cygwin, I\'d go with Perl. It\'s the easiest to learn (check out the O\'Reily book: <a href="http://books.google.com/books?id=bS--s5DAIHsC&dq=%22learning+perl%22&pg=PP1&ots=udTVanap5Y&sig=gJW55LqGpEXCHqRMgHfTJ8nmP70&hl=en&sa=X&oi=book_result&resnum=1&ct=result" rel="nofollow noreferrer">Learning Perl</a>) and widely applicable.</p>\n'}, {'answer_id': 82353, 'author': 'Weidenrinde', 'author_id': 11344, 'author_profile': 'https://Stackoverflow.com/users/11344', 'pm_score': 2, 'selected': True, 'text': '<p>I don\'t like sed too much, but it works for such things:</p>\n\n<pre><code>var="Name2";sed -n "1p;s/\\([^ ]*\\) .*$var=\\([^ ,]*\\).*/\\1 \\2/p" < filename\n</code></pre>\n\n<p>Gives you:</p>\n\n<pre><code> A B\n a Val2\n c Val7\n</code></pre>\n'}, {'answer_id': 82557, 'author': 'deterb', 'author_id': 15585, 'author_profile': 'https://Stackoverflow.com/users/15585', 'pm_score': 0, 'selected': False, 'text': '<p>I would use Perl. Write a small module (or more than one) for dealing with the different formats. You could then run perl oneliners using that library. Example for what it would\nlook like as follows:</p>\n\n<pre><code>perl -e \'use Parser;\' -e \'parser("in.input").get("Name2");\'\n</code></pre>\n\n<p>Don\'t quote me on the syntax, but that\'s the general idea. Abstract the task at hand to allow you to think in terms of what you need to do, not how you need to do it. Ruby would be another option, it tends to have a cleaner syntax, but either language would work.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6387/'] |
82,269 | <p>I have a SharePoint site with multiple lists, some of which have the same fields - a choice of products or countries.</p>
<p>How can I build the lists in a way that I configure the choice field once and use it in multiple lists, so that in the future, if I add a value to the choice, I add it only once?</p>
| [{'answer_id': 82630, 'author': 'Eugene Katz', 'author_id': 1533, 'author_profile': 'https://Stackoverflow.com/users/1533', 'pm_score': 0, 'selected': False, 'text': '<p>You should create a list which contains the countries. Then in the lists where you want to reuse the countries lookup, create a column of type Lookup and select the countries list in the "Get infomation from" dropdown.</p>\n\n<p>Here is a link to a more visual guide:\n<a href="http://blog.phase2int.com/?p=101" rel="nofollow noreferrer">http://blog.phase2int.com/?p=101</a></p>\n'}, {'answer_id': 82695, 'author': 'Jason Z', 'author_id': 2470, 'author_profile': 'https://Stackoverflow.com/users/2470', 'pm_score': 2, 'selected': True, 'text': '<p>If you go to Site Settings, under Galleries there is an option for Site Columns. You can create your choice list there. Then, under the Library Settings there is an option to Add From Existing Site Columns. You should be able to see and select your newly created column there.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15637/'] |
82,286 | <p>I want to place a Webpart on a page that holds a subfolder of the Document Library in SharePoint, but somehow, the only thing I get is the root folder of the document library.</p>
<p>Is there a Webpart that fills this need?</p>
| [{'answer_id': 82405, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': True, 'text': "<p>By default I don't think that is possible.</p>\n\n<p>The list web part that would show the Shared Documents understands how to render the library, but doesn't understand how to filter to only show the contents of one subfolder.</p>\n\n<p>It would be nice to create a Filter Web Part and to provide that filter to the List web part so that it filters according to the sub folder defined within the fileref field of the document library. However the filters it appears to be able to consume are Type, Modified and Modified By. So you could filter it to just the documents you touched, but not the ones in a given location.</p>\n\n<p>End result: Roll your own web part.</p>\n"}, {'answer_id': 156049, 'author': 'Nat', 'author_id': 13813, 'author_profile': 'https://Stackoverflow.com/users/13813', 'pm_score': 1, 'selected': False, 'text': '<p>The reason is that the folder selected by the webpart is not controlled by the webpart itself, but by a querystring parameter.</p>\n\n<p>e.g.</p>\n\n<pre><code>"?RootFolder=%2fDocuments%2fMyFolder1&FolderCTID="\n</code></pre>\n\n<p>So folders are not "real" folders as such, despite the "lie" that is the webdav interface\n e.g. <code>\\\\sharepointsite\\documents</code></p>\n\n<p>There should be a way of including the desired RootFolder parameter, like a linking to the page with the querystring included (far from ideal).</p>\n\n<p>I do not know of any webparts that do this.</p>\n'}, {'answer_id': 4696692, 'author': 'Denis M. Kitchen', 'author_id': 120638, 'author_profile': 'https://Stackoverflow.com/users/120638', 'pm_score': 0, 'selected': False, 'text': '<p>One alternative I\'ve used is to drop a Page Viewer Web Part on the page and choose "Folder" as the type of thing to view. Then specify the webdav UNC to the folder such as "\\some_sharepoint-site\\some_site\\shared documents\\some_folder\\"</p>\n'}, {'answer_id': 12008006, 'author': 'Derek', 'author_id': 1607210, 'author_profile': 'https://Stackoverflow.com/users/1607210', 'pm_score': 2, 'selected': False, 'text': '<p>Here is how to do it in Sharepoint 2010 with only Javascript, no SharePoint Designer necessary.</p>\n\n<ol>\n<li>create a document library web part on your web part page</li>\n<li>change the view to show all items without folders and set the item limit to a sufficiently large number so that there are no batches</li>\n<li>add Content Editor web part <em>below</em> document library web part</li>\n<li>Add the following javascript and change the the first variable to meet your needs</li>\n</ol>\n\n<p>Note: If you have more than one Document Library web part, you will need to add to this code.</p>\n\n<pre><code><script type="text/javascript" language="javascript">\n\n //change this to meet your needs\n var patt = /FOLDER%20TO%20SEARCH/gi; \n var x = document.getElementsByTagName("TD"); // find all of the TDs\n var i=0; \n\n for (i=0;i<x.length;i++)\n {\n if (x[i].className =="ms-vb-title") //find the TDs styled for documents\n {\n var y = x[i].getElementsByTagName("A"); //this gets the URL linked to the name field\n //conveniently the URL is the first variable in the array. YMMV.\n var title = y[0]; \n\n //search for pattern\n var result = patt.test(title);\n\n //If the pattern isn\'t in that row, do not display the row\n if ( !result )\n {\n x[i].parentNode.style.display = "none"; //and hide the row \n }\n }\n } \n</script> \n</code></pre>\n'}, {'answer_id': 18026927, 'author': 'Jennifer Kong', 'author_id': 2647484, 'author_profile': 'https://Stackoverflow.com/users/2647484', 'pm_score': 1, 'selected': False, 'text': '<p>I was able to do this by creating a new Column and specifying a keyword for the entire Shared Documents list. </p>\n\n<p>Then I had to add metadata.\nAdd the WebPart again to the page.\nCreate a View that enabled the display of the files as a flat list, and filter on the new Column (i.e. where Keyword is/contains ----).\nThen I get the list I want on the page with the web part.</p>\n'}, {'answer_id': 20639690, 'author': 'Asad Ali Sandhu', 'author_id': 3112066, 'author_profile': 'https://Stackoverflow.com/users/3112066', 'pm_score': 0, 'selected': False, 'text': '<p>Place the document library list view web part on any page.\nEdit the web part.\nFrom filter select column "Content Type" and value "Folder"\nSave and you are done. </p>\n\n<p>By doing that it will show you root folder files only.</p>\n'}, {'answer_id': 29227940, 'author': 'JohnDUSA', 'author_id': 3612746, 'author_profile': 'https://Stackoverflow.com/users/3612746', 'pm_score': 1, 'selected': False, 'text': "<p>I have a work around I've used that doesn't required Designer. Not as elegant, but achievable by any power user.</p>\n\n<p>After you've added the library web part, go to the page and click down to the folder you want to be the default. See that the page link now shows something like : \n<code>www.mysite.com/sharepoint/default.aspx?RootFolder=%2Fsubfoldername&FolderCTID=...</code></p>\n\n<p>Copy that link. Delete <code>&FolderCTID</code> and everything that follows. In this case what remains is :<br>\n<code>www.mysite.com/sharepoint/default.aspx?RootFolder=%2Fsubfoldername</code></p>\n\n<p>Use this link for navigation to the page and the library will display as you want within that page. Be aware it does not replace the default view for that page.</p>\n"}, {'answer_id': 47141636, 'author': 'Alberto S.', 'author_id': 1538604, 'author_profile': 'https://Stackoverflow.com/users/1538604', 'pm_score': 1, 'selected': False, 'text': '<p>Another way of face this issue would be to just use the Content Search WebPart ( CSWP ) and filter the results based on : </p>\n\n<ul>\n<li>folder path</li>\n<li>url depth</li>\n</ul>\n\n<p>You will need a UrlDepth value that matches your requirement. The best thing is to use a high value, like 10, and then reduce until it shows just the files you need.\nRegarding folder path, remove the (quotes) ", this way the query will perform a "contains" lookup, instead of "equal to":</p>\n\n<p>Result will be something like this:</p>\n\n<pre><code>path:[your site]/Docs/our_team UrlDepth:7 \n</code></pre>\n\n<p>If the <strong>folder name contains spaces</strong>, you may need to wraps it with quotes. something like:</p>\n\n<pre><code>path:[your site]/Docs/"our team"\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15637/'] |
82,319 | <p>In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there:
(channels) * (bits) * (samples/s) * (seconds) = (filesize)</p>
<p>Is there a simpler way - a free library, or something in the .net framework perhaps?</p>
<p>How would I do this if the .wav file is compressed (with the mpeg codec for example)?</p>
| [{'answer_id': 82344, 'author': 'xan', 'author_id': 15667, 'author_profile': 'https://Stackoverflow.com/users/15667', 'pm_score': 1, 'selected': False, 'text': '<p>You might find that the <a href="http://msdn.microsoft.com/en-us/xna/default.aspx" rel="nofollow noreferrer">XNA library</a> has some support for working with WAV\'s etc. if you are willing to go down that route. It is designed to work with C# for game programming, so might just take care of what you need.</p>\n'}, {'answer_id': 82364, 'author': 'moobaa', 'author_id': 3569, 'author_profile': 'https://Stackoverflow.com/users/3569', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s a bit of a tutorial (with - presumably - working code you can leverage) over at <a href="http://www.codeproject.com/KB/audio-video/WaveEdit.aspx" rel="nofollow noreferrer">CodeProject</a>.</p>\n\n<p>The only thing you have to be a little careful of is that it\'s perfectly "normal" for a WAV file to be composed of multiple chunks - so you have to scoot over the entire file to ensure that all chunks are accounted for.</p>\n'}, {'answer_id': 82379, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>What exactly is your application doing with compressed WAVs? Compressed WAV files are always tricky - I always try and use an alternative container format in this case such as OGG or WMA files. The XNA libraries tend to be designed to work with specific formats - although it is possible that within XACT you'll find a more generic wav playback method. A possible alternative is to look into the SDL C# port, although I've only ever used it to play uncompressed WAVs - once opened you can query the number of samples to determine the length.</p>\n"}, {'answer_id': 82394, 'author': 'Cetra', 'author_id': 15087, 'author_profile': 'https://Stackoverflow.com/users/15087', 'pm_score': 2, 'selected': False, 'text': '<p>In the .net framework there is a mediaplayer class:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer_members.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer_members.aspx</a></p>\n\n<p>Here is an example:</p>\n\n<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2667714&SiteID=1&pageid=0#2685871" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2667714&SiteID=1&pageid=0#2685871</a></p>\n'}, {'answer_id': 82408, 'author': 'Jan Zich', 'author_id': 15716, 'author_profile': 'https://Stackoverflow.com/users/15716', 'pm_score': 6, 'selected': True, 'text': '<p>You may consider using the mciSendString(...) function (error checking is omitted for clarity):</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace Sound\n{\n public static class SoundInfo\n {\n [DllImport("winmm.dll")]\n private static extern uint mciSendString(\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle);\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format("open \\"{0}\\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);\n mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString("close wave", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n }\n}\n</code></pre>\n'}, {'answer_id': 82439, 'author': 'sieben', 'author_id': 1147, 'author_profile': 'https://Stackoverflow.com/users/1147', 'pm_score': 1, 'selected': False, 'text': '<p>I\'m gonna have to say <a href="http://mediainfo.sourceforge.net/en" rel="nofollow noreferrer">MediaInfo</a>, I have been using it for over a year with a audio/video encoding application I\'m working on. It gives all the information for wav files along with almost every other format.</p>\n\n<p><a href="http://sourceforge.net/project/showfiles.php?group_id=86862&package_id=90614" rel="nofollow noreferrer">MediaInfoDll</a> Comes with sample C# code on how to get it working.</p>\n'}, {'answer_id': 83276, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m going to assume that you\'re somewhat familiar with the structure of a .WAV file : it contains a WAVEFORMATEX header struct, followed by a number of other structs (or "chunks") containing various kinds of information. See <a href="http://en.wikipedia.org/wiki/WAV" rel="nofollow noreferrer">Wikipedia</a> for more info on the file format.</p>\n\n<p>First, iterate through the .wav file and add up the the unpadded lengths of the "data" chunks (the "data" chunk contains the audio data for the file; usually there is only one of these, but it\'s possible that there could be more than one). You now have the total size, in bytes, of the audio data.</p>\n\n<p>Next, get the "average bytes per second" member of the WAVEFORMATEX header struct of the file.</p>\n\n<p>Finally, divide the total size of the audio data by the average bytes per second - this will give you the duration of the file, in seconds.</p>\n\n<p>This works reasonably well for uncompressed and compressed files.</p>\n'}, {'answer_id': 396113, 'author': 'Lars', 'author_id': 42809, 'author_profile': 'https://Stackoverflow.com/users/42809', 'pm_score': 3, 'selected': False, 'text': '<p>I had difficulties with the example of the MediaPlayer-class above. It could take some time, before the player has opened the file. In the "real world" you have to register for the MediaOpened-event, after that has fired, the NaturalDuration is valid.\nIn a console-app you just have to wait a few seconds after the open.</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Windows.Media;\nusing System.Windows;\n\nnamespace ConsoleApplication2\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length == 0)\n return;\n Console.Write(args[0] + ": ");\n MediaPlayer player = new MediaPlayer();\n Uri path = new Uri(args[0]);\n player.Open(path);\n TimeSpan maxWaitTime = TimeSpan.FromSeconds(10);\n DateTime end = DateTime.Now + maxWaitTime;\n while (DateTime.Now < end)\n {\n System.Threading.Thread.Sleep(100);\n Duration duration = player.NaturalDuration;\n if (duration.HasTimeSpan)\n {\n Console.WriteLine(duration.TimeSpan.ToString());\n break;\n }\n }\n player.Close();\n }\n }\n}\n</code></pre>\n'}, {'answer_id': 2009777, 'author': 'Josh Stodola', 'author_id': 54420, 'author_profile': 'https://Stackoverflow.com/users/54420', 'pm_score': 3, 'selected': False, 'text': '<p>Not to take anything away from the answer already accepted, but I was able to get the duration of an audio file (several different formats, including AC3, which is what I needed at the time) using the <code>Microsoft.DirectX.AudioVideoPlayBack</code> namespace. This is part of <a href="http://msdn.microsoft.com/en-us/library/bb318658(VS.85).aspx" rel="noreferrer">DirectX 9.0 for Managed Code</a>. Adding a reference to that made my code as simple as this...</p>\n\n<pre><code>Public Shared Function GetDuration(ByVal Path As String) As Integer\n If File.Exists(Path) Then\n Return CInt(New Audio(Path, False).Duration)\n Else\n Throw New FileNotFoundException("Audio File Not Found: " & Path)\n End If\nEnd Function\n</code></pre>\n\n<p>And it\'s pretty fast, too! Here\'s a reference for the <a href="http://msdn.microsoft.com/en-us/library/bb324224(VS.85).aspx" rel="noreferrer">Audio</a> class.</p>\n'}, {'answer_id': 8181938, 'author': 'Monti Pal', 'author_id': 1053726, 'author_profile': 'https://Stackoverflow.com/users/1053726', 'pm_score': 5, 'selected': False, 'text': '<p>Download NAudio.dll\nfrom the link\n<a href="https://www.dll-files.com/naudio.dll.html" rel="nofollow noreferrer">https://www.dll-files.com/naudio.dll.html</a></p>\n<p>and then use this function</p>\n<pre><code>public static TimeSpan GetWavFileDuration(string fileName) \n{ \n WaveFileReader wf = new WaveFileReader(fileName);\n return wf.TotalTime; \n}\n</code></pre>\n<p>you will get the Duration</p>\n'}, {'answer_id': 12416165, 'author': 'Neoheurist', 'author_id': 1670042, 'author_profile': 'https://Stackoverflow.com/users/1670042', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Imports System.IO\nImports System.Text\n\nImports System.Math\nImports System.BitConverter\n\nPublic Class PulseCodeModulation\n \' Pulse Code Modulation WAV (RIFF) file layout\n\n \' Header chunk\n\n \' Type Byte Offset Description\n \' Dword 0 Always ASCII "RIFF"\n \' Dword 4 Number of bytes in the file after this value (= File Size - 8)\n \' Dword 8 Always ASCII "WAVE"\n\n \' Format Chunk\n\n \' Type Byte Offset Description\n \' Dword 12 Always ASCII "fmt "\n \' Dword 16 Number of bytes in this chunk after this value\n \' Word 20 Data format PCM = 1 (i.e. Linear quantization)\n \' Word 22 Channels Mono = 1, Stereo = 2\n \' Dword 24 Sample Rate per second e.g. 8000, 44100\n \' Dword 28 Byte Rate per second (= Sample Rate * Channels * (Bits Per Sample / 8))\n \' Word 32 Block Align (= Channels * (Bits Per Sample / 8))\n \' Word 34 Bits Per Sample e.g. 8, 16\n\n \' Data Chunk\n\n \' Type Byte Offset Description\n \' Dword 36 Always ASCII "data"\n \' Dword 40 The number of bytes of sound data (Samples * Channels * (Bits Per Sample / 8))\n \' Buffer 44 The sound data\n\n Dim HeaderData(43) As Byte\n\n Private AudioFileReference As String\n\n Public Sub New(ByVal AudioFileReference As String)\n Try\n Me.HeaderData = Read(AudioFileReference, 0, Me.HeaderData.Length)\n Catch Exception As Exception\n Throw\n End Try\n\n \'Validate file format\n\n Dim Encoder As New UTF8Encoding()\n\n If "RIFF" <> Encoder.GetString(BlockCopy(Me.HeaderData, 0, 4)) Or _\n "WAVE" <> Encoder.GetString(BlockCopy(Me.HeaderData, 8, 4)) Or _\n "fmt " <> Encoder.GetString(BlockCopy(Me.HeaderData, 12, 4)) Or _\n "data" <> Encoder.GetString(BlockCopy(Me.HeaderData, 36, 4)) Or _\n 16 <> ToUInt32(BlockCopy(Me.HeaderData, 16, 4), 0) Or _\n 1 <> ToUInt16(BlockCopy(Me.HeaderData, 20, 2), 0) _\n Then\n Throw New InvalidDataException("Invalid PCM WAV file")\n End If\n\n Me.AudioFileReference = AudioFileReference\n End Sub\n\n ReadOnly Property Channels() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 22, 2), 0) \'mono = 1, stereo = 2\n End Get\n End Property\n\n ReadOnly Property SampleRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 24, 4), 0) \'per second\n End Get\n End Property\n\n ReadOnly Property ByteRate() As Integer\n Get\n Return ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0) \'sample rate * channels * (bits per channel / 8)\n End Get\n End Property\n\n ReadOnly Property BlockAlign() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 32, 2), 0) \'channels * (bits per sample / 8)\n End Get\n End Property\n\n ReadOnly Property BitsPerSample() As Integer\n Get\n Return ToUInt16(BlockCopy(Me.HeaderData, 34, 2), 0)\n End Get\n End Property\n\n ReadOnly Property Duration() As Integer\n Get\n Dim Size As Double = ToUInt32(BlockCopy(Me.HeaderData, 40, 4), 0)\n Dim ByteRate As Double = ToUInt32(BlockCopy(Me.HeaderData, 28, 4), 0)\n Return Ceiling(Size / ByteRate)\n End Get\n End Property\n\n Public Sub Play()\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, AudioPlayMode.Background)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Public Sub Play(playMode As AudioPlayMode)\n Try\n My.Computer.Audio.Play(Me.AudioFileReference, playMode)\n Catch Exception As Exception\n Throw\n End Try\n End Sub\n\n Private Function Read(AudioFileReference As String, ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim inputFile As System.IO.FileStream\n\n Try\n inputFile = IO.File.Open(AudioFileReference, IO.FileMode.Open)\n Catch Exception As FileNotFoundException\n Throw New FileNotFoundException("PCM WAV file not found")\n Catch Exception As Exception\n Throw\n End Try\n\n Dim BytesRead As Long\n Dim Buffer(Bytes - 1) As Byte\n\n Try\n BytesRead = inputFile.Read(Buffer, Offset, Bytes)\n Catch Exception As Exception\n Throw\n Finally\n Try\n inputFile.Close()\n Catch Exception As Exception\n \'Eat the second exception so as to not mask the previous exception\n End Try\n End Try\n\n If BytesRead < Bytes Then\n Throw New InvalidDataException("PCM WAV file read failed")\n End If\n\n Return Buffer\n End Function\n\n Private Function BlockCopy(ByRef Source As Byte(), ByVal Offset As Long, ByVal Bytes As Long) As Byte()\n Dim Destination(Bytes - 1) As Byte\n\n Try\n Buffer.BlockCopy(Source, Offset, Destination, 0, Bytes)\n Catch Exception As Exception\n Throw\n End Try\n\n Return Destination\n End Function\nEnd Class\n</code></pre>\n'}, {'answer_id': 21500321, 'author': 'Aleks', 'author_id': 3258422, 'author_profile': 'https://Stackoverflow.com/users/3258422', 'pm_score': 2, 'selected': False, 'text': '<p>Try code below from <a href="http://alvas.net/alvas.audio,tips.aspx#tip25" rel="nofollow">How to determine the length of a .wav file in C#</a></p>\n\n<pre><code> string path = @"c:\\test.wav";\n WaveReader wr = new WaveReader(File.OpenRead(path));\n int durationInMS = wr.GetDurationInMS();\n wr.Close();\n</code></pre>\n'}, {'answer_id': 40933199, 'author': 'Manish Nayak', 'author_id': 4732757, 'author_profile': 'https://Stackoverflow.com/users/4732757', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, There is a free library that can be used to get time duration of Audio file. This library also provides many more functionalities.</p>\n\n<p><a href="http://taglib.org/" rel="noreferrer"><strong>TagLib</strong></a></p>\n\n<p>TagLib is distributed under the GNU Lesser General Public License (LGPL) and Mozilla Public License (MPL).</p>\n\n<p>I implemented below code that returns time duration in seconds.</p>\n\n<pre><code>using TagLib.Mpeg;\n\npublic static double GetSoundLength(string FilePath)\n{\n AudioFile ObjAF = new AudioFile(FilePath);\n return ObjAF.Properties.Duration.TotalSeconds;\n}\n</code></pre>\n'}, {'answer_id': 52929705, 'author': 'Martin Abilev', 'author_id': 7424574, 'author_profile': 'https://Stackoverflow.com/users/7424574', 'pm_score': 1, 'selected': False, 'text': '<p>time = FileLength / (Sample Rate * Channels * Bits per sample /8)</p>\n'}, {'answer_id': 54192641, 'author': 'item.wu', 'author_id': 10915057, 'author_profile': 'https://Stackoverflow.com/users/10915057', 'pm_score': 2, 'selected': False, 'text': '<p>i have tested blew code would fail,file formats are like "\\\\ip\\dir\\*.wav\'</p>\n\n<pre><code> public static class SoundInfo\n {\n [DllImport("winmm.dll")]\n private static extern uint mciSendString\n (\n string command,\n StringBuilder returnValue,\n int returnLength,\n IntPtr winHandle\n );\n\n public static int GetSoundLength(string fileName)\n {\n StringBuilder lengthBuf = new StringBuilder(32);\n\n mciSendString(string.Format("open \\"{0}\\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);\n mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n mciSendString("close wave", null, 0, IntPtr.Zero);\n\n int length = 0;\n int.TryParse(lengthBuf.ToString(), out length);\n\n return length;\n }\n}\n</code></pre>\n\n<p>while naudio works</p>\n\n<pre><code> public static int GetSoundLength(string fileName)\n {\n using (WaveFileReader wf = new WaveFileReader(fileName))\n {\n return (int)wf.TotalTime.TotalMilliseconds;\n }\n }`\n</code></pre>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/82319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1078/'] |
Subsets and Splits