qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
75,379 | <p>The problem is simple, but I'm struggling a bit already.</p>
<pre><code>Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();
</code></pre>
<p>That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. </p>
<p>Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?</p>
| [{'answer_id': 75424, 'author': 'Justin Rudd', 'author_id': 12968, 'author_profile': 'https://Stackoverflow.com/users/12968', 'pm_score': 0, 'selected': False, 'text': '<p>Use the <code>Context.addServlet</code> overload that takes a <code>ServletHolder</code>. <code>ServletHolder</code> is a class that accepts either a Class or a Servlet instance.</p>\n\n<pre><code>Servlet myServlet = new MyServlet();\nServletHolder holder = new ServletHolder(myServlet);\ncontext.addServlet(holder, "/");\n</code></pre>\n\n<p>This assumes Jetty 6. I think it will work for Jetty 7 as well.</p>\n'}, {'answer_id': 75760, 'author': 'delux247', 'author_id': 5569, 'author_profile': 'https://Stackoverflow.com/users/5569', 'pm_score': 3, 'selected': True, 'text': '<p>I\'m not sure why using Guice make\'s Justin\'s option not work for you. What exactly is getting injected in? I\'m not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating.</p>\n\n<pre><code>Context context = new Context(server, "/", Context.NO_SESSIONS);\nServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);\n// Do this to force Jetty to instantiate the servlet\nmainPageViewHolder.getServlet(); \ncontext.addServlet(mainPageViewHolder, "/");\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3105/'] |
75,385 | <p>The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.</p>
<p>Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.</p>
<p>Thanks,</p>
<pre><code>int foo(void)
{
unsigned int fooUnsigned = 0xffffffff;
int fooSigned = fooUnsigned; // no warning
if (fooSigned < fooUnsigned) // warning
{
return 0;
}
return fooSigned;
}
</code></pre>
<p>Update:</p>
<p>Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;</p>
<pre><code>#pragma warning (4 : 4365)
</code></pre>
<p>Which results in;</p>
<pre><code>warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch
</code></pre>
| [{'answer_id': 75596, 'author': 'quamrana', 'author_id': 4834, 'author_profile': 'https://Stackoverflow.com/users/4834', 'pm_score': 4, 'selected': True, 'text': '<p>You need to enable warning 4365 to catch the assignment.</p>\n\n<p>That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.</p>\n'}, {'answer_id': 75711, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 0, 'selected': False, 'text': "<p>@quamrana:</p>\n\n<p>There must be something beyond the /Wall option to enable warning 4365:</p>\n\n<pre><code>C:\\Temp>cl /Wall /c foo.c\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nfoo.c\nfoo.c(6) : warning C4018: '<' : signed/unsigned mismatch\n</code></pre>\n\n<p>I see that Andrew got it to work, but does anyone have an idea why it's not working here?</p>\n\n<p>The Visual Studio docs indicate that it should, but I can't even get the example program in the docs to give the C4365 warning (though it does give the related C4245 warning - but that occurs with just a /W4 option anyway).</p>\n"}, {'answer_id': 4883323, 'author': 'ottibus', 'author_id': 601104, 'author_profile': 'https://Stackoverflow.com/users/601104', 'pm_score': 2, 'selected': False, 'text': '<p>You can change the level of any specific warning by using /W[level][code]. So in this case /W34365 will make warning 4365 into a level 3 warning. If you do this a lot you might find it useful to put these options in a text file and use the @[file] option to simplify the command line.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1043/'] |
75,401 | <p>User <a href="https://stackoverflow.com/users/1065/kokos">kokos</a> answered the wonderful <em><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></em> question by mentioning the <code>using</code> keyword. Can you elaborate on that? What are the uses of <code>using</code>?</p>
| [{'answer_id': 75419, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 2, 'selected': False, 'text': '<p>When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.</p>\n'}, {'answer_id': 75426, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 7, 'selected': False, 'text': '<p>Things like this:</p>\n\n<pre><code>using (var conn = new SqlConnection("connection string"))\n{\n conn.Open();\n\n // Execute SQL statement here on the connection you created\n}\n</code></pre>\n\n<p>This <code>SqlConnection</code> will be closed without needing to explicitly call the <code>.Close()</code> function, and this will happen <em>even if an exception is thrown</em>, without the need for a <code>try</code>/<code>catch</code>/<code>finally</code>.</p>\n'}, {'answer_id': 75435, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="http://web.archive.org/web/20080809044303/http://www.ayende.com:80/Wiki/Rhino%20Mocks%20Record-playback%20Syntax.ashx" rel="nofollow noreferrer">Rhino Mocks Record-playback Syntax</a> makes an interesting use of <code>using</code>.</p>\n'}, {'answer_id': 75443, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 1, 'selected': False, 'text': "<p>When you use <em>using</em>, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.</p>\n<p>A bullet point:</p>\n<p>If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.</p>\n"}, {'answer_id': 75444, 'author': 'MagicKat', 'author_id': 8505, 'author_profile': 'https://Stackoverflow.com/users/8505', 'pm_score': 5, 'selected': False, 'text': '<p><em>using</em> can be used to call IDisposable. It can also be used to alias types.</p>\n<pre><code>using (SqlConnection cnn = new SqlConnection()) { /* Code */}\nusing f1 = System.Windows.Forms.Form;\n</code></pre>\n'}, {'answer_id': 75451, 'author': 'David Arno', 'author_id': 7122, 'author_profile': 'https://Stackoverflow.com/users/7122', 'pm_score': 2, 'selected': False, 'text': '<p>"using" can also be used to resolve namespace conflicts.</p>\n<p>See <em><a href="http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/" rel="nofollow noreferrer">http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/</a></em> for a short tutorial I wrote on the subject.</p>\n'}, {'answer_id': 75461, 'author': 'David Basarab', 'author_id': 2469, 'author_profile': 'https://Stackoverflow.com/users/2469', 'pm_score': 1, 'selected': False, 'text': '<p>The <em>using</em> keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.</p>\n<pre><code>using (Font font2 = new Font("Arial", 10.0f))\n{\n // Use font2\n}\n</code></pre>\n<p>See <a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx" rel="nofollow noreferrer">here</a> for the MSDN article on the C# <em>using</em> keyword.</p>\n'}, {'answer_id': 75480, 'author': 'Bob Wintemberg', 'author_id': 12999, 'author_profile': 'https://Stackoverflow.com/users/12999', 'pm_score': 2, 'selected': False, 'text': "<p><strong>using</strong> is used when you have a resource that you want disposed after it's been used.</p>\n<p>For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.</p>\n<p>The resource being used needs to implement IDisposable to work properly.</p>\n<p>Example:</p>\n<pre><code>using (File file = new File (parameters))\n{\n // Code to do stuff with the file\n}\n</code></pre>\n"}, {'answer_id': 75483, 'author': 'paulwhit', 'author_id': 7301, 'author_profile': 'https://Stackoverflow.com/users/7301', 'pm_score': 10, 'selected': True, 'text': '<p>The reason for the <code>using</code> statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn\'t require explicit code to ensure that this happens.</p>\n\n<p>As in <em><a href="https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C" rel="noreferrer">Understanding the \'using\' statement in C# (codeproject)</a></em> and <em><a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects" rel="noreferrer">Using objects that implement IDisposable (microsoft)</a></em>, the C# compiler converts</p>\n\n<pre><code>using (MyResource myRes = new MyResource())\n{\n myRes.DoSomething();\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>{ // Limits scope of myRes\n MyResource myRes= new MyResource();\n try\n {\n myRes.DoSomething();\n }\n finally\n {\n // Check for a null resource.\n if (myRes != null)\n // Call the object\'s Dispose method.\n ((IDisposable)myRes).Dispose();\n }\n}\n</code></pre>\n\n<p>C# 8 introduces a new syntax, named "<a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">using declarations</a>":</p>\n\n<blockquote>\n <p>A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.</p>\n</blockquote>\n\n<p>So the equivalent code of above would be:</p>\n\n<pre><code>using var myRes = new MyResource();\nmyRes.DoSomething();\n</code></pre>\n\n<p>And when control leaves the containing scope (usually a method, but it can also be a code block), <code>myRes</code> will be disposed.</p>\n'}, {'answer_id': 75497, 'author': 'Joel Martinez', 'author_id': 5416, 'author_profile': 'https://Stackoverflow.com/users/5416', 'pm_score': 2, 'selected': False, 'text': '<p>Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will <strong>always</strong> call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.</p>\n\n<p>This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.</p>\n'}, {'answer_id': 75516, 'author': 'Sam Schutte', 'author_id': 146, 'author_profile': 'https://Stackoverflow.com/users/146', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:</p>\n\n<pre><code> using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\n {\n using (BufferedStream bs = new BufferedStream(fs))\n {\n using (System.IO.StreamReader sr = new StreamReader(bs))\n {\n string output = sr.ReadToEnd();\n }\n }\n }\n</code></pre>\n'}, {'answer_id': 75640, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Not that it is ultra important, but <em>using</em> can also be used to change resources on the fly.</p>\n<p>Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.</p>\n"}, {'answer_id': 75867, 'author': 'BlackTigerX', 'author_id': 8411, 'author_profile': 'https://Stackoverflow.com/users/8411', 'pm_score': 7, 'selected': False, 'text': '<p>Since a lot of people still do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(""))\nusing (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {\n //code\n}\n</code></pre>\n\n<p>I guess a lot of people still don\'t know that you can do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {\n //code\n}\n</code></pre>\n'}, {'answer_id': 76192, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': '<p>In conclusion, when you use a local variable of a type that implements <code>IDisposable</code>, <em>always</em>, without exception, use <code>using</code><sup>1</sup>.</p>\n\n<p>If you use nonlocal <code>IDisposable</code> variables, then <em>always</em> implement the <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="noreferrer"><code>IDisposable</code> pattern</a>.</p>\n\n<p>Two simple rules, no exception<sup>1</sup>. Preventing resource leaks otherwise is a real pain in the *ss.</p>\n\n<hr>\n\n<p><sup>1)</sup>: The only exception is –\xa0when you\'re handling exceptions. It might then be less code to call <code>Dispose</code> explicitly in the <code>finally</code> block.</p>\n'}, {'answer_id': 76232, 'author': 'Brendan Kendrick', 'author_id': 13473, 'author_profile': 'https://Stackoverflow.com/users/13473', 'pm_score': 1, 'selected': False, 'text': '<p>Another example of a reasonable use in which the object is immediately disposed:</p>\n\n<pre><code>using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) \n{\n while (myReader.Read()) \n {\n MyObject theObject = new MyObject();\n theObject.PublicProperty = myReader.GetString(0);\n myCollection.Add(theObject);\n }\n}\n</code></pre>\n'}, {'answer_id': 76278, 'author': 'Lucas', 'author_id': 5966, 'author_profile': 'https://Stackoverflow.com/users/5966', 'pm_score': 3, 'selected': False, 'text': '<p>Another great use of <em>using</em> is when instantiating a modal dialog.</p>\n<pre class="lang-vbnet prettyprint-override"><code>Using frm as new Form1\n\n Form1.ShowDialog\n\n \' Do stuff here\n\nEnd Using\n</code></pre>\n'}, {'answer_id': 204957, 'author': 'Amanda Mitchell', 'author_id': 26628, 'author_profile': 'https://Stackoverflow.com/users/26628', 'pm_score': 4, 'selected': False, 'text': '<p><em>using</em>, in the sense of</p>\n<pre><code>using (var foo = new Bar())\n{\n Baz();\n}\n</code></pre>\n<p>Is actually shorthand for a try/finally block. It is equivalent to the code:</p>\n<pre><code>var foo = new Bar();\ntry\n{\n Baz();\n}\nfinally\n{\n foo.Dispose();\n}\n</code></pre>\n<p>You\'ll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we\'ve come up with a class that we call <em>Scope</em> that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you\'d do it like this:</p>\n<pre><code>using (new Scope(() => IsWorking = false))\n{\n IsWorking = true;\n MundaneYetDangerousWork();\n}\n</code></pre>\n<p>You can read more about our solution and how we derived it <a href="https://faithlife.codes/blog/2008/08/leverage_using_blocks_with_scope/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 204987, 'author': 'milot', 'author_id': 22637, 'author_profile': 'https://Stackoverflow.com/users/22637', 'pm_score': 1, 'selected': False, 'text': "<p>Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:</p>\n\n<pre><code>using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))\n{\n // do stuff\n} // here adapter_object is disposed automatically\n</code></pre>\n"}, {'answer_id': 13175552, 'author': 'Shiraj Momin', 'author_id': 1787655, 'author_profile': 'https://Stackoverflow.com/users/1787655', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public class ClassA:IDisposable\n{\n #region IDisposable Members\n public void Dispose()\n {\n GC.SuppressFinalize(this);\n }\n #endregion\n}\n</code></pre>\n<hr />\n<pre><code>public void fn_Data()\n{\n using (ClassA ObjectName = new ClassA())\n {\n // Use objectName\n }\n}\n</code></pre>\n'}, {'answer_id': 20271484, 'author': 'Riya Patil', 'author_id': 2191381, 'author_profile': 'https://Stackoverflow.com/users/2191381', 'pm_score': -1, 'selected': False, 'text': '<p>The <em>using</em> clause is used to define the scope for the particular variable.</p>\n<p>For example:</p>\n<pre><code>Using(SqlConnection conn = new SqlConnection(ConnectionString)\n{\n Conn.Open()\n\n // Execute SQL statements here.\n // You do not have to close the connection explicitly\n // here as "USING" will close the connection once the\n // object Conn goes out of the defined scope.\n}\n</code></pre>\n'}, {'answer_id': 22994945, 'author': 'VictorySaber', 'author_id': 2878135, 'author_profile': 'https://Stackoverflow.com/users/2878135', 'pm_score': 3, 'selected': False, 'text': '<p>You can make use of the alias namespace by way of the following example:</p>\n\n<pre><code>using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;\n</code></pre>\n\n<p>This is called a <em>using alias directive</em> as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to\ne.g.</p>\n\n<pre><code>LegacyEntities.Account\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account\n</code></pre>\n\n<p>or simply</p>\n\n<pre><code>Account // It is not obvious this is a legacy entity\n</code></pre>\n'}, {'answer_id': 29407147, 'author': 'snowell', 'author_id': 3720990, 'author_profile': 'https://Stackoverflow.com/users/3720990', 'pm_score': 1, 'selected': False, 'text': '<p>The <em>using</em> statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.</p>\n<p>The <em>using</em> statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the <em>using</em> block, the object is read-only and cannot be modified or reassigned.</p>\n<p>This comes from <a href="https://social.msdn.microsoft.com/Search/en-US?query=using&emptyWatermark=true&ac=4" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 29897282, 'author': 'Seb', 'author_id': 4693156, 'author_profile': 'https://Stackoverflow.com/users/4693156', 'pm_score': 1, 'selected': False, 'text': '<p>For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.</p>\n\n<p>A different name for error handling would\'ve been nice, and maybe a somehow more obvious one.</p>\n'}, {'answer_id': 29897576, 'author': 'Pluc', 'author_id': 1338607, 'author_profile': 'https://Stackoverflow.com/users/1338607', 'pm_score': 3, 'selected': False, 'text': "<p>Just adding a little something that I was surprised did not come up. The most interesting feature of <em>using</em> (in my opinion) is that no matter how you exit the <em>using</em> block, it will always dispose the object. This includes returns and exceptions.</p>\n<pre><code>using (var db = new DbContext())\n{\n if(db.State == State.Closed)\n throw new Exception("Database connection is closed.");\n return db.Something.ToList();\n}\n</code></pre>\n<p>It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.</p>\n"}, {'answer_id': 34465332, 'author': 'Aureliano Buendia', 'author_id': 738587, 'author_profile': 'https://Stackoverflow.com/users/738587', 'pm_score': 4, 'selected': False, 'text': '<p>Microsoft documentation states that <strong>using</strong> has a double function (<a href="https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx</a>), both as a <em>directive</em> and in <em>statements</em>. As a <em>statement</em>, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an <strong>IDisposable</strong> object. As a <em>directive</em>, it is routinely used to import namespaces and types. Also as a directive, you can create <em>aliases</em> for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (<a href="https://rads.stackoverflow.com/amzn/click/com/B008E6I1K8" rel="noreferrer" rel="nofollow noreferrer">http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8</a>), by Joseph and Ben Albahari. One example:</p>\n\n<pre><code>namespace HelloWorld\n{\n using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;\n public class Startup\n {\n public static AppFunc OrderEvents() \n {\n AppFunc appFunc = (IDictionary<DateTime, string> events) =>\n {\n if ((events != null) && (events.Count > 0))\n {\n List<string> result = events.OrderBy(ev => ev.Key)\n .Select(ev => ev.Value)\n .ToList();\n return result;\n }\n throw new ArgumentException("Event dictionary is null or empty.");\n };\n return appFunc;\n }\n }\n}\n</code></pre>\n\n<p>This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one\'s code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (<a href="http://www.dotnetperls.com/using-alias" rel="noreferrer">http://www.dotnetperls.com/using-alias</a>).</p>\n'}, {'answer_id': 41463137, 'author': 'Siamand', 'author_id': 2276651, 'author_profile': 'https://Stackoverflow.com/users/2276651', 'pm_score': 1, 'selected': False, 'text': '<p>It also can be used for creating scopes for Example:</p>\n\n<pre><code>class LoggerScope:IDisposable {\n static ThreadLocal<LoggerScope> threadScope = \n new ThreadLocal<LoggerScope>();\n private LoggerScope previous;\n\n public static LoggerScope Current=> threadScope.Value;\n\n public bool WithTime{get;}\n\n public LoggerScope(bool withTime){\n previous = threadScope.Value;\n threadScope.Value = this;\n WithTime=withTime;\n }\n\n public void Dispose(){\n threadScope.Value = previous;\n }\n}\n\n\nclass Program {\n public static void Main(params string[] args){\n new Program().Run();\n }\n\n public void Run(){\n log("something happend!");\n using(new LoggerScope(false)){\n log("the quick brown fox jumps over the lazy dog!");\n using(new LoggerScope(true)){\n log("nested scope!");\n }\n }\n }\n\n void log(string message){\n if(LoggerScope.Current!=null){\n Console.WriteLine(message);\n if(LoggerScope.Current.WithTime){\n Console.WriteLine(DateTime.Now);\n }\n }\n }\n\n}\n</code></pre>\n'}, {'answer_id': 49166602, 'author': 'deepak samantaray', 'author_id': 4661703, 'author_profile': 'https://Stackoverflow.com/users/4661703', 'pm_score': 1, 'selected': False, 'text': "<p>The <em>using</em> statement tells .NET to release the object specified in the <em>using</em> block once it is no longer needed.</p>\n<p>So you should use the 'using' block for classes that require cleaning up after them, like <em>System.IO</em> types.</p>\n"}, {'answer_id': 50293207, 'author': 'Vazgen Torosyan', 'author_id': 3541666, 'author_profile': 'https://Stackoverflow.com/users/3541666', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n<p>using as a statement automatically calls the dispose on the specified\nobject. The object must implement the IDisposable interface. It is\npossible to use several objects in one statement as long as they are\nof the same type.</p>\n</blockquote>\n<p>The <a href="https://en.wikipedia.org/wiki/Common_Language_Runtime" rel="nofollow noreferrer">CLR</a> converts your code into <a href="https://en.wikipedia.org/wiki/Common_Intermediate_Language" rel="nofollow noreferrer">CIL</a>. And the <em>using</em> statement gets translated into a try and finally block. This is how the <em>using</em> statement is represented in CIL. A <em>using</em> statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a <em>try</em> statement with a <em>finally</em> clause. The object then gets disposed in the <em>finally</em> clause.</p>\n'}, {'answer_id': 51590168, 'author': 'Chamila Maddumage', 'author_id': 8194089, 'author_profile': 'https://Stackoverflow.com/users/8194089', 'pm_score': 2, 'selected': False, 'text': '<p>There are two usages of the <code>using</code> keyword in C# as follows.</p>\n<ol>\n<li><p>As a directive</p>\n<p>Generally we use the <code>using</code> keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.</p>\n<p>Example:</p>\n<pre><code>using System.IO;\n</code></pre>\n</li>\n<li><p>As a statement</p>\n<p>This is another way to use the <code>using</code> keyword in C#. It plays a vital role in improving performance in garbage collection.</p>\n<p>The <code>using</code> statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.</p>\n<p>Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.</p>\n<p>You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.</p>\n<p>Example:</p>\n<pre><code>string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";\n\nusing (SqlConnection conn = new SqlConnection(connString))\n{\n SqlCommand cmd = conn.CreateCommand();\n cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";\n conn.Open();\n using (SqlDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n Console.WriteLine("{0}\\t{1}", dr.GetString(0), dr.GetString(1));\n }\n}\n</code></pre>\n</li>\n</ol>\n<p>In the preceding code I am not closing any connection; it will close automatically. The <code>using</code> statement will call conn.Close() automatically due to the <code>using</code> statement (<code>using (SqlConnection conn = new SqlConnection(connString)</code>) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.</p>\n<p>For more information, see <em><a href="https://www.c-sharpcorner.com/UploadFile/manas1/usage-and-importance-of-using-in-C-Sharp472/" rel="nofollow noreferrer">Usage and Importance of Using in C#</a></em>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13332/'] |
75,411 | <p>I've set an external tool (sablecc) in eclipse (3.4) that generates a bunch of classes in the current project. I need to run this tool and regenerate these classes fairly frequently. This means that every time I want to run sablecc, I have to manually delete the packages/classes that sablecc creates in order to ensure that I don't have conflicts between the old and new generated classes. Is there some easy way to automate this from within eclipse or otherwise? </p>
| [{'answer_id': 75469, 'author': 'JesperE', 'author_id': 13051, 'author_profile': 'https://Stackoverflow.com/users/13051', 'pm_score': 0, 'selected': False, 'text': '<p>You can tell Eclipse to refresh the workspace (or parts of it) after an external tool has been run. This should force Eclipse to detect any new/deleted classes.</p>\n'}, {'answer_id': 76240, 'author': 'flicken', 'author_id': 12880, 'author_profile': 'https://Stackoverflow.com/users/12880', 'pm_score': 0, 'selected': False, 'text': '<p>JesperE is referring to the option <em>Refresh->Refresh resources on completion</em> in your external tools configuration for running sablecc.</p>\n'}, {'answer_id': 76245, 'author': 'Lukáš Rampa', 'author_id': 10560, 'author_profile': 'https://Stackoverflow.com/users/10560', 'pm_score': 1, 'selected': False, 'text': '<p>Not sure if I understand your point right, I suppose you need to delete old classes before running sablecc because some of them would not be eventually created in new run.</p>\n\n<p>It is probably best to write short <a href="http://ant.apache.org/" rel="nofollow noreferrer">Ant</a> build.xml with the target, which first removes the classes (Ant delete task) and then runs sablecc (Ant exec task). It is also possible to preset eclipse so that it refreshes workspace after Ant finishes.</p>\n\n<p>Put the build.xml anywhere to project, right click, Run As/Ant Build.</p>\n\n<p>Just for the sake of the clean style, you could then call sablecc with its Ant task (implemented by org.sablecc.ant.taskdef), instead of running it externally in new process.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85/'] |
75,432 | <p>I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.</p>
| [{'answer_id': 75452, 'author': 'AlanKley', 'author_id': 8761, 'author_profile': 'https://Stackoverflow.com/users/8761', 'pm_score': 5, 'selected': True, 'text': '<p>Call DeleteUrlCacheEntry with the same URL just prior to calling URLDownloadToFile.\nYou will need to link against Wininet.lib</p>\n'}, {'answer_id': 75518, 'author': 'Shawn Miller', 'author_id': 247, 'author_profile': 'https://Stackoverflow.com/users/247', 'pm_score': 2, 'selected': False, 'text': '<p>Could you add a harmless query parameter to the end of your URL?</p>\n\n<p><a href="https://stackoverflow.com/?CacheBuster=1020am">https://stackoverflow.com/?CacheBuster=1020am</a></p>\n'}, {'answer_id': 1375267, 'author': 'Remy Lebeau', 'author_id': 65863, 'author_profile': 'https://Stackoverflow.com/users/65863', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, it is pulling a cached version of the file by default. To avoid the cache file completely, pass an IBindStatusCallback object in the lpfnCB\nparameter of URLDownloadToFile(). In your implemented IBindStatusCallback::GetBindInfo() method, include the BINDF_GETNEWESTVERSION flag, and optionally also the BINDF_NOWRITECACHE flag, in the value you return via the grfBINDF parameter. If you want the cache file, if present, to be updated instead of skippe, specify the BINDF_RESYNCHRONIZE flag instead.</p>\n'}, {'answer_id': 20701711, 'author': 'user3122475', 'author_id': 3122475, 'author_profile': 'https://Stackoverflow.com/users/3122475', 'pm_score': 2, 'selected': False, 'text': '<p>clean cache</p>\n\n<pre><code>// Limpa cache do Internet Explorer\nprocedure DeletaIECache;\nvar\n lpEntryInfo: PInternetCacheEntryInfo;\n hCacheDir: LongWord;\n dwEntrySize: LongWord;\nbegin\n dwEntrySize := 0;\n FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize) ;\n GetMem(lpEntryInfo, dwEntrySize) ;\n if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize;\n hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize) ;\n if hCacheDir <> 0 then\n begin\n repeat\n DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName) ;\n FreeMem(lpEntryInfo, dwEntrySize) ;\n dwEntrySize := 0;\n FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^), dwEntrySize) ;\n GetMem(lpEntryInfo, dwEntrySize) ;\n if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize;\n until not FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize) ;\n end;\n FreeMem(lpEntryInfo, dwEntrySize) ;\n FindCloseUrlCache(hCacheDir) ;\nend;\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8761/'] |
75,440 | <p>What method do I call to get the name of a class?</p>
| [{'answer_id': 75456, 'author': 'clahey', 'author_id': 8453, 'author_profile': 'https://Stackoverflow.com/users/8453', 'pm_score': 5, 'selected': False, 'text': "<p>It's not a method, it's a field. The field is called <code>__name__</code>. <code>class.__name__</code> will give the name of the class as a string. <code>object.__class__.__name__</code> will give the name of the class of an object.</p>\n"}, {'answer_id': 75467, 'author': 'Mr Shark', 'author_id': 6093, 'author_profile': 'https://Stackoverflow.com/users/6093', 'pm_score': 7, 'selected': True, 'text': "<pre><code>In [1]: class Test:\n ...: pass\n ...: \n\nIn [2]: Test.__name__\nOut[2]: 'Test'\n</code></pre>\n"}, {'answer_id': 77222, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>In [8]: <code>str(\'2\'.__class__)</code><br />\nOut[8]: <code>"<type \'str\'>"</code><br /></p>\n\n<p>In [9]: <code>str(len.__class__)</code><br />\nOut[9]: <code>"<type \'builtin_function_or_method\'>"</code><br /></p>\n\n<p>In [10]: <code>str(4.6.__class__)</code><br />\nOut[10]: <code>"<type \'float\'>"</code><br /></p>\n\n<p>Or, as was pointed out before,<br /></p>\n\n<p>In [11]: <code>4.6.__class__.__name__</code><br />\nOut[11]: <code>\'float\'</code></p>\n'}, {'answer_id': 83155, 'author': 'Jon Cage', 'author_id': 15369, 'author_profile': 'https://Stackoverflow.com/users/15369', 'pm_score': 4, 'selected': False, 'text': '<p>I agree with Mr.Shark, but if you have an instance of a class, you\'ll need to use its <code>__class__</code> member:</p>\n\n<pre><code>>>> class test():\n... pass\n...\n>>> a_test = test()\n>>>\n>>> a_test.__name__\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nAttributeError: test instance has no attribute \'__name__\'\n>>>\n>>> a_test.__class__\n<class __main__.test at 0x009EEDE0>\n</code></pre>\n'}, {'answer_id': 53653620, 'author': 'Azat Ibrakov', 'author_id': 5997596, 'author_profile': 'https://Stackoverflow.com/users/5997596', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="https://docs.python.org/whatsnew/3.3.html#pep-3155-qualified-name-for-classes-and-functions" rel="nofollow noreferrer"><strong>Python 3.3</strong></a> and onwards we can use <a href="https://docs.python.org/library/stdtypes.html#definition.__qualname__" rel="nofollow noreferrer"><code>__qualname__</code> field</a> for both classes & functions.</p>\n<p>It differs from <a href="https://docs.python.org/library/stdtypes.html#definition.__name__" rel="nofollow noreferrer"><code>__name__</code> field</a> for nested objects like class defined in other class</p>\n<pre><code>>>> class A:\n class B:\n pass\n>>> A.B.__name__\n\'B\'\n>>> A.B.__qualname__\n\'A.B\'\n</code></pre>\n<p>which may be quite useful.</p>\n<h1>Further reading</h1>\n<ul>\n<li><a href="https://www.python.org/dev/peps/pep-3155/" rel="nofollow noreferrer">PEP 3155 -- Qualified name for classes and functions</a>.</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8453/'] |
75,441 | <p>As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?</p>
| [{'answer_id': 75481, 'author': 'Phillip Wells', 'author_id': 3012, 'author_profile': 'https://Stackoverflow.com/users/3012', 'pm_score': 4, 'selected': True, 'text': '<p>Use the <<a href="http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html" rel="noreferrer">attrib</a>> task. For example, to make the file "test.txt" read/write, you would use</p>\n\n<pre><code><attrib file="test.txt" readonly="false"/>\n</code></pre>\n'}, {'answer_id': 76863, 'author': 'LordHits', 'author_id': 8088, 'author_profile': 'https://Stackoverflow.com/users/8088', 'pm_score': 3, 'selected': False, 'text': '<p>Also, for a list of files, the command is:</p>\n\n<pre><code><attrib readonly="false">\n <fileset basedir="mydirectory">\n <include name="**"/>\n </fileset>\n</attrib>\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8088/'] |
75,446 | <p>I have just started reading DDD. I am unable to completely grasp the concept of Entity vs Value objects.. Can someone please explain the problems (maintainability, performance.. etc) a system could face when a Value object is designed as a Entity object? Example would be great...</p>
| [{'answer_id': 75769, 'author': 'JasonTrue', 'author_id': 13433, 'author_profile': 'https://Stackoverflow.com/users/13433', 'pm_score': 7, 'selected': False, 'text': '<p>Reduced to the essential distinction, identity matters for entities, but does not matter for value objects. For example, someone\'s Name is a value object. A Customer entity might be composed of a customer Name (value object), List<Order> OrderHistory (List of entities), and perhaps a default Address (typically a value object). The Customer Entity would have an ID, and each order would have an ID, but a Name should not; generally, within the object model anyway, the identity of an Address probably does not matter.</p>\n\n<p>Value objects can typically be represented as immutable objects; changing one property of a value object essentially destroys the old object and creates a new one, because you\'re not as concerned with identity as with content. Properly, the Equals instance method on Name would return "true" as long as the object\'s properties are identical to the properties of another instance.</p>\n\n<p>However, changing some attribute of an entity like Customer doesn\'t destroy the customer; a Customer entity is typically mutable. The identity remains the same (at least once the object has been persisted).</p>\n\n<p>You probably create value objects without realizing it; anytime you are representing some aspect of an Entity by creating a fine-grained class, you\'ve got a value object. For example, a class IPAddress, which has some constraints on valid values but is composed of simpler datatypes, would be a value object. An EmailAddress could be a string, or it could be a value object with its own set of behaviors.</p>\n\n<p>It\'s quite possible that even items that have an identity in your database don\'t have an identity in your object model. But the simplest case is a composite of some attributes that make sense together. You probably don\'t want to have Customer.FirstName, Customer.LastName, Customer.MiddleInitial and Customer.Title when you can compose those together as Customer.Name; they\'ll probably be multiple fields in your database by the time you think about persistence, but your object model doesn\'t care.</p>\n'}, {'answer_id': 91373, 'author': 'Christophe Herreman', 'author_id': 17255, 'author_profile': 'https://Stackoverflow.com/users/17255', 'pm_score': 3, 'selected': False, 'text': "<p>I don't know if the following is correct, but I would say that in the case of an Address object, we want to use it as a Value Object instead of an Entity because changes to the entity would be reflected on all linked objects (a Person for instance).</p>\n\n<p>Take this case: You are living in your house with some other people. If we would use Entity for Address, I would argue that there would be one unique Address that all Person objects link to. If one person moves out, you want to update his address. If you would update the properties of the Address Entity, all people would have a different address. In the case of a Value Object, we would not be able to edit the Address (since it is immutable) and we would be forced to provide a new Address for that Person.</p>\n\n<p>Does this sound right? I must say that I was/am also still confused about this difference, after reading the DDD book.</p>\n\n<p>Going one step further, how would this be modelled in the database? Would you have all properties of the Address object as columns in the Person table or would you create a separate Address table that would also have a unique identifier? In the latter case, the people living in the same house would each have a different instance of an Address object, but those objects would be the same except for their ID property.</p>\n"}, {'answer_id': 221642, 'author': 'Richard Dorman', 'author_id': 1199234, 'author_profile': 'https://Stackoverflow.com/users/1199234', 'pm_score': 6, 'selected': False, 'text': '<p>Any object that is collectively defined by all of it attributes is a value object. If any of the attributes change you have a new instance of a value object. This is why value objects are defined as immutable.</p>\n\n<p>If the object is not fully defined by all of its attributes then there are a subset of attributes that make up the identity of the object. The remaining attributes can change without redefining the object. This kind of object cannot be defined at immutable.</p>\n\n<p>A simpler way of making the distinction is to think of value objects as static data that will never change and entities as data that evolves in your application.</p>\n'}, {'answer_id': 772649, 'author': 'n8wrl', 'author_id': 37710, 'author_profile': 'https://Stackoverflow.com/users/37710', 'pm_score': 2, 'selected': False, 'text': "<p>I asked about this in another thread and I think I'm still confused. I may be confusing performance considerations with data modelling. In our Cataloging application, a Customer doesn't change until it needs to. That sounds dumb - but the 'reads' of customer data far outnumber the 'writes' and since many many web requests are all hitting on the 'active set' of objects, I don't want to keep loading Customers time and again. So I was headed down an immutable road for the Customer object - load it, cache it, and serve up the same one to the 99% of (multi-threaded) requests that want to see the Customer. Then, when a customer changes something, get an 'editor' to make a new Customer and invalidate the old one.</p>\n\n<p>My concern is if many threads see the same customer object and it is mutable, then when one thread starts to change it mayhem ensues in the others.</p>\n\n<p>My problems now are, 1) is this reasonable, and 2) how best to do this without duplicating a lot of code about the properties.</p>\n"}, {'answer_id': 2469926, 'author': 'Dharmesh', 'author_id': 296517, 'author_profile': 'https://Stackoverflow.com/users/296517', 'pm_score': 3, 'selected': False, 'text': '<p>address can be entity or value object that depends on the busiess process. address object can be entity in courier service application but address can be value object in some other application. in courier application identity matters for address object </p>\n'}, {'answer_id': 47422311, 'author': 'Ramin Farajpour', 'author_id': 3269793, 'author_profile': 'https://Stackoverflow.com/users/3269793', 'pm_score': 2, 'selected': False, 'text': '<p>3 distinction between <code>Entities</code> and <code>Value Objects</code> </p>\n\n<ul>\n<li><p>Identifier vs structural equality:\nEntities have identifier,entities are the same if they have the same \nidentifier.\nValue Objects on beyond the hand have structural equality, we consider two \nvalue objects equal when all the fields are the same. Value objects cannot \nhave identifier.</p></li>\n<li><p>Mutability vs immutability: \nValue Objects are immutable data structures whereas entities change during \ntheir life time.</p></li>\n<li><p>Lifespan: Value Objects Should belong to Entities</p></li>\n</ul>\n'}, {'answer_id': 48483132, 'author': 'Premraj', 'author_id': 1697099, 'author_profile': 'https://Stackoverflow.com/users/1697099', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Value Types :</strong> </p>\n\n<ul>\n<li>Value types do not exist on his own, depends on Entity types.</li>\n<li>Value Type object belongs to an Entity Type Object.</li>\n<li>The lifespan of a value type instance is bounded by the lifespan of the owning entity instance.</li>\n<li>Three Value types: Basic(primitive datatypes), Composite(Address) and Collection(Map, List, Arrays)</li>\n</ul>\n\n<p><strong>Entities:</strong> </p>\n\n<ul>\n<li>Entity types can exist on his own (Identity)</li>\n<li>An entity has its own life-cycle. It may exist independently of any other entity.</li>\n<li>For example: Person, Organisation, College, Mobile, Home etc.. every object has its own identity</li>\n</ul>\n'}, {'answer_id': 61063417, 'author': 'Alireza Rahmani khalili', 'author_id': 2043248, 'author_profile': 'https://Stackoverflow.com/users/2043248', 'pm_score': 2, 'selected': False, 'text': '<p>In a very simple sentence I can say, we have three types of equality:</p>\n\n<ul>\n<li><strong>Identifier equality</strong>: a class has id filed and two objects are compared with their id field value. </li>\n<li><strong>Reference equality</strong>: if a reference to two objects has a same address in memory.</li>\n<li><strong>Structural equality</strong>: two objects are equal if all members of them are matched.</li>\n</ul>\n\n<p>Identifier equality <strong>refers</strong> only to Entity and structural equality refers to Value Object only. In fact Value Objects do not have id and we can use them interchangeably. also value objects must be immutable and entities can be mutable and value objects will not have nay table in database.</p>\n'}, {'answer_id': 68228468, 'author': 'TheGeeky', 'author_id': 4003872, 'author_profile': 'https://Stackoverflow.com/users/4003872', 'pm_score': 1, 'selected': False, 'text': '<p>Consider the following examples from <em><strong>Wikipedia</strong></em>, in order to better understand the difference between Value Objects and Entities:</p>\n<p><strong>Value Object:</strong> When people exchange dollar bills, they generally do not\ndistinguish between each unique bill; they only are concerned about the face\nvalue of the dollar bill. In this context, dollar bills are Value Objects. However,\nthe Federal Reserve may be concerned about each unique bill; in this context each\nbill would be an entity.</p>\n<p><strong>Entity:</strong> Most airlines distinguish each seat uniquely on every flight. Each seat is\nan entity in this context. However, Southwest Airlines, EasyJet and Ryanair do\nnot distinguish between every seat; all seats are the same. In this context, a seat is\nactually a Value Object.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
75,463 | <p>Does anyone know of some good resources related to setting up heirarchical user account systems? I'm currently setting one up and am struggling with some of the more complex logic (especially with determining permissions). I was hoping I might be able to find some resources to help me along.</p>
<p><strong>Some Background:</strong>
I'm building a user account system for a web CMS that allows for a nested group hierarchy. Each group can be allowed/denied access to read, write, add, and delete (either explicitly for that group, or implicitly by one of its parents). As if that weren't complicated enough, the system also allows for users to be members of multiple groups. -- This is where I'm stuck. I've got everything set up, but I'm struggling with the actual logic for determining pemissions for a given user.</p>
| [{'answer_id': 75490, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 1, 'selected': False, 'text': '<p>Look at the permissions in the <a href="http://en.wikipedia.org/wiki/Andrew_File_System" rel="nofollow noreferrer">Andrew File System</a>. It allows users to create and administer groups of their own, while selectively assigning admin rights and ACLs. You might find that many of the pesky details are already worked out for you in their model.</p>\n\n<p><strong>Edit:</strong> here\'s a better link to AFS documentation:</p>\n\n<p><a href="http://www.cs.cmu.edu/~help/afs/index.html" rel="nofollow noreferrer">http://www.cs.cmu.edu/~help/afs/index.html</a></p>\n\n<p>Here\'s the section on groups:</p>\n\n<p><a href="http://www.cs.cmu.edu/~help/afs/afs_groups.html" rel="nofollow noreferrer">http://www.cs.cmu.edu/~help/afs/afs_groups.html</a></p>\n'}, {'answer_id': 75510, 'author': 'davethegr8', 'author_id': 12930, 'author_profile': 'https://Stackoverflow.com/users/12930', 'pm_score': 3, 'selected': True, 'text': '<p>The manual for CakePHP has an excellent description of how Access Control Lists work.</p>\n\n<p><a href="http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html" rel="nofollow noreferrer">http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html</a></p>\n'}, {'answer_id': 75571, 'author': 'Donn Felker', 'author_id': 5210, 'author_profile': 'https://Stackoverflow.com/users/5210', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve done exactly this before and its no trivial implementation. You\'re going to want to look at the SecurityPermission class. </p>\n\n<p>[<a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermission.aspx][1]" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermission.aspx][1]</a></p>\n\n<p>I have done this before by utilizing XML (which I\'m not sure I\'d do again) and storing that XML as permission list inside of SQL server in an XML column through a CLR stored proc. The XML would have an element called a "permission" and then the permission would actually be a ENUM inside of the code. Each permission was a new implementation of the SecurityPermission class (linked above) Users were tied to groups which were defined in SQL server and then as the user was added/removed to groups, the XML doc would get updated to reflect which groups they were apart of. </p>\n\n<p>As soon as the user logged in, the users credentials would be loaded into the application store (session) and then would be accessed accordingly. When authorization needed to take place the XMl in the application store would be pulled down loaded into the SecurityPermission via the "FromXML" method. At that point I would use the following methods to determine if the user had permission: </p>\n\n<ul>\n<li>Demand</li>\n<li>Intersect</li>\n<li>Union</li>\n<li>IsUnrestricted</li>\n<li>IsSubSetOf</li>\n</ul>\n\n<p>etc., etc, etc. </p>\n\n<p>At that point after performing the Demand I was able to determine if the caller had access according to how I implemented my security routines in the SecurityPermissions. </p>\n\n<p>Again, this is leaving out a TON of detail, but this should get you going down the right path. </p>\n\n<p>Take a look at this name space as well: [2]: <a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.security.permissions.aspx</a> "System.Security.Permissions"</p>\n'}, {'answer_id': 458047, 'author': 'Ben Aston', 'author_id': 38522, 'author_profile': 'https://Stackoverflow.com/users/38522', 'pm_score': 2, 'selected': False, 'text': "<p>Represent the permissions set for a given group as a bit mask. OR-ing the bit masks together will give you the resultant permission set.</p>\n\n<p>Update for @Alex:</p>\n\n<p>I wrote this answer 3 years ago, but I believe I was alluding to the following...</p>\n\n<p>From the question</p>\n\n<blockquote>\n <p>a nested group hierarchy. Each group can be allowed/denied access to\n read, write, add, and delete (either explicitly for that group, or\n implicitly by one of its parents). As if that weren't complicated\n enough, the system also allows for users to be members of multiple\n groups. -- This is where I'm stuck. I've got everything set up, but\n I'm struggling with the actual logic for determining pemissions for a\n given user.</p>\n</blockquote>\n\n<p>Assign a bitmask matching the total permission set of a group (or role) in the system:</p>\n\n<p>e.g. <code>00</code> (using two bits keeps it simple here!)</p>\n\n<p>The first bit confers <code>Permission A</code> and the second <code>Permission B</code>.</p>\n\n<p>Now say Group A confers the following permission set: <code>01</code>.</p>\n\n<p>... and say Group B confers the following permission set: <code>10</code>.</p>\n\n<p>To get the resultant permission set for a user in an arbitrary set of groups you could perform a logical <code>OR</code> on the permission set bit masks:</p>\n\n<pre><code>Permission set for Group A 01\nPermission set for Group B 10 OR \n ----\nResultant permission set 11 (i.e. both permission A and B are conferred)\n</code></pre>\n\n<p>I do not know the details of the questioner's system, but the system outlined here could be augmented to achieve different group-composition behaviors using different logical operators.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5291/'] |
75,479 | <p>I have an Eclipse RCP app running on Java 6. When I try to run the product configuration from within Eclipse, it silently terminates almost immediately. No error is reported in the console. I've tried setting breakpoints in the IApplication and in the Activator, and neither are reached.</p>
<p>I know I don't have much specific information here, but can anyone give me any pointers on where I might start looking to diagnose the problem? </p>
| [{'answer_id': 75503, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 2, 'selected': True, 'text': "<p>Have you checked the logs in runtime/.metadata folder?,<br><br> Also make sure to validate all plugins in the runtime. Having them as a dependency doesn't necessarily mean they are added to the runtime. This is probably the biggest gotcha when launching an rcp app.</p>\n"}, {'answer_id': 75699, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 2, 'selected': False, 'text': '<p>I wasn\'t able to locate the runtime/.metadata folder, but <a href="http://www.eclipsezone.com/eclipse/forums/t99010.rhtml" rel="nofollow noreferrer">this very helpful post</a> directed me to add -consoleLog and -noExit to my runtime arguments, which dumped the errors to the console. Configuration problems.</p>\n'}, {'answer_id': 11744829, 'author': 'Phaedrus', 'author_id': 544303, 'author_profile': 'https://Stackoverflow.com/users/544303', 'pm_score': 0, 'selected': False, 'text': '<p>I experienced this problem after migrating my RCP app from 3.7 to 4.2. The solution for me was to delete to runtime-product.product directory and re-run. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4223/'] |
75,482 | <p>I am serving all content through apache with <code>Content-Encoding: zip</code> but that compresses on the fly. A good amount of my content is static files on the disk. I want to gzip the files beforehand rather than compressing them every time they are requested.</p>
<p>This is something that, I believe, <code>mod_gzip</code> did in Apache 1.x automatically, but just having the file with .gz next to it. That's no longer the case with <code>mod_deflate</code>.</p>
| [{'answer_id': 75682, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 5, 'selected': True, 'text': '<p>This functionality was misplaced in mod_gzip anyway. In Apache 2.x, <a href="http://httpd.apache.org/docs/2.2/content-negotiation.html" rel="noreferrer">you do that with content negotiation</a>. Specifically, you need to enable <code>MultiViews</code> with the <a href="http://httpd.apache.org/docs/2.2/mod/core.html#options" rel="noreferrer"><code>Options</code> directive</a> and you need to specify your encoding types with the <a href="http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addencoding" rel="noreferrer"><code>AddEncoding</code> directive</a>.</p>\n'}, {'answer_id': 75697, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 0, 'selected': False, 'text': '<p>You can use <a href="http://httpd.apache.org/docs/2.2/mod/mod_cache.html" rel="nofollow noreferrer"><code>mod_cache</code></a> to proxy local content in memory or on disk. I don\'t know if this will work as expected with <code>mod_deflate</code>.</p>\n'}, {'answer_id': 75727, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 1, 'selected': False, 'text': '<p>mod_gzip compressed content on the fly as well. You can pre-compress the files by actually logging into your server, and doing it from shell.</p>\n\n<pre><code>cd /var/www/.../data/\nfor file in *; do\n gzip -c $file > $file.gz;\ndone;\n</code></pre>\n'}, {'answer_id': 97155, 'author': 'Otto', 'author_id': 9594, 'author_profile': 'https://Stackoverflow.com/users/9594', 'pm_score': 3, 'selected': False, 'text': '<p>To answer my own question with the really simple line I was missing in my confiuration:</p>\n\n<pre><code>Options FollowSymLinks MultiViews\n</code></pre>\n\n<p>I was missing the MultiViews option. It\'s there in the Ubuntu default web server configuration, so don\'t be like me and drop it off.</p>\n\n<p>Also I wrote a quick Rake task to compress all the files.</p>\n\n<pre><code>namespace :static do\n desc "Gzip compress the static content so Apache doesn\'t need to do it on-the-fly."\n task :compress do\n puts "Gzipping js, html and css files."\n Dir.glob("#{RAILS_ROOT}/public/**/*.{js,html,css}") do |file|\n system "gzip -c -9 #{file} > #{file}.gz"\n end\n end\nend\n</code></pre>\n'}, {'answer_id': 609051, 'author': 'brianegge', 'author_id': 14139, 'author_profile': 'https://Stackoverflow.com/users/14139', 'pm_score': 2, 'selected': False, 'text': '<p>I have an Apache 2 built from source, and I found I had to modify the following in my <strong>httpd.conf</strong> file:</p>\n\n<p>Add MultiViews to Options:</p>\n\n<blockquote>\n<pre><code>Options Indexes FollowSymLinks MultiViews\n</code></pre>\n</blockquote>\n\n<p>Uncomment AddEncoding:</p>\n\n<blockquote>\n<pre><code>AddEncoding x-compress .Z\nAddEncoding x-gzip .gz .tgz\n</code></pre>\n</blockquote>\n\n<p>Comment AddType:</p>\n\n<blockquote>\n<pre><code>#AddType application/x-compress .Z\n#AddType application/x-gzip .gz .tgz\n</code></pre>\n</blockquote>\n'}, {'answer_id': 9169300, 'author': 'Arno Schäfer', 'author_id': 1193560, 'author_profile': 'https://Stackoverflow.com/users/1193560', 'pm_score': 3, 'selected': False, 'text': '<p>I am afraid MultiViews will not work as expected: the doc says Multiviews works "if the server receives a request for /some/dir/foo, if /some/dir has MultiViews enabled, and /some/dir/foo does not exist...", in other words: if you have a file foo.js and foo.js.gz in the same directory, just activating MultiViews will not cause the .gz file to be sent even if the AcceptEncoding gzip header is transmitted by the browser (you can verify this behavior by temporarily disabling mod_deflate and monitoring the response with e.g. HTTPFox).</p>\n\n<p>I am not sure if there is a way around this with MultiViews (maybe you can rename the original file and then add a special AddEncoding directive), but I believe you can construct a mod_rewrite rule to handle this.</p>\n'}, {'answer_id': 25556606, 'author': 'Vivien', 'author_id': 2191299, 'author_profile': 'https://Stackoverflow.com/users/2191299', 'pm_score': 0, 'selected': False, 'text': '<p>I have a lot of big .json files. Most readers are in this situation. The preview answers didn\'t talk about the returned "Content-type".</p>\n\n<p>I you want the following request return a pre-compressed file with "Content-Type: application/json" transparently, use Multiview with ForceType</p>\n\n<pre><code>http://www.domain.com/(...)/bigfile.json\n-> Content-Encoding:gzip, Content-Type: Content-Encoding:gzip\n</code></pre>\n\n<p>1) files must be rename: "file.ext.ext"</p>\n\n<p>2) Multiview works great with ForceType</p>\n\n<p>In the file system:</p>\n\n<pre><code>// Note there is no bigfile.json\n(...)/bigfile.json.gz\n(...)/bigfile.json.json\n</code></pre>\n\n<p>In your apache config:</p>\n\n<pre><code><Directory (...)>\n AddEncoding gzip .gz\n Options +Multiviews\n <Files *.json.gz>\n ForceType application/json\n </Files>\n</Directory>\n</code></pre>\n\n<p>Short and simple :)</p>\n'}, {'answer_id': 34932031, 'author': 'Kevinoid', 'author_id': 503410, 'author_profile': 'https://Stackoverflow.com/users/503410', 'pm_score': 3, 'selected': False, 'text': '<p>It is possible to serve pre-compressed files using <code>mod_negotiation</code> although it is a bit finicky. The primary difficulty is that <strong><a href="https://httpd.apache.org/docs/2.4/mod/mod_negotiation.html#multiviews" rel="nofollow noreferrer">only requests for files which do not exist are negotiated</a></strong>. So if <code>foo.js</code> and <code>foo.js.gz</code> both exist, responses for <code>/foo.js</code> will always be uncompressed (although responses for <code>/foo</code> would work correctly).</p>\n\n<p>The easiest solution I\'ve found (<a href="https://feeding.cloud.geek.nz/posts/serving-pre-compressed-files-using/" rel="nofollow noreferrer">from François Marier</a>) is to rename uncompressed files with a double file extension, so <code>foo.js</code> is deployed as <code>foo.js.js</code> so requests for <code>/foo.js</code> negotiate between <code>foo.js.js</code> (no encoding) and <code>foo.js.gz</code> (gzip encoding).</p>\n\n<p>I combine that trick with the following configuration:</p>\n\n<pre><code>Options +MultiViews\nRemoveType .gz\nAddEncoding gzip .gz\n\n# Send .tar.gz without Content-Encoding: gzip\n<FilesMatch ".+\\.tar\\.gz$">\n RemoveEncoding .gz\n # Note: Can use application/x-gzip for backwards-compatibility\n AddType application/gzip .gz\n</FilesMatch>\n</code></pre>\n\n<p>I <a href="https://kevinlocke.name/bits/2016/01/20/serving-pre-compressed-files-with-apache-multiviews/" rel="nofollow noreferrer">wrote a post</a> which discusses the reasoning for this configuration and some alternatives in detail.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9594/'] |
75,487 | <p>I'm looking mainly at things like new SQL syntax, new kinds of locking, new capabilities etc. Not so much in the surrounding services like data warehousing and reports...</p>
| [{'answer_id': 75515, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<ul>\n<li>New separate types for Date and Time, instead of just Datetime</li>\n<li>New geographic types for lattitude/longitude</li>\n<li>Change Data Capture is pretty neat if you're doing anything where auditing is important</li>\n<li>Configuration Servers, for maintaining multiple databases.</li>\n</ul>\n\n<p>That's what caught my attention at the Heroes Happen Here launch back in April.</p>\n"}, {'answer_id': 75520, 'author': 'MagicKat', 'author_id': 8505, 'author_profile': 'https://Stackoverflow.com/users/8505', 'pm_score': 0, 'selected': False, 'text': '<p>HotAdd CPU. <a href="http://msdn.microsoft.com/en-us/library/bb964703.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb964703.aspx</a></p>\n'}, {'answer_id': 75522, 'author': 'Phillip Wells', 'author_id': 3012, 'author_profile': 'https://Stackoverflow.com/users/3012', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a great article on the new T-SQL features <a href="http://msdn.microsoft.com/en-us/library/cc721270.aspx" rel="nofollow noreferrer">here</a> (by SQL guru Itzik Ben-Gan). It covers</p>\n\n<ul>\n<li>Declaring and initializing variables\n<li>Compound assignment operators\n<li>Table value constructor support through the VALUES clause\n<li>Enhancements to the CONVERT function\n<li>New date and time data types and functions\n<li>Large UDTs (GEOMETRY and GEOGRAPHY)\n<li>The HIERARCHYID data type\n<li>Table types and table-valued parameters\n<li>The MERGE statement, grouping sets enhancements\n<li>DDL trigger enhancements\n<li>Sparse columns\n<li>Filtered indexes\n<li>Large CLR user-defined aggregates\n<li>Multi-input CLR user-defined aggregates\n<li>The ORDER option for CLR table-valued functions\n<li>Object dependencies\n<li>Change data capture\n<li>Collation alignment with Microsoft® Windows®\n<li>Deprecation\n</ul>\n'}, {'answer_id': 75532, 'author': 'Mostlyharmless', 'author_id': 12881, 'author_profile': 'https://Stackoverflow.com/users/12881', 'pm_score': 1, 'selected': True, 'text': '<p>Did you check the whitepaper on the website? \n<a href="http://www.microsoft.com/sqlserver/2008/en/us/overview.aspx" rel="nofollow noreferrer"> SQL Server 2008 Overview. </a></p>\n\n<p>I cannot recall off the top of my head, but it atleast has a nice database to object linking functionality. They have geospatial types too, if you need to use those.</p>\n'}, {'answer_id': 75554, 'author': 'Andrew Jahn', 'author_id': 5831, 'author_profile': 'https://Stackoverflow.com/users/5831', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://download.microsoft.com/download/6/9/d/69d1fea7-5b42-437a-b3ba-a4ad13e34ef6/SQL2008_ProductOverview.docx" rel="nofollow noreferrer">white paper on SQL Server 2008</a></p>\n\n<p>This should cover most of the new features. I noticed the new date time data types and new security features.</p>\n'}, {'answer_id': 75716, 'author': 'stephbu', 'author_id': 12702, 'author_profile': 'https://Stackoverflow.com/users/12702', 'pm_score': 2, 'selected': False, 'text': '<p>Filestream blob storage is the biggest bonus to me</p>\n'}, {'answer_id': 76078, 'author': 'David Vidmar', 'author_id': 11063, 'author_profile': 'https://Stackoverflow.com/users/11063', 'pm_score': 0, 'selected': False, 'text': '<p>Page compressiong sounds really nice to me. Haven\'t used it yet, though.</p>\n\n<p><a href="http://sqlblog.com/blogs/linchi_shea/archive/2008/05/11/sql-server-2008-page-compression-compression-ratios-from-real-world-databases.aspx" rel="nofollow noreferrer">http://sqlblog.com/blogs/linchi_shea/archive/2008/05/11/sql-server-2008-page-compression-compression-ratios-from-real-world-databases.aspx</a></p>\n'}, {'answer_id': 76786, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Sparse indexing for those with lots of NULLs. Also the DATETIME2 data type that a lot of people have been waiting for 0001-01-01 through 9999-12-31.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5777/'] |
75,489 | <p>I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.<br><br> I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.<br>
<br>
Any advice?</p>
<p>Thanks.</p>
| [{'answer_id': 75674, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 4, 'selected': True, 'text': '<p>The parseDate and formatDate tags work, but they work with Date objects.\nYou can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag.</p>\n\n<p>somewhere other than the jsp create your date object.</p>\n\n<pre><code>long longvalue = ...;//from database.\njava.util.Date dateValue = new java.util.Date(longvalue);\nrequest.setAttribute("dateValue", dateValue);\n</code></pre>\n\n<p>put it on the request and then you can access it in your tag like this.</p>\n\n<pre><code><fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>\n</code></pre>\n'}, {'answer_id': 2628641, 'author': 'BenM', 'author_id': 43850, 'author_profile': 'https://Stackoverflow.com/users/43850', 'pm_score': 6, 'selected': False, 'text': '<p>You can avoid having to make any changes to your Servlet by creating a date object within the JSP using the <code>jsp:useBean</code> and <code>jsp:setProperty</code> tags to set the time of newly created date object to that of the time stamp. For example:</p>\n\n<pre><code><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>\n<jsp:useBean id="dateValue" class="java.util.Date"/>\n<jsp:setProperty name="dateValue" property="time" value="${timestampValue}"/>\n<fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9450/'] |
75,495 | <p>When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)</p>
<p>The following code demonstrates the problem:</p>
<pre><code><Window x:Class="ExampleApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ExampleApplication3"
Title="Example" Height="600" Width="600">
<Grid Background="LightGray">
<loc:UserControl1 />
</Grid>
</Window>
</code></pre>
<p>The following definition of <code>UserControl1</code> displays reasonably at design time but displays as a fixed size at run time:</p>
<pre><code><UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid Background="LightCyan" />
</UserControl>
</code></pre>
<p>The following definition of <code>UserControl1</code> displays as a dot at design time but expands to fill the parent <code>Window1</code> at run time:</p>
<pre><code><UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Background="LightCyan" />
</UserControl>
</code></pre>
| [{'answer_id': 75527, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 6, 'selected': False, 'text': '<p>For Blend, a little known trick is to add these attributes to your usercontrol or window:</p>\n\n<pre><code> xmlns:d="http://schemas.microsoft.com/expression/blend/2008" \n xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" \nmc:Ignorable="d"\n d:DesignHeight="500" d:DesignWidth="600"\n</code></pre>\n\n<p>This will set the design height and width to 500 and 600 respectively. However this will only work for the blend designer. Not the Visual Studio Designer. </p>\n\n<p>As far as the Visual Studio Designer your technique is all that works. Which is why I don\'t use the Visual Studio Designer. ;)</p>\n'}, {'answer_id': 75606, 'author': 'Alex Duggleby', 'author_id': 5790, 'author_profile': 'https://Stackoverflow.com/users/5790', 'pm_score': 6, 'selected': True, 'text': '<p>In Visual Studio add the Width and Height attribute to your UserControl XAML, but in the code-behind insert this</p>\n\n<pre><code>public UserControl1()\n{\n InitializeComponent();\n if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n {\n this.Width = double.NaN; ;\n this.Height = double.NaN; ;\n }\n}\n</code></pre>\n\n<p>This checks to see if the control is running in Design-mode. If not (i.e. runtime) it will set the Width and Height to NaN (Not a number) which is the value you set it to if you remove the Width and Height attributes in XAML.</p>\n\n<p>So at design-time you will have the preset width and height (including if you put the user control in a form) and at runtime it will dock depending on its parent container.</p>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 79134, 'author': 'AndyL', 'author_id': 9944, 'author_profile': 'https://Stackoverflow.com/users/9944', 'pm_score': 3, 'selected': False, 'text': '<p>I do this all the time. Simply set the width and height values to "auto" where you instantiate your control, and this will override the design-time values for that UserControl.</p>\n\n<p>ie: <code><loc:UserControl1 Width="auto" Height="auto" /></code></p>\n\n<p>Another option is to set a combination of MinWidth and MinHeight to a size that allows design-time work, while Width and Height remain "auto". Obviously, this only works if you don\'t need the UserControl to size smaller than the min values at runtime.</p>\n'}, {'answer_id': 311897, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I do it similar, but my solution assures that if you add your control to an container in design mode, it will appear reasonably.</p>\n\n<pre><code>protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n if (this.Parent != null)\n {\n this.Width = double.NaN;\n this.Height = double.NaN;\n }\n}\n</code></pre>\n\n<p>what do you think?</p>\n'}, {'answer_id': 421841, 'author': 'Paul', 'author_id': 44636, 'author_profile': 'https://Stackoverflow.com/users/44636', 'pm_score': 0, 'selected': False, 'text': '<p>Thanks to the original answerer for this solution! For those that are interested, here it is in VB:</p>\n\n<pre><code>If LicenseManager.UsageMode <> LicenseUsageMode.Designtime Then\n Me.Width = Double.NaN\n Me.Height = Double.NaN\nEnd If\n</code></pre>\n'}, {'answer_id': 1208106, 'author': 'jpierson', 'author_id': 83658, 'author_profile': 'https://Stackoverflow.com/users/83658', 'pm_score': 0, 'selected': False, 'text': '<p>Some have suggested using the LicenseManager.UsageMode property which I\'ve never seen before but I have used the following code.</p>\n\n<pre><code>if(!DesignerProperties.GetIsInDesignMode(this))\n{\n this.Width = double.NaN;\n this.Height = double.NaN;\n}\n</code></pre>\n\n<p>esskar,</p>\n\n<p>I just want to add that you should generally always call the method of the base when overriding an "On" method.</p>\n\n<pre><code>protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n base.OnVisualParentChanged(oldParent);\n\n ...\n}\n</code></pre>\n\n<p>Great workaround by the way, I\'m using it myself now too.</p>\n'}, {'answer_id': 5526765, 'author': 'CLaRGe', 'author_id': 20507, 'author_profile': 'https://Stackoverflow.com/users/20507', 'pm_score': 3, 'selected': False, 'text': '<p>Here are a list of <a href="http://msdn.microsoft.com/en-us/library/ff602277%28v=vs.95%29.aspx" rel="nofollow noreferrer">Design-Time Attributes in the Silverlight Designer</a>. They are the same for the WPF designer.</p>\n\n<p>It lists all of the <code>d:</code> values available in the Designer such as <code>d:DesignHeight</code>, <code>d:DesignWidth</code>, <code>d:IsDesignTimeCreatable</code>, <code>d:CreateList</code> and several others.</p>\n'}, {'answer_id': 5909295, 'author': 'Ondrej', 'author_id': 741414, 'author_profile': 'https://Stackoverflow.com/users/741414', 'pm_score': 2, 'selected': False, 'text': '<p>I was looking for similar solution like the one used in Blend and with your mentions I created simple behavior class with two attached properties Width & Height that are applied only in DesinTime</p>\n\n<pre>\npublic static class DesignBehavior \n{\n private static readonly Type OwnerType = typeof (DesignBehavior);\n\n #region Width\n\n public static readonly DependencyProperty WidthProperty =\n DependencyProperty.RegisterAttached(\n "Width",\n typeof (double),\n OwnerType,\n new FrameworkPropertyMetadata(double.NaN, new PropertyChangedCallback(WidthChangedCallback)));\n\n public static double GetWidth(DependencyObject depObj)\n {\n return (double)depObj.GetValue(WidthProperty);\n }\n\n public static void SetWidth(DependencyObject depObj, double value)\n {\n depObj.SetValue(WidthProperty, value);\n }\n\n private static void WidthChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n if (DesignerProperties.GetIsInDesignMode(depObj)) {\n depObj.SetValue(FrameworkElement.WidthProperty, e.NewValue);\n }\n }\n\n #endregion\n\n #region Height\n\n public static readonly DependencyProperty HeightProperty =\n DependencyProperty.RegisterAttached(\n "Height",\n typeof (double),\n OwnerType,\n new FrameworkPropertyMetadata(double.NaN, new PropertyChangedCallback(HeightChangedCallback)));\n\n public static double GetHeight(DependencyObject depObj)\n {\n return (double)depObj.GetValue(HeightProperty);\n }\n\n public static void SetHeight(DependencyObject depObj, double value)\n {\n depObj.SetValue(HeightProperty, value);\n }\n\n\n private static void HeightChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n if (DesignerProperties.GetIsInDesignMode(depObj)) {\n depObj.SetValue(FrameworkElement.HeightProperty, e.NewValue);\n }\n }\n\n #endregion\n\n}\n</pre>\n\n<p>Then in your UserControl you just set these properties in Xaml</p>\n\n<pre>\n<UserControl x:Class="ExtendedDataGrid.Views.PersonOverviewView"\n xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n xmlns:tool="http://schemas.microsoft.com/wpf/2008/toolkit"\n xmlns:b="clr-namespace:ExtendedDataGrid.Behaviors"\n b:DesignBehavior.Width="600" b:DesignBehavior.Height="200">\n <Grid>\n ...\n </Grid>\n</UserControl>\n</pre>\n'}, {'answer_id': 12169914, 'author': 'Roger Dufresne', 'author_id': 1631841, 'author_profile': 'https://Stackoverflow.com/users/1631841', 'pm_score': 1, 'selected': False, 'text': "<p>Use MinWidth and MinHeight on the control. That way, you'll see it in the designer, and at runtime it will size the way you want.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/317/'] |
75,500 | <p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
| [{'answer_id': 75524, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': '<p>How about pdf2tiff? <a href="http://python.net/~gherman/pdf2tiff.html" rel="nofollow noreferrer">http://python.net/~gherman/pdf2tiff.html</a></p>\n'}, {'answer_id': 75567, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 7, 'selected': True, 'text': '<p>Use Imagemagick, or better yet, Ghostscript.</p>\n\n<p><a href="http://www.ibm.com/developerworks/library/l-graf2/#N101C2" rel="noreferrer">http://www.ibm.com/developerworks/library/l-graf2/#N101C2</a> has an example for imagemagick:</p>\n\n<pre><code>convert foo.pdf pages-%03d.tiff\n</code></pre>\n\n<p><a href="http://www.asmail.be/msg0055376363.html" rel="noreferrer">http://www.asmail.be/msg0055376363.html</a> has an example for ghostscript:</p>\n\n<pre><code>gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit\n</code></pre>\n\n<p>I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.</p>\n'}, {'answer_id': 75590, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://pypi.org/project/pdf2tiff/" rel="nofollow noreferrer">https://pypi.org/project/pdf2tiff/</a></p>\n\n<p>You could also use pdf2ps, ps2image and then convert from the resulting image to tiff with other utilities (I remember \'paul\' [paul - Yet another image viewer (displays PNG, TIFF, GIF, JPG, etc.])</p>\n'}, {'answer_id': 75593, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 2, 'selected': False, 'text': '<p>ABCPDF can do so as well -- check out <a href="http://www.websupergoo.com/helppdf6net/default.html" rel="nofollow noreferrer"><a href="http://www.websupergoo.com/helppdf6net/default.html" rel="nofollow noreferrer">http://www.websupergoo.com/helppdf6net/default.html</a></a></p>\n'}, {'answer_id': 98191, 'author': 'Lou Franco', 'author_id': 3937, 'author_profile': 'https://Stackoverflow.com/users/3937', 'pm_score': 2, 'selected': False, 'text': '<p>Disclaimer: work for product I am recommending</p>\n\n<p>Atalasoft has a .NET library that can <a href="http://www.atalasoft.com/products/dotimage/net-tiff-pdf-sdk.aspx" rel="nofollow noreferrer">convert PDF to TIFF</a> -- we are a partner of FOXIT, so the PDF rendering is very good.</p>\n'}, {'answer_id': 113276, 'author': 'tomasso', 'author_id': 15043, 'author_profile': 'https://Stackoverflow.com/users/15043', 'pm_score': 6, 'selected': False, 'text': "<p>Using GhostScript from the command line, I've used the following in the past:</p>\n\n<p>on Windows:</p>\n\n<p><code>gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf</code></p>\n\n<p>on *nix:</p>\n\n<p><code>gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf</code></p>\n\n<p>For a large number of files, a simple batch/shell script could be used to convert an arbitrary number of files...</p>\n"}, {'answer_id': 120316, 'author': 'gyurisc', 'author_id': 260, 'author_profile': 'https://Stackoverflow.com/users/260', 'pm_score': 4, 'selected': False, 'text': '<p>I wrote a little powershell script to go through a directory structure and convert all pdf files to tiff files using ghostscript. Here is my script: </p>\n\n<pre><code>$tool = \'C:\\Program Files\\gs\\gs8.63\\bin\\gswin32c.exe\'\n$pdfs = get-childitem . -recurse | where {$_.Extension -match "pdf"}\n\nforeach($pdf in $pdfs)\n{\n\n $tiff = $pdf.FullName.split(\'.\')[0] + \'.tiff\'\n if(test-path $tiff)\n {\n "tiff file already exists " + $tiff\n }\n else \n { \n \'Processing \' + $pdf.Name \n $param = "-sOutputFile=$tiff"\n & $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit\n }\n}\n</code></pre>\n'}, {'answer_id': 221341, 'author': 'Setori', 'author_id': 21537, 'author_profile': 'https://Stackoverflow.com/users/21537', 'pm_score': 3, 'selected': False, 'text': '<p>using python this is what I ended up with</p>\n<pre class="lang-py prettyprint-override"><code>import os\nos.popen(\' \'.join([\n self._ghostscriptPath + \'gswin32c.exe\', \n \'-q\',\n \'-dNOPAUSE\',\n \'-dBATCH\',\n \'-r300\',\n \'-sDEVICE=tiff12nc\',\n \'-sPAPERSIZE=a4\',\n \'-sOutputFile=%s %s\' % (tifDest, pdfSource),\n ]))\n</code></pre>\n'}, {'answer_id': 2428473, 'author': 'John', 'author_id': 291872, 'author_profile': 'https://Stackoverflow.com/users/291872', 'pm_score': 1, 'selected': False, 'text': '<p>I like PDFTIFF.com to <a href="http://www.pdftiff.com" rel="nofollow noreferrer">convert PDF to TIFF</a>, it can handle unlimited pages</p>\n'}, {'answer_id': 3790112, 'author': 'Tyler', 'author_id': 457635, 'author_profile': 'https://Stackoverflow.com/users/457635', 'pm_score': 3, 'selected': False, 'text': '<p>1) Install GhostScript</p>\n\n<p>2) Install ImageMagick</p>\n\n<p>3) Create "Convert-to-TIFF.bat" (Windows XP, Vista, 7) and use the following line:</p>\n\n<pre><code>for %%f in (%*) DO "C:\\Program Files\\ImageMagick-6.6.4-Q16\\convert.exe" -density 300 -compress lzw %%f %%f.tiff\n</code></pre>\n\n<p>Dragging any number of single-page PDF files onto this file will convert them to compressed TIFFs, at 300 DPI. </p>\n'}, {'answer_id': 7511450, 'author': 'Russell Wong', 'author_id': 360257, 'author_profile': 'https://Stackoverflow.com/users/360257', 'pm_score': 2, 'selected': False, 'text': "<p>Required ghostscript & tiffcp\nTested in Ubuntu</p>\n\n<pre><code>import os\n\ndef pdf2tiff(source, destination):\n idx = destination.rindex('.')\n destination = destination[:idx]\n args = [\n '-q', '-dNOPAUSE', '-dBATCH',\n '-sDEVICE=tiffg4',\n '-r600', '-sPAPERSIZE=a4',\n '-sOutputFile=' + destination + '__%03d.tiff'\n ]\n gs_cmd = 'gs ' + ' '.join(args) +' '+ source\n os.system(gs_cmd)\n args = [destination + '__*.tiff', destination + '.tiff' ]\n tiffcp_cmd = 'tiffcp ' + ' '.join(args)\n os.system(tiffcp_cmd)\n args = [destination + '__*.tiff']\n rm_cmd = 'rm ' + ' '.join(args)\n os.system(rm_cmd) \npdf2tiff('abc.pdf', 'abc.tiff')\n</code></pre>\n"}, {'answer_id': 8065301, 'author': 'Sally', 'author_id': 1037695, 'author_profile': 'https://Stackoverflow.com/users/1037695', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe also try this? <a href="http://www.sautinsoft.com/products/pdf-focus/index.php" rel="nofollow">PDF Focus</a></p>\n\n<p>This .Net library allows you to solve the problem :)</p>\n\n<p>This code will help (Convert 1000 PDF files to 300-dpi TIFF files in C#):</p>\n\n<pre><code> SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\n string[] pdfFiles = Directory.GetFiles(@"d:\\Folder with 1000 pdfs\\", "*.pdf");\n string folderWithTiffs = @"d:\\Folder with TIFFs\\";\n\n foreach (string pdffile in pdfFiles)\n {\n f.OpenPdf(pdffile);\n\n if (f.PageCount > 0)\n {\n //save all pages to tiff files with 300 dpi\n f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);\n }\n f.ClosePdf();\n }\n</code></pre>\n'}, {'answer_id': 8353467, 'author': 'k venkat', 'author_id': 1076963, 'author_profile': 'https://Stackoverflow.com/users/1076963', 'pm_score': 2, 'selected': False, 'text': '<p>The PDF Focus .Net can do it in such way:</p>\n\n<p><strong>1.</strong> <em><strong>PDF to TIFF</em></strong></p>\n\n<pre><code>SautinSoft.PdfFocus f = new SautinSoft.PdfFocus(); \n\nstring pdfPath = @"c:\\My.pdf";\n\nstring imageFolder = @"c:\\images\\";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount > 0)\n{\n //Save all PDF pages to image folder as tiff images, 200 dpi\n int result = f.ToImage(imageFolder, "page",System.Drawing.Imaging.ImageFormat.Tiff, 200);\n}\n</code></pre>\n\n<p><strong>2.</strong> <em><strong>PDF to Multipage-TIFF</em></strong></p>\n\n<pre><code>//Convert PDF file to Multipage TIFF file\n\nSautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\nstring pdfPath = @"c:\\Document.pdf";\nstring tiffPath = @"c:\\Result.tiff";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount > 0)\n{\n f.ToMultipageTiff(tiffPath, 120) == 0)\n {\n System.Diagnostics.Process.Start(tiffPath);\n }\n} \n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260/'] |
75,508 | <p>I have 28,000 images I need to convert into a movie.
I tried </p>
<pre><code>mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi
</code></pre>
<p>But it seems to crap out at 7500 frames.</p>
<p>The files are named
webcam_2007-04-16_070804.jpg
webcam_2007-04-16_071004.jpg
webcam_2007-04-16_071204.jpg
webcam_2007-04-16_071404.jpg
Up to march 2008 or so.</p>
<p>Is there another way I can pass the filenames to mencoder so it doesn't stop part way?</p>
<pre><code>MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team
CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7)
CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1
Compiled with runtime CPU detection.
success: format: 16 data: 0x0 - 0x0
MF file format detected.
[mf] search expr: *.jpg
[mf] number of files: 28617 (114468)
VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s)
[V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333
Opening video filter: [expand osd=1]
Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder)
==========================================================================
VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12)
VDec: using Planar YV12 as output csp (no 3)
Movie-Aspect is 1.33:1 - prescaling to correct movie aspect.
videocodec: libavcodec (640x480 fourcc=3234504d [MP42])
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0]
Flushing video frames.
Writing index...
Writing header...
ODML: Aspect information not (yet?) available or unspecified, not writing vprp header.
Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames
</code></pre>
| [{'answer_id': 75566, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 0, 'selected': False, 'text': '<p>another alternative is to bypass mencoder and use ffmpeg directly</p>\n'}, {'answer_id': 75616, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 1, 'selected': False, 'text': '<p>You might be better off going to #mplayer or #ffmpeg on Freenode IRC for specific help with those programs.</p>\n'}, {'answer_id': 75635, 'author': 'metadave', 'author_id': 7237, 'author_profile': 'https://Stackoverflow.com/users/7237', 'pm_score': 0, 'selected': False, 'text': '<p>Kinda of an odd answer... but I thought that Blender could construct videos from sequences of images. Just a thought.</p>\n'}, {'answer_id': 75668, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 3, 'selected': True, 'text': '<p>Shove the list of images in a file, one per line. Then use <code>mf://@filename</code></p>\n'}, {'answer_id': 83658, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You can create a video from a sequence of images using LiVES:\n<a href="http://lives.sourceforge.net" rel="nofollow noreferrer">http://lives.sourceforge.net</a></p>\n\n<p>Simply place all of the images in a directory, and make sure they are in alphanumeric order.\nThen in LiVES, just go to File/Open File or Directory, and double-click on the image directory.</p>\n\n<p>Once the images have loaded you can edit the clip and save it in a variety of formats.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11950/'] |
75,526 | <p>I understand that some countries have laws regarding website accessibility. In general, what are the minimum requirements that a website must meet to be accessible, regardless of country? Or, in lieu of minimum requirements, what are some specific things that websites should have to make the accessible?</p>
| [{'answer_id': 75586, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': 0, 'selected': False, 'text': "<p>It's not a binary question, and there's no silver bullet. Making sure you follow at least the basics of WCAG and testing in a couple of screen readers and without the mouse will probably be the most effective use of your time. If at all possible, test with real people with real disabilities, they have a perspective that is hard for fully-abled people to attain.</p>\n"}, {'answer_id': 75612, 'author': 'Scott Gowell', 'author_id': 6943, 'author_profile': 'https://Stackoverflow.com/users/6943', 'pm_score': 1, 'selected': False, 'text': '<p>I recommend <a href="http://aprompt.snow.utoronto.ca/" rel="nofollow noreferrer">A-prompt</a> for testing of Accessibility.\nIt is free and it can really help.</p>\n\n<p>I also recommend Mark Pilgrim\'s online text - <a href="http://diveintoaccessibility.org/" rel="nofollow noreferrer">Dive into Accessibility</a>.</p>\n'}, {'answer_id': 75613, 'author': 'James B', 'author_id': 2951, 'author_profile': 'https://Stackoverflow.com/users/2951', 'pm_score': 0, 'selected': False, 'text': '<p>Well, obviously the law in different countries varies vastly. In the UK, for example, we don\'t have any specific web-accessibility laws, but no service is allowed to discriminate against someone with a sight or hearing impediment, insofar as it relates to functionality.</p>\n\n<p>In light of this, a simplistic way to design would be to ensure that your website is readable by screen-readers, can be tabbed through successfully and in a logical order, and allows the scaling of screen elements (including images and font sizes) correctly for those who require web-pages to be magnified.</p>\n\n<p>In addition, your website should have functionality fall-backs in place for any JavaScript and Flash, such that if they were turned off (such as is the case in many screen readers) all functionality is still usable. Don\'t rely on WAI-ARIA for JavaScript accessibility, as it isn\'t standardised, and it isn\'t widely supported.</p>\n\n<p>Of course, this doesn\'t necessarily cover every possible law, but it\'s a good starting point. If your website meets the above \'criteria\', you\'re likely to have a good level of accessibility. There is <a href="http://checker.atrc.utoronto.ca/index.html" rel="nofollow noreferrer">a test</a> for accessibility, of sorts, following WCAG but it\'s by no means \'conclusive\' for what is an acceptable level of accessibility in each individual country.</p>\n'}, {'answer_id': 75658, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 3, 'selected': True, 'text': '<p>W3C publishes Web Content Accessibility Guidelines:</p>\n\n<p><a href="http://www.w3.org/TR/WAI-WEBCONTENT/" rel="nofollow noreferrer">http://www.w3.org/TR/WAI-WEBCONTENT/</a></p>\n\n<p>If you want a quick summary list, look for the yellow-highlighted lines in that document. Each guideline is also broken down into specific requirements ("checkpoints") in one of three priorities - to claim any kind of accessibility under this scheme you must satisfy all priority 1 checkpoints, but they\'re "necessary" rather than "sufficient" conditions.</p>\n\n<p>Looking at your pages in lynx is also a good measure - if it won\'t render in text, chances are good that a screen reader will have a difficult time of it too.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13281/'] |
75,533 | <p>I'm trying to have the same KDE Konsole experience within Mac OS X.</p>
<p>Here's my (overly complicated?) setup:</p>
<ul>
<li>I have Control and Command swapped at the System Preferences level. (Can't live without this)</li>
<li>Parallels lets you, at the Parallels application level, also reverse Control and Command. So I can undo the System Preferences setting (and get the setup I want within virtual Linux)</li>
</ul>
<p>I want this same per-application-opt-out for the Mac OS X Terminal app. Is it possible?</p>
| [{'answer_id': 194426, 'author': 'haa', 'author_id': 12115, 'author_profile': 'https://Stackoverflow.com/users/12115', 'pm_score': 2, 'selected': False, 'text': '<p>You can <strong>simply ssh into the Linux/Unix system</strong> and run X11 programs direct to your Mac screen: <code>ssh -X user@host_or_ipaddress</code>, login, and just run the X11 programs you want (e.g. <code>emacs&</code>) and the X11 apps will appear on the Mac display.</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>X11 windows work just like any other window, including Exposé goodness, etc...</li>\n<li>No need to work only inside the Parallels console window</li>\n<li>Same solution works with any Linux/Unix system, remote or virtual</li>\n<li>ssh connection is secure even over the internet</li>\n</ul>\n\n<p>Tech info:</p>\n\n<ul>\n<li>"ssh -X" turns on X11 forwarding for the ssh connection, i.e. the X11 display connection is tunneled through ssh securely</li>\n<li>"ssh -X" also handles X11 authentication tunneling</li>\n<li><code>X11.app</code> is automagically started on OSX by <code>launchd</code> when needed</li>\n<li>X11 can connect to displays over the network, which is one of the few cool things about it ;-)</li>\n</ul>\n'}, {'answer_id': 977228, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can customize the command keys used for an individual application in System Preferences > Keyboard & Mouse > Keyboard Shortcuts. I think (if I understand correctly what you\'re trying to do) that this might allow you to accomplish your goal. You could remap all of Terminal\'s command keys to use control instead of command, to get them out of your way... but then you might need to do a lot of customization on the machines you ssh into, so that they use Command instead of control</p>\n\n<p>It seems that you\'re going to have to do an ENORMOUS amount of work just to allow you to use your pinky instead of your thumb for the modifier key. </p>\n\n<p>Another possibility: user preferences can be manipulated by the "defaults" command. I haven\'t been able to find a way to use this to control they modifier key mappings, but it should logically be possible (if you\'re willing to do a lot of digging). If so, then you could write short scripts to switch back and forth between Mac default and your swapped mode. Trigger the scripts with Quicksilver, and whenever you use Terminal you can call one script, and whenever you leave it you can call another. Again, a big pain to achieve what you want, but it <em>might</em> be possible.</p>\n\n<p>I don\'t think there\'s a clean and simple solution. </p>\n\n<p>I\'ve seen third-party programs that give more control over manipulating modifier keys, if you\'re willing to install them (probably kernel extensions). They <em>might</em> be able to do what you want, but I don\'t recall the names. If you google for programs to fix emacs and vi keys you might find them.</p>\n\n<p>Good luck.</p>\n'}, {'answer_id': 4619639, 'author': 'Mario F', 'author_id': 3785, 'author_profile': 'https://Stackoverflow.com/users/3785', 'pm_score': 0, 'selected': False, 'text': '<p>I had exactly the same problem as you. I\'ve remapped Command to CAPS Lock, and Control to Command, but as a frequent Linux user I want both setups to be as similar as possible. This is how I solved it:</p>\n\n<ul>\n<li>Install <a href="http://www.keyboardmaestro.com/main/" rel="nofollow">Keyboard Maestro</a> (not free, but totally worth it), and set it up to run at login.</li>\n<li>Inside KM, define macros to send <em>CMD+{key}</em> to <em>CTRL+{key}</em> inside <strong>Terminal</strong>.</li>\n</ul>\n\n<p>If you want to remap a lot of keys this is <strong>a lot</strong> of work. But I\'ve already done it myself, you can just download this file <a href="http://dl.dropbox.com/u/3093385/terminal.kmmacros" rel="nofollow">kmmacros</a>. Double-clicking is enough to install it. A couple of caveats:</p>\n\n<ul>\n<li>You need to set <strong>Terminal</strong> to use option as a meta key (Terminal > Preferences > Keyboard).</li>\n<li>The bindings are only for emacs-mode. <a href="http://www.scribd.com/doc/985254/Bash-Emacs-Editing-Mode-readline-Cheat-Sheet" rel="nofollow">This</a> cheat sheet should be helpful.</li>\n<li>Most default shortcuts don\'t work anymore (<em>CMD-N</em>, <em>CMD-C</em>, ...), and the menu in <strong>Terminal</strong> does not reflect this. For some conflicts (New Window, Close Window), I\'ve taken the ones from Gnome.</li>\n</ul>\n'}, {'answer_id': 8332329, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>The solution you\'re looking for is <strong><a href="http://pqrs.org/macosx/keyremap4macbook/index.html">KeyRemap4MacBook</a></strong>. There is a Tiger, Leopard, Snow Leopard, and Lion version.</p>\n\n<p>Once installed, goto <strong>System Preferences</strong> -> <strong>KeyRemap4MacBook</strong></p>\n\n<p>Then select the following options:</p>\n\n<ul>\n<li>Change Command_L Key (Left Command)</li>\n<li>---> Command_L to Control_L (except Terminal, Virtual Machine, RDC)</li>\n<li>Change Control_L Key (Left Control)</li>\n<li>---> Control_L to Command_L (except Terminal, Virtual Machine, RDC)</li>\n</ul>\n\n<p>You can repeat this for Command_R (Right Command) and Control_R (Right Control) also if you desire. Tested and working on my Macbook.</p>\n'}, {'answer_id': 15505757, 'author': 'vikor', 'author_id': 1430433, 'author_profile': 'https://Stackoverflow.com/users/1430433', 'pm_score': 2, 'selected': False, 'text': '<p>There is very good and key-mapping flexible terminal: <a href="http://www.iterm2.com" rel="nofollow">iTerm2</a></p>\n\n<p>My favorite set: iTerm + zsh + <a href="https://github.com/robbyrussell/oh-my-zsh" rel="nofollow">oh-my-zsh</a></p>\n'}, {'answer_id': 34832557, 'author': 'dorserg', 'author_id': 376893, 'author_profile': 'https://Stackoverflow.com/users/376893', 'pm_score': 2, 'selected': False, 'text': '<p>The 2016 solution is to use <a href="https://github.com/tekezo/Karabiner" rel="nofollow noreferrer">Karabiner</a> open-source program which allows you to remap modifier and other keys with <strong>very fine granularity</strong>, for example</p>\n\n<ul>\n<li>Remap only the <strong>left</strong> <kbd>⌘ Cmd</kbd> or <kbd>Option</kbd> key.</li>\n<li>Remap a key only for specific applications, e.g. only inside Terminal, Emacs, or virtual machine.</li>\n</ul>\n\n<p>For example, here\'s how to remap left <kbd>⌘ Cmd</kbd> key to act as <kbd>Ctrl</kbd> <strong>only inside Terminal</strong> (and leave the right one unaffected so that you could still use e.g. <kbd>⌘ Cmd + Tab</kbd> to switch between apps):</p>\n\n<p><a href="https://i.stack.imgur.com/GnqQ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GnqQ7.png" alt="karabiner-screenshot"></a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8913/'] |
75,538 | <p>No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?</p>
| [{'answer_id': 75581, 'author': 'neuroguy123', 'author_id': 12529, 'author_profile': 'https://Stackoverflow.com/users/12529', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not sure about hidden, but there are some <a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow noreferrer">interesting</a> <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow noreferrer">\'tricks\'</a> that probably aren\'t obvious from just reading the spec.</p>\n'}, {'answer_id': 75627, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': '<blockquote>\n <p>C++ is a standard, there shouldn\'t be any hidden features...</p>\n</blockquote>\n\n<p>C++ is a multi-paradigm language, you can bet your last money on there being hidden features. One example out of many: <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow noreferrer">template metaprogramming</a>. Nobody in the standards committee intended there to be a Turing-complete sublanguage that gets executed at compile-time.</p>\n'}, {'answer_id': 75709, 'author': 'Drealmer', 'author_id': 12291, 'author_profile': 'https://Stackoverflow.com/users/12291', 'pm_score': 3, 'selected': False, 'text': '<p>I found this blog to be an amazing resource about the arcanes of C++ : <a href="http://cpptruths.blogspot.com/" rel="nofollow noreferrer">C++ Truths</a>.</p>\n'}, {'answer_id': 75818, 'author': 'sergtk', 'author_id': 13441, 'author_profile': 'https://Stackoverflow.com/users/13441', 'pm_score': 3, 'selected': False, 'text': '<p>There is no hidden features, but the language C++ is very powerful and frequently even developers of standard couldn\'t imagine what C++ can be used for. </p>\n\n<p>Actually from simple enough language construction you can write something very powerful.\nA lot of such things are available at www.boost.org as an examples (and <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html" rel="noreferrer">http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html</a> among them).</p>\n\n<p>To understand the way how simple language constuction can be combined to something powerful it is good to read <a href="https://rads.stackoverflow.com/amzn/click/com/0201734842" rel="noreferrer" rel="nofollow noreferrer">"C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis</a> and really magic book <a href="https://rads.stackoverflow.com/amzn/click/com/0201704315" rel="noreferrer" rel="nofollow noreferrer">"Modern C++ Design ... " by Andrei Alexandrescu</a>.</p>\n\n<p>And finally, it is difficult to learn C++, you should try to fill it ;)</p>\n'}, {'answer_id': 75849, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 2, 'selected': False, 'text': '<p>There are a lot of "undefined behavior". You can learn how to avoid them reading good books and reading the standards.</p>\n'}, {'answer_id': 75917, 'author': 'Amir', 'author_id': 13480, 'author_profile': 'https://Stackoverflow.com/users/13480', 'pm_score': 1, 'selected': False, 'text': '<p>There are tons of "tricky" constructs in C++.\nThey go from "simple" implementions of <a href="http://www.gamedev.net/reference/programming/features/cppseal/" rel="nofollow noreferrer">sealed/final classes</a> using virtual inheritance.\nAnd get to pretty "complex" meta programming constructs such as Boost\'s <a href="http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html" rel="nofollow noreferrer">MPL</a> (<a href="http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html" rel="nofollow noreferrer">tutorial</a>). The possibilities for shooting yourself in the foot are endless, but if kept in check (i.e. seasoned programmers), provide some of the best flexibility in terms of maintainability and performance.</p>\n'}, {'answer_id': 76058, 'author': 'Markowitch', 'author_id': 11964, 'author_profile': 'https://Stackoverflow.com/users/11964', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n <p>One example out of many: template\n metaprogramming. Nobody in the\n standards committee intended there to\n be a Turing-complete sublanguage that\n gets executed at compile-time.</p>\n</blockquote>\n\n<p>Template metaprogramming is hardly a hidden feature. It\'s even in the boost library. See <a href="http://www.boost.org/doc/libs/release/libs/mpl/doc/index.html" rel="nofollow noreferrer">MPL</a>. But if "almost hidden" is good enough, then take a look at the <a href="http://www.boost.org/doc/libs" rel="nofollow noreferrer">boost libraries</a>. It contain many goodies which are not easy accesible without the backing of a strong library.</p>\n\n<p>One example is <a href="http://www.boost.org/doc/libs/release/doc/html/lambda.html" rel="nofollow noreferrer">boost.lambda</a> library, which is interesting since C++ does not have lambda functions in the current standard.</p>\n\n<p>Another example is <a href="http://loki-lib.sourceforge.net/index.php?n=Main.HomePage" rel="nofollow noreferrer">Loki</a>, which "makes extensive use of C++ template metaprogramming and implements several commonly used tools: typelist, functor, singleton, smart pointer, object factory, visitor and multimethods." [<a href="http://en.wikipedia.org/wiki/Loki_%28C%2B%2B%29" rel="nofollow noreferrer">Wikipedia</a>]</p>\n'}, {'answer_id': 76606, 'author': 'MSN', 'author_id': 6210, 'author_profile': 'https://Stackoverflow.com/users/6210', 'pm_score': 6, 'selected': False, 'text': "<p>Lifetime of temporaries bound to const references is one that few people know about. Or at least it's my favorite piece of C++ knowledge that most people don't know about.</p>\n\n<pre><code>const MyClass& x = MyClass(); // temporary exists as long as x is in scope\n</code></pre>\n"}, {'answer_id': 76801, 'author': 'Colin Jensen', 'author_id': 9884, 'author_profile': 'https://Stackoverflow.com/users/9884', 'pm_score': 6, 'selected': False, 'text': "<p>The array operator is associative.</p>\n\n<p>A[8] is a synonym for *(A + 8). Since addition is associative, that can be rewritten as *(8 + A), which is a synonym for..... 8[A]</p>\n\n<p>You didn't say useful... :-) </p>\n"}, {'answer_id': 77169, 'author': 'Sridhar Iyer', 'author_id': 13820, 'author_profile': 'https://Stackoverflow.com/users/13820', 'pm_score': 2, 'selected': False, 'text': '<p>Most C++ developers ignore the power of template metaprogramming. Check out <a href="http://loki-lib.sourceforge.net/index.php?n=Main.HomePage" rel="nofollow noreferrer">Loki Libary</a>. It implements several advanced tools like typelist, functor, singleton, smart pointer, object factory, visitor and multimethods using template metaprogramming extensively (from <a href="http://en.wikipedia.org/wiki/Loki_(C%2B%2B)" rel="nofollow noreferrer">wikipedia</a>). \nFor most part you could consider these as "hidden" c++ feature.</p>\n'}, {'answer_id': 78128, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 7, 'selected': False, 'text': '<p>I agree with most posts there: C++ is a multi-paradigm language, so the "hidden" features you\'ll find (other than "undefined behaviours" that you should avoid at all cost) are clever uses of facilities.</p>\n\n<p>Most of those facilities are not build-in features of the language, but library-based ones.</p>\n\n<p>The most important is the <strong>RAII</strong>, often ignored for years by C++ developers coming from the C world. <strong>Operator overloading</strong> is often a misunderstood feature that enable both array-like behaviour (subscript operator), pointer like operations (smart pointers) and build-in-like operations (multiplying matrices.</p>\n\n<p>The use of <strong>exception</strong> is often difficult, but with some work, can produce really robust code through <strong>exception safety</strong> specifications (including code that won\'t fail, or that will have a commit-like features that is that will succeed, or revert back to its original state).</p>\n\n<p>The most famous of "hidden" feature of C++ is <strong>template metaprogramming</strong>, as it enables you to have your program partially (or totally) executed at compile-time instead of runtime. This is difficult, though, and you must have a solid grasp on templates before trying it.</p>\n\n<p>Other make uses of the multiple paradigm to produce "ways of programming" outside of C++\'s ancestor, that is, C.</p>\n\n<p>By using <strong>functors</strong>, you can simulate functions, with the additional type-safety and being stateful. Using the <strong>command</strong> pattern, you can delay code execution. Most other <strong>design patterns</strong> can be easily and efficiently implemented in C++ to produce alternative coding styles not supposed to be inside the list of "official C++ paradigms".</p>\n\n<p>By using <strong>templates</strong>, you can produce code that will work on most types, including not the one you thought at first. You can increase type safety,too (like an automated typesafe malloc/realloc/free). C++ object features are really powerful (and thus, dangerous if used carelessly), but even the <strong>dynamic polymorphism</strong> have its static version in C++: the <strong>CRTP</strong>.</p>\n\n<p>I have found that most "<em>Effective C++</em>"-type books from Scott Meyers or "<em>Exceptional C++</em>"-type books from Herb Sutter to be both easy to read, and quite treasures of info on known and less known features of C++.</p>\n\n<p>Among my preferred is one that should make the hair of any Java programmer rise from horror: In C++, <strong>the most object-oriented way to add a feature to an object is through a non-member non-friend function, instead of a member-function</strong> (i.e. class method), because:</p>\n\n<ul>\n<li><p>In C++, a class\' interface is both its member-functions and the non-member functions in the same namespace</p></li>\n<li><p>non-friend non-member functions have no privileged access to the class internal. As such, using a member function over a non-member non-friend one will weaken the class\' encapsulation.</p></li>\n</ul>\n\n<p>This never fails to surprise even experienced developers.</p>\n\n<p>(Source: Among others, Herb Sutter\'s online Guru of the Week #84: <a href="http://www.gotw.ca/gotw/084.htm" rel="nofollow noreferrer">http://www.gotw.ca/gotw/084.htm</a> )</p>\n'}, {'answer_id': 78436, 'author': 'Robert', 'author_id': 14364, 'author_profile': 'https://Stackoverflow.com/users/14364', 'pm_score': 5, 'selected': False, 'text': "<p>Oooh, I can come up with a list of pet hates instead:</p>\n\n<ul>\n<li>Destructors need to be virtual if you intend use polymorphically</li>\n<li>Sometimes members are initialized by default, sometimes they aren't</li>\n<li>Local clases can't be used as template parameters (makes them less useful)</li>\n<li>exception specifiers: look useful, but aren't</li>\n<li>function overloads hide base class functions with different signatures.</li>\n<li>no useful standardisation on internationalisation (portable standard wide charset, anyone? We'll have to wait until C++0x)</li>\n</ul>\n\n<p>On the plus side</p>\n\n<ul>\n<li>hidden feature: function try blocks. Unfortunately I haven't found a use for it. Yes I know why they added it, but you have to rethrow in a constructor which makes it pointless.</li>\n<li>It's worth looking carefully at the STL guarantees about iterator validity after container modification, which can let you make some slightly nicer loops.</li>\n<li>Boost - it's hardly a secret but it's worth using.</li>\n<li>Return value optimisation (not obvious, but it's specifically allowed by the standard)</li>\n<li>Functors aka function objects aka operator(). This is used extensively by the STL. not really a secret, but is a nifty side effect of operator overloading and templates.</li>\n</ul>\n"}, {'answer_id': 78484, 'author': 'Jason Mock', 'author_id': 13630, 'author_profile': 'https://Stackoverflow.com/users/13630', 'pm_score': 7, 'selected': False, 'text': "<p>One language feature that I consider to be somewhat hidden, because I had never heard about it throughout my entire time in school, is the namespace alias. It wasn't brought to my attention until I ran into examples of it in the boost documentation. Of course, now that I know about it you can find it in any standard C++ reference.</p>\n\n<pre><code>namespace fs = boost::filesystem;\n\nfs::path myPath( strPath, fs::native );\n</code></pre>\n"}, {'answer_id': 78557, 'author': 'shoosh', 'author_id': 9611, 'author_profile': 'https://Stackoverflow.com/users/9611', 'pm_score': 2, 'selected': False, 'text': '<ul>\n<li>pointers to class methods </li>\n<li>The "typename" keyword</li>\n</ul>\n'}, {'answer_id': 78840, 'author': 'Ben', 'author_id': 13950, 'author_profile': 'https://Stackoverflow.com/users/13950', 'pm_score': 8, 'selected': False, 'text': '<p>You can put URIs into C++ source without error. For example:</p>\n\n<pre><code>void foo() {\n http://stackoverflow.com/\n int bar = 4;\n\n ...\n}\n</code></pre>\n'}, {'answer_id': 132174, 'author': 'bernardn', 'author_id': 21548, 'author_profile': 'https://Stackoverflow.com/users/21548', 'pm_score': -1, 'selected': False, 'text': "<p>Pointer arithmetics.</p>\n\n<p>It's actually a C feature, but I noticed that few people that use C/C++ are really aware it even exists. I consider this feature of the C language truly shows the genius and vision of its inventor.</p>\n\n<p>To make a long story short, pointer arithmetics allows the compiler to perform a[n] as *(a+n) for any type of a. As a side note, as '+' is commutative a[n] is of course equivalent to n[a].</p>\n"}, {'answer_id': 132815, 'author': 'AareP', 'author_id': 11741, 'author_profile': 'https://Stackoverflow.com/users/11741', 'pm_score': 4, 'selected': False, 'text': '<p>Getting rid of forward declarations:</p>\n\n<pre><code>struct global\n{\n void main()\n {\n a = 1;\n b();\n }\n int a;\n void b(){}\n}\nsingleton;\n</code></pre>\n\n<p>Writing switch-statements with ?: operators:</p>\n\n<pre><code>string result = \n a==0 ? "zero" :\n a==1 ? "one" :\n a==2 ? "two" :\n 0;\n</code></pre>\n\n<p>Doing everything on a single line:</p>\n\n<pre><code>void a();\nint b();\nfloat c = (a(),b(),1.0f);\n</code></pre>\n\n<p>Zeroing structs without memset: </p>\n\n<pre><code>FStruct s = {0};\n</code></pre>\n\n<p>Normalizing/wrapping angle- and time-values:</p>\n\n<pre><code>int angle = (short)((+180+30)*65536/360) * 360/65536; //==-150\n</code></pre>\n\n<p>Assigning references:</p>\n\n<pre><code>struct ref\n{\n int& r;\n ref(int& r):r(r){}\n};\nint b;\nref a(b);\nint c;\n*(int**)&a = &c;\n</code></pre>\n'}, {'answer_id': 152659, 'author': 'vividos', 'author_id': 23740, 'author_profile': 'https://Stackoverflow.com/users/23740', 'pm_score': 6, 'selected': False, 'text': "<p>A nice feature that isn't used often is the function-wide try-catch block:</p>\n\n<pre><code>int Function()\ntry\n{\n // do something here\n return 42;\n}\ncatch(...)\n{\n return -1;\n}\n</code></pre>\n\n<p>Main usage would be to translate exception to other exception class and rethrow, or to translate between exceptions and return-based error code handling.</p>\n"}, {'answer_id': 169114, 'author': 'Sumant', 'author_id': 25014, 'author_profile': 'https://Stackoverflow.com/users/25014', 'pm_score': 5, 'selected': False, 'text': '<p>Hidden features:</p>\n\n<ol>\n<li>Pure virtual functions can have implementation. Common example, pure virtual destructor.</li>\n<li><p>If a function throws an exception not listed in its exception specifications, but the function has <code>std::bad_exception</code> in its exception specification, the exception is converted into <code>std::bad_exception</code> and thrown automatically. That way you will at least know that a <code>bad_exception</code> was thrown. Read more <a href="http://cpptruths.blogspot.com/2007/05/use-of-stdbadexception.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>function try blocks</p></li>\n<li><p>The template keyword in disambiguating typedefs in a class template. If the name of a member template specialization appears after a <code>.</code>, <code>-></code>, or <code>::</code> operator, and that name has explicitly qualified template parameters, prefix the member template name with the keyword template. Read more <a href="http://en.wikibooks.org/wiki/More_C++_Idioms/Policy_Clone" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>function parameter defaults can be changed at runtime. Read more <a href="http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p><code>A[i]</code> works as good as <code>i[A]</code></p></li>\n<li><p>Temporary instances of a class can be modified! A non-const member function can be invoked on a temporary object. For example:</p>\n\n<pre><code>struct Bar {\n void modify() {}\n}\nint main (void) {\n Bar().modify(); /* non-const function invoked on a temporary. */\n}\n</code></pre>\n\n<p>Read more <a href="http://cpptruths.blogspot.com/2009/08/modifying-temporaries.html" rel="nofollow noreferrer">here</a>.</p></li>\n<li><p>If two different types are present before and after the <code>:</code> in the ternary (<code>?:</code>) operator expression, then the resulting type of the expression is the one that is the most general of the two. For example:</p>\n\n<pre><code>void foo (int) {}\nvoid foo (double) {}\nstruct X {\n X (double d = 0.0) {}\n};\nvoid foo (X) {} \n\nint main(void) {\n int i = 1;\n foo(i ? 0 : 0.0); // calls foo(double)\n X x;\n foo(i ? 0.0 : x); // calls foo(X)\n}\n</code></pre></li>\n</ol>\n'}, {'answer_id': 170597, 'author': 'Sirish', 'author_id': 7965, 'author_profile': 'https://Stackoverflow.com/users/7965', 'pm_score': 5, 'selected': False, 'text': '<p>Array initialization in constructor.\nFor example in a class if we have a array of <code>int</code> as:</p>\n\n<pre><code>class clName\n{\n clName();\n int a[10];\n};\n</code></pre>\n\n<p>We can initialize all elements in the array to its default (here all elements of array to zero) in the constructor as:</p>\n\n<pre><code>clName::clName() : a()\n{\n}\n</code></pre>\n'}, {'answer_id': 172357, 'author': 'Constantin', 'author_id': 20310, 'author_profile': 'https://Stackoverflow.com/users/20310', 'pm_score': 5, 'selected': False, 'text': "<p><code>map::operator[]</code> creates entry if key is missing and returns reference to default-constructed entry value. So you can write:</p>\n\n<pre><code>map<int, string> m;\nstring& s = m[42]; // no need for map::find()\nif (s.empty()) { // assuming we never store empty values in m\n s.assign(...);\n}\ncout << s;\n</code></pre>\n\n<p>I'm amazed at how many C++ programmers don't know this.</p>\n"}, {'answer_id': 218306, 'author': 'Jim Hunziker', 'author_id': 6160, 'author_profile': 'https://Stackoverflow.com/users/6160', 'pm_score': 4, 'selected': False, 'text': '<p>Putting functions or variables in a nameless namespace deprecates the use of <code>static</code> to restrict them to file scope.</p>\n'}, {'answer_id': 302563, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 8, 'selected': False, 'text': "<p>Most C++ programmers are familiar with the ternary operator:</p>\n\n<pre><code>x = (y < 0) ? 10 : 20;\n</code></pre>\n\n<p>However, they don't realize that it can be used as an lvalue:</p>\n\n<pre><code>(a == 0 ? a : b) = 1;\n</code></pre>\n\n<p>which is shorthand for</p>\n\n<pre><code>if (a == 0)\n a = 1;\nelse\n b = 1;\n</code></pre>\n\n<p>Use with caution :-)</p>\n"}, {'answer_id': 304187, 'author': 'Jason Baker', 'author_id': 2147, 'author_profile': 'https://Stackoverflow.com/users/2147', 'pm_score': 4, 'selected': False, 'text': '<p>Read a file into a vector of strings:</p>\n\n<pre><code> vector<string> V;\n copy(istream_iterator<string>(cin), istream_iterator<string>(),\n back_inserter(V));\n</code></pre>\n\n<p><a href="http://www.sgi.com/tech/stl/istream_iterator.html" rel="nofollow noreferrer">istream_iterator</a></p>\n'}, {'answer_id': 312426, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<blockquote>\n <p>Pointer arithmetics.</p>\n</blockquote>\n\n<p>C++ programmers prefer to avoid pointers because of the bugs that can be introduced.</p>\n\n<p>The coolest C++ I\'ve ever seen though? <a href="http://web.archive.org/web/20120110153227/http://weegen.home.xs4all.nl/eelis/analogliterals.xhtml" rel="nofollow noreferrer" title="Analog literals.">Analog literals.</a></p>\n'}, {'answer_id': 312449, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>A quite hidden feature is that you can define variables within an if condition, and its scope will span only over the if, and its else blocks:</p>\n\n<pre><code>if(int * p = getPointer()) {\n // do something\n}\n</code></pre>\n\n<p>Some macros use that, for example to provide some "locked" scope like this:</p>\n\n<pre><code>struct MutexLocker { \n MutexLocker(Mutex&);\n ~MutexLocker(); \n operator bool() const { return false; } \nprivate:\n Mutex &m;\n};\n\n#define locked(mutex) if(MutexLocker const& lock = MutexLocker(mutex)) {} else \n\nvoid someCriticalPath() {\n locked(myLocker) { /* ... */ }\n}\n</code></pre>\n\n<p>Also BOOST_FOREACH uses it under the hood. To complete this, it\'s not only possible in an if, but also in a switch:</p>\n\n<pre><code>switch(int value = getIt()) {\n // ...\n}\n</code></pre>\n\n<p>and in a while loop:</p>\n\n<pre><code>while(SomeThing t = getSomeThing()) {\n // ...\n}\n</code></pre>\n\n<p>(and also in a for condition). But i\'m not too sure whether these are all that useful :)</p>\n'}, {'answer_id': 409233, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="http://cpptruths.blogspot.com/2008/01/function-template-overload-resolution.html" rel="nofollow noreferrer">C++ Truths</a>.</p>\n\n<p>Defining functions having identical signatures in the same scope, so this is legal:</p>\n\n<pre><code>template<class T> // (a) a base template\nvoid f(T) {\n std::cout << "f(T)\\n";\n}\n\ntemplate<>\nvoid f<>(int*) { // (b) an explicit specialization\n std::cout << "f(int *) specilization\\n";\n}\n\ntemplate<class T> // (c) another, overloads (a)\nvoid f(T*) {\n std::cout << "f(T *)\\n";\n}\n\ntemplate<>\nvoid f<>(int*) { // (d) another identical explicit specialization\n std::cout << "f(int *) another specilization\\n";\n}\n</code></pre>\n'}, {'answer_id': 421854, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 1, 'selected': False, 'text': '<p>If operator delete() takes size argument in addition to *void, that means it will, highly, be a base class. That size argument render possible checking the size of the types in order to destroy the correct one. Here what <a href="http://semantics.org/commonknowledge/index.html" rel="nofollow noreferrer">Stephen Dewhurst</a> tells about this:</p>\n\n<blockquote>\n <p>Notice also that we\'ve employed a\n two-argument version of operator\n delete rather than the usual\n one-argument version. This\n two-argument version is another\n "usual" version of member operator\n delete often employed by base classes\n that expect derived classes to inherit\n their operator delete implementation.\n The second argument will contain the\n size of the object being\n deleted—information that is often\n useful in implementing custom memory\n management.</p>\n</blockquote>\n'}, {'answer_id': 421896, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 4, 'selected': False, 'text': '<p>One of the most interesting grammars of any programming languages.</p>\n\n<p>Three of these things belong together, and two are something altogether different...</p>\n\n<pre><code>SomeType t = u;\nSomeType t(u);\nSomeType t();\nSomeType t;\nSomeType t(SomeType(u));\n</code></pre>\n\n<p>All but the third and fifth define a <code>SomeType</code> object on the stack and initialize it (with <code>u</code> in the first two case, and the default constructor in the fourth. The third is declaring a function that takes no parameters and returns a <code>SomeType</code>. The fifth is similarly declaring a function that takes one parameter by value of type <code>SomeType</code> named <code>u</code>.</p>\n'}, {'answer_id': 432333, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 6, 'selected': False, 'text': "<p>One thing that's little known is that unions can be templates too:</p>\n\n<pre><code>template<typename From, typename To>\nunion union_cast {\n From from;\n To to;\n\n union_cast(From from)\n :from(from) { }\n\n To getTo() const { return to; }\n};\n</code></pre>\n\n<p>And they can have constructors and member functions too. Just nothing that has to do with inheritance (including virtual functions). </p>\n"}, {'answer_id': 456773, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 4, 'selected': False, 'text': '<p>Defining ordinary friend functions in class templates needs special attention:</p>\n\n<pre><code>template <typename T> \nclass Creator { \n friend void appear() { // a new function ::appear(), but it doesn\'t \n … // exist until Creator is instantiated \n } \n};\nCreator<void> miracle; // ::appear() is created at this point \nCreator<double> oops; // ERROR: ::appear() is created a second time! \n</code></pre>\n\n<p>In this example, two different instantiations create two identical definitions—a direct violation of the <a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="noreferrer">ODR</a> </p>\n\n<p>We must therefore make sure the template parameters of the class template appear in the type of any friend function defined in that template (unless we want to prevent more than one instantiation of a class template in a particular file, but this is rather unlikely). Let\'s apply this to a variation of our previous example:</p>\n\n<pre><code>template <typename T> \nclass Creator { \n friend void feed(Creator<T>*){ // every T generates a different \n … // function ::feed() \n } \n}; \n\nCreator<void> one; // generates ::feed(Creator<void>*) \nCreator<double> two; // generates ::feed(Creator<double>*) \n</code></pre>\n\n<p>Disclaimer: I have pasted this section from <a href="https://rads.stackoverflow.com/amzn/click/com/0201734842" rel="noreferrer" rel="nofollow noreferrer">C++ Templates: The Complete Guide</a> / Section 8.4</p>\n'}, {'answer_id': 456787, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>A dangerous secret is</p>\n\n<pre><code>Fred* f = new(ram) Fred(); http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10\nf->~Fred();\n</code></pre>\n\n<p>My favorite secret I rarely see used:</p>\n\n<pre><code>class A\n{\n};\n\nstruct B\n{\n A a;\n operator A&() { return a; }\n};\n\nvoid func(A a) { }\n\nint main()\n{\n A a, c;\n B b;\n a=c;\n func(b); //yeah baby\n a=b; //gotta love this\n}\n</code></pre>\n'}, {'answer_id': 572900, 'author': 'dirkgently', 'author_id': 66692, 'author_profile': 'https://Stackoverflow.com/users/66692', 'pm_score': 0, 'selected': False, 'text': '<pre><code>class Empty {};\n\nnamespace std {\n // #1 specializing from std namespace is okay under certain circumstances\n template<>\n void swap<Empty>(Empty&, Empty&) {} \n}\n\n/* #2 The following function has no arguments. \n There is no \'unknown argument list\' as we do\n in C.\n*/\nvoid my_function() { \n cout << "whoa! an error\\n"; // #3 using can be scoped, as it is in main below\n // and this doesn\'t affect things outside of that scope\n}\n\nint main() {\n using namespace std; /* #4 you can use using in function scopes */\n cout << sizeof(Empty) << "\\n"; /* #5 sizeof(Empty) is never 0 */\n /* #6 falling off of main without an explicit return means "return 0;" */\n}\n</code></pre>\n'}, {'answer_id': 674995, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.devx.com/cplus/10MinuteSolution/32145/0/page/1" rel="nofollow noreferrer">Indirect Conversion Idiom</a>:</p>\n\n<blockquote>\n <p>Suppose you\'re designing a smart\n pointer class. In addition to\n overloading the operators * and ->, a\n smart pointer class usually defines a\n conversion operator to bool:</p>\n</blockquote>\n\n<pre><code>template <class T>\nclass Ptr\n{\npublic:\n operator bool() const\n {\n return (rawptr ? true: false);\n }\n//..more stuff\nprivate:\n T * rawptr;\n};\n</code></pre>\n\n<blockquote>\n <p>The conversion to bool enables clients\n to use smart pointers in expressions\n that require bool operands:</p>\n</blockquote>\n\n<pre><code>Ptr<int> ptr(new int);\nif(ptr ) //calls operator bool()\n cout<<"int value is: "<<*ptr <<endl;\nelse\n cout<<"empty"<<endl;\n</code></pre>\n\n<blockquote>\n <p>Furthermore, the implicit conversion\n to bool is required in conditional\n declarations such as:</p>\n</blockquote>\n\n<pre><code>if (shared_ptr<X> px = dynamic_pointer_cast<X>(py))\n{\n //we get here only of px isn\'t empty\n} \n</code></pre>\n\n<blockquote>\n <p>Alas, this automatic conversion opens\n the gate to unwelcome surprises:</p>\n</blockquote>\n\n<pre><code>Ptr <int> p1;\nPtr <double> p2;\n\n//surprise #1\ncout<<"p1 + p2 = "<< p1+p2 <<endl; \n//prints 0, 1, or 2, although there isn\'t an overloaded operator+()\n\nPtr <File> pf;\nPtr <Query> pq; // Query and File are unrelated \n\n//surprise #2\nif(pf==pq) //compares bool values, not pointers! \n</code></pre>\n\n<p>Solution: Use the "indirect conversion" idiom, by a conversion from pointer to data member[pMember] to bool so that there will be only 1 implicit conversion, which will prevent aforementioned unexpected behaviour: pMember->bool rather that bool->something else.</p>\n'}, {'answer_id': 691496, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p>Pay attention to difference between free function pointer and member function pointer initializations:</p>\n\n<p>member function:</p>\n\n<pre><code>struct S\n{\n void func(){};\n};\nint main(){\nvoid (S::*pmf)()=&S::func;// & is mandatory\n}\n</code></pre>\n\n<p>and free function:</p>\n\n<pre><code>void func(int){}\nint main(){\nvoid (*pf)(int)=func; // & is unnecessary it can be &func as well; \n}\n</code></pre>\n\n<p>Thanks to this redundant &, you can add stream manipulators-which are free functions- in chain without it:</p>\n\n<pre><code>cout<<hex<<56; //otherwise you would have to write cout<<&hex<<56, not neat.\n</code></pre>\n'}, {'answer_id': 730018, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence">Is it possible for C++ template to check for a function’s existence?</a></p>\n'}, {'answer_id': 754133, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': -1, 'selected': False, 'text': '<p>Emulating <strong>reinterpret cast</strong> with <strong>static cast</strong> :</p>\n\n<pre><code>int var;\nstring *str = reinterpret_cast<string*>(&var);\n</code></pre>\n\n<p>the above code is equivalent to following:</p>\n\n<pre><code>int var; \nstring *str = static_cast<string*>(static_cast<void*>(&var));\n</code></pre>\n'}, {'answer_id': 876180, 'author': 'a_m0d', 'author_id': 106762, 'author_profile': 'https://Stackoverflow.com/users/106762', 'pm_score': 1, 'selected': False, 'text': "<p>The class and struct class-keys are nearly identical. The main difference is that classes default to private access for members and bases, while structs default to public:</p>\n\n<pre><code>// this is completely valid C++:\nclass A;\nstruct A { virtual ~A() = 0; };\nclass B : public A { public: virtual ~B(); };\n\n// means the exact same as:\nstruct A;\nclass A { public: virtual ~A() = 0; };\nstruct B : A { virtual ~B(); };\n\n// you can't even tell the difference from other code whether 'struct'\n// or 'class' was used for A and B\n</code></pre>\n\n<p>Unions can also have members and methods, and default to public access similarly to structs.</p>\n"}, {'answer_id': 889001, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 7, 'selected': False, 'text': '<p>Not only can variables be declared in the init part of a <code>for</code> loop, but also classes and functions. </p>\n\n<pre><code>for(struct { int a; float b; } loop = { 1, 2 }; ...; ...) {\n ...\n}\n</code></pre>\n\n<p>That allows for multiple variables of differing types.</p>\n'}, {'answer_id': 903449, 'author': 'Özgür', 'author_id': 12652, 'author_profile': 'https://Stackoverflow.com/users/12652', 'pm_score': 0, 'selected': False, 'text': '<p>Adding <a href="https://stackoverflow.com/questions/122316/template-constraints-c">constraints</a> to templates.</p>\n'}, {'answer_id': 1029069, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Primitive types have constructors.</p>\n\n<pre><code>int i(3);\n</code></pre>\n\n<p>works.</p>\n'}, {'answer_id': 1064070, 'author': 'vobject', 'author_id': 53911, 'author_profile': 'https://Stackoverflow.com/users/53911', 'pm_score': 2, 'selected': False, 'text': '<p>It seems to me that only few people know about unnamed namespaces: </p>\n\n<pre><code>namespace {\n // Classes, functions, and objects here.\n}\n</code></pre>\n\n<p>Unnamed namespaces behave as if they was replaced by:</p>\n\n<pre><code>namespace __unique_name__ { /* empty body */ }\nusing namespace __unique_name__;\nnamespace __unique_name__ {\n // original namespace body\n}\n</code></pre>\n\n<p>".. where all occurances of [this unique name] in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program." [C++03, 7.3.1.1/1]</p>\n'}, {'answer_id': 1065606, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>You can access protected data and function members of any class, without undefined behavior, and with expected semantics. Read on to see how. Read also <a href="http://tinyurl.com/defect-report" rel="nofollow noreferrer">the defect report</a> about this. </p>\n\n<p>Normally, C++ forbids you to access non-static protected members of a class\'s object, even if that class is your base class</p>\n\n<pre><code>struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // error: can\'t access protected member\n static int get(A &x) { return x.a; }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>That\'s forbidden: You and the compiler don\'t know what the reference actually points at. It could be a <code>C</code> object, in which case class <code>B</code> has no business and clue about its data. Such access is only granted if <code>x</code> is a reference to a derived class or one derived from it. And it could allow arbitrary piece of code to read any protected member by just making up a "throw-away" class that reads out members, for example of <code>std::stack</code>:</p>\n\n<pre><code>void f(std::stack<int> &s) {\n // now, let\'s decide to mess with that stack!\n struct pillager : std::stack<int> {\n static std::deque<int> &get(std::stack<int> &s) {\n // error: stack<int>::c is protected\n return s.c;\n }\n };\n\n // haha, now let\'s inspect the stack\'s middle elements!\n std::deque<int> &d = pillager::get(s);\n}\n</code></pre>\n\n<p>Surely, as you see this would cause way too much damage. But now, member pointers allow circumventing this protection! The key point is that the type of a member pointer is bound to the class that actually contains said member - <em>not</em> to the class that you specified when taking the address. This allows us to circumvent checking</p>\n\n<pre><code>struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // valid: *can* access protected member\n static int get(A &x) { return x.*(&B::a); }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>And of course, it also works with the <code>std::stack</code> example. </p>\n\n<pre><code>void f(std::stack<int> &s) {\n // now, let\'s decide to mess with that stack!\n struct pillager : std::stack<int> {\n static std::deque<int> &get(std::stack<int> &s) {\n return s.*(pillager::c);\n }\n };\n\n // haha, now let\'s inspect the stack\'s middle elements!\n std::deque<int> &d = pillager::get(s);\n}\n</code></pre>\n\n<p>That\'s going to be even easier with a using declaration in the derived class, which makes the member name public and refers to the member of the base class. </p>\n\n<pre><code>void f(std::stack<int> &s) {\n // now, let\'s decide to mess with that stack!\n struct pillager : std::stack<int> {\n using std::stack<int>::c;\n };\n\n // haha, now let\'s inspect the stack\'s middle elements!\n std::deque<int> &d = s.*(&pillager::c);\n}\n</code></pre>\n'}, {'answer_id': 1402670, 'author': 'Kamil Szot', 'author_id': 166921, 'author_profile': 'https://Stackoverflow.com/users/166921', 'pm_score': 0, 'selected': False, 'text': '<p>Member pointers and member pointer operator ->* </p>\n\n<pre><code>#include <stdio.h>\nstruct A { int d; int e() { return d; } };\nint main() {\n A* a = new A();\n a->d = 8;\n printf("%d %d\\n", a ->* &A::d, (a ->* &A::e)() );\n return 0;\n}\n</code></pre>\n\n<p>For methods (a ->* &A::e)() is a bit like Function.call() from javascript </p>\n\n<pre><code>var f = A.e\nf.call(a) \n</code></pre>\n\n<p>For members it\'s a bit like accessing with [] operator </p>\n\n<pre><code>a[\'d\']\n</code></pre>\n'}, {'answer_id': 1414869, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>Many know of the <code>identity</code> / <code>id</code> metafunction, but there is a nice usecase for it for non-template cases: Ease writing declarations:</p>\n\n<pre><code>// void (*f)(); // same\nid<void()>::type *f;\n\n// void (*f(void(*p)()))(int); // same\nid<void(int)>::type *f(id<void()>::type *p);\n\n// int (*p)[2] = new int[10][2]; // same\nid<int[2]>::type *p = new int[10][2];\n\n// void (C::*p)(int) = 0; // same\nid<void(int)>::type C::*p = 0;\n</code></pre>\n\n<p>It helps decrypting C++ declarations greatly!</p>\n\n<pre><code>// boost::identity is pretty much the same\ntemplate<typename T> \nstruct id { typedef T type; };\n</code></pre>\n'}, {'answer_id': 1465581, 'author': 'sdcvvc', 'author_id': 100020, 'author_profile': 'https://Stackoverflow.com/users/100020', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.reddit.com/r/programming/comments/96aku/in_c_throw_is_an_expression/" rel="nofollow noreferrer">throw is an expression</a></p>\n'}, {'answer_id': 1573354, 'author': 'Macke', 'author_id': 72312, 'author_profile': 'https://Stackoverflow.com/users/72312', 'pm_score': 1, 'selected': False, 'text': "<p>I find recursive template instatiations pretty cool:</p>\n\n<pre><code>template<class int>\nclass foo;\n\ntemplate\nclass foo<0> {\n int* get<0>() { return array; }\n int* array; \n};\n\ntemplate<class int>\nclass foo<i> : public foo<i-1> {\n int* get<i>() { return array + 1; } \n};\n</code></pre>\n\n<p>I've used that to generate a class with 10-15 functions that return pointers into various parts of an array, since an API I used required one function pointer for each value.</p>\n\n<p>I.e. programming the compiler to generate a bunch of functions, via recursion. Easy as pie. :)</p>\n"}, {'answer_id': 1771776, 'author': 'Jeffrey Faust', 'author_id': 215580, 'author_profile': 'https://Stackoverflow.com/users/215580', 'pm_score': 2, 'selected': False, 'text': '<p>main() does not need a return value:</p>\n\n<pre><code>int main(){}\n</code></pre>\n\n<p>is the shortest valid C++ program.</p>\n'}, {'answer_id': 1771843, 'author': 'Kaz Dragon', 'author_id': 24913, 'author_profile': 'https://Stackoverflow.com/users/24913', 'pm_score': 4, 'selected': False, 'text': '<p>You can template bitfields.</p>\n\n<pre><code>template <size_t X, size_t Y>\nstruct bitfield\n{\n char left : X;\n char right : Y;\n};\n</code></pre>\n\n<p>I have yet to come up with any purpose for this, but it sure as heck surprised me.</p>\n'}, {'answer_id': 1966865, 'author': 'Rune FS', 'author_id': 112407, 'author_profile': 'https://Stackoverflow.com/users/112407', 'pm_score': 0, 'selected': False, 'text': "<p>My favorite (for the time being) is the lack of sematics in a statement like \nA=B=C. What the value of A is basically undetermined.</p>\n\n<p>Think of this:</p>\n\n<pre><code>class clC\n{\npublic:\n clC& operator=(const clC& other)\n {\n //do some assignment stuff\n return copy(other);\n }\n virtual clC& copy(const clC& other);\n}\n\nclass clB : public clC\n{\npublic:\n clB() : m_copy()\n {\n }\n\n clC& copy(const clC& other)\n {\n return m_copy;\n }\n\nprivate:\n class clInnerB : public clC\n {\n }\n clInnerB m_copy;\n}\n</code></pre>\n\n<p>now A might be of a type inaccessible to any other than objects of type clB and have a value that's unrelated to C.</p>\n"}, {'answer_id': 2176229, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 4, 'selected': False, 'text': '<h3>void functions can return void values</h3>\n\n<p>Little known, but the following code is fine</p>\n\n<pre><code>void f() { }\nvoid g() { return f(); }\n</code></pre>\n\n<p>Aswell as the following weird looking one</p>\n\n<pre><code>void f() { return (void)"i\'m discarded"; }\n</code></pre>\n\n<p>Knowing about this, you can take advantage in some areas. One example: <code>void</code> functions can\'t return a value but you can also not just return nothing, because they may be instantiated with non-void. Instead of storing the value into a local variable, which will cause an error for <code>void</code>, just return a value directly</p>\n\n<pre><code>template<typename T>\nstruct sample {\n // assume f<T> may return void\n T dosomething() { return f<T>(); }\n\n // better than T t = f<T>(); /* ... */ return t; !\n};\n</code></pre>\n'}, {'answer_id': 2176258, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': "<h3>Preventing comma operator from calling operator overloads</h3>\n\n<p>Sometimes you make valid use of the comma operator, but you want to ensure that no user defined comma operator gets into the way, because for instance you rely on sequence points between the left and right side or want to make sure nothing interferes with the desired action. This is where <code>void()</code> comes into game:</p>\n\n<pre><code>for(T i, j; can_continue(i, j); ++i, void(), ++j)\n do_code(i, j);\n</code></pre>\n\n<p>Ignore the place holders i put for the condition and code. What's important is the <code>void()</code>, which makes the compiler force to use the builtin comma operator. This can be useful when implementing traits classes, sometimes, too. </p>\n"}, {'answer_id': 2339965, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can view all the predefined macros through command-line switches with some compilers. This works with gcc and icc (Intel\'s C++ compiler):</p>\n\n<pre><code>$ touch empty.cpp\n$ g++ -E -dM empty.cpp | sort >gxx-macros.txt\n$ icc -E -dM empty.cpp | sort >icx-macros.txt\n$ touch empty.c\n$ gcc -E -dM empty.c | sort >gcc-macros.txt\n$ icc -E -dM empty.c | sort >icc-macros.txt\n</code></pre>\n\n<p>For MSVC they are listed in a <a href="http://msdn.microsoft.com/en-us/library/b0084kay%28VS.80%29.aspx" rel="nofollow noreferrer">single place</a>. They could be documented in a single place for the others too, but with the above commands you can clearly <em>see</em> what is and isn\'t defined and exactly what values are used, after applying all of the other command-line switches.</p>\n\n<p>Compare (after sorting):</p>\n\n<pre><code> $ diff gxx-macros.txt icx-macros.txt\n $ diff gxx-macros.txt gcc-macros.txt\n $ diff icx-macros.txt icc-macros.txt\n</code></pre>\n'}, {'answer_id': 2339999, 'author': 'AnT stands with Russia', 'author_id': 187690, 'author_profile': 'https://Stackoverflow.com/users/187690', 'pm_score': 4, 'selected': False, 'text': '<p>The ternary conditional operator <code>?:</code> requires its second and third operand to have "agreeable" types (speaking informally). But this requirement has one exception (pun intended): either the second or third operand can be a throw expression (which has type <code>void</code>), regardless of the type of the other operand.</p>\n\n<p>In other words, one can write the following pefrectly valid C++ expressions using the <code>?:</code> operator</p>\n\n<pre><code>i = a > b ? a : throw something();\n</code></pre>\n\n<p>BTW, the fact that throw expression is actually <em>an expression</em> (of type <code>void</code>) and not a statement is another little-known feature of C++ language. This means, among other things, that the following code is perfectly valid</p>\n\n<pre><code>void foo()\n{\n return throw something();\n}\n</code></pre>\n\n<p>although there\'s not much point in doing it this way (maybe in some generic template code this might come handy).</p>\n'}, {'answer_id': 2340305, 'author': 'Viktor Sehr', 'author_id': 100724, 'author_profile': 'https://Stackoverflow.com/users/100724', 'pm_score': 2, 'selected': False, 'text': "<ol>\n<li><p><code>map::insert(std::pair(key, value));</code> doesn't overwrite if key value already exists. </p></li>\n<li><p>You can instantiate a class right after its definition:\n(I might add that this feature has given me hundreds of compilation errors because of the missing semicolon, and I've never ever seen anyone use this on classes)</p>\n\n<pre><code>class MyClass {public: /* code */} myClass;\n</code></pre></li>\n</ol>\n"}, {'answer_id': 2340449, 'author': 'aheld', 'author_id': 259873, 'author_profile': 'https://Stackoverflow.com/users/259873', 'pm_score': -1, 'selected': False, 'text': '<p>I know somebody who defines a getter and a setter at the same time with only one method. Like this:</p>\n\n<pre><code>class foo\n{\n int x;\n\n int* GetX(){\n return &x;\n }\n}\n</code></pre>\n\n<p>You can now use this as a getter as usual (well, almost):</p>\n\n<pre><code>int a = *GetX();\n</code></pre>\n\n<p>and as a setter:</p>\n\n<pre><code>*GetX() = 17;\n</code></pre>\n'}, {'answer_id': 2520439, 'author': 'osgx', 'author_id': 196561, 'author_profile': 'https://Stackoverflow.com/users/196561', 'pm_score': -1, 'selected': False, 'text': '<p>Template metaprogramming is.</p>\n'}, {'answer_id': 2912402, 'author': 'mihai', 'author_id': 350838, 'author_profile': 'https://Stackoverflow.com/users/350838', 'pm_score': -1, 'selected': False, 'text': '<p>Not actually a hidden feature, but pure awesomeness:</p>\n\n<pre><code>#define private public \n</code></pre>\n'}, {'answer_id': 3056080, 'author': 'Martín Fixman', 'author_id': 305597, 'author_profile': 'https://Stackoverflow.com/users/305597', 'pm_score': -1, 'selected': False, 'text': '<p>You can return a variable reference as part of a function. It has some uses, mostly for producing horrible code:</p>\n\n<pre><code>int s ;\nvector <int> a ;\nvector <int> b ;\n\nint &G(int h)\n{\n if ( h < a.size() ) return a[h] ;\n if ( h - a.size() < b.size() ) return b[ h - a.size() ] ;\n return s ;\n}\n\nint main()\n{\n a = vector <int> (100) ;\n b = vector <int> (100) ;\n\n G( 20) = 40 ; //a[20] becomes 40\n G(120) = 40 ; //b[20] becomes 40\n G(424) = 40 ; //s becomes 40\n}\n</code></pre>\n'}, {'answer_id': 3100801, 'author': 'Alexandre C.', 'author_id': 373025, 'author_profile': 'https://Stackoverflow.com/users/373025', 'pm_score': 3, 'selected': False, 'text': "<p>Local classes are awesome :</p>\n\n<pre><code>struct MyAwesomeAbstractClass\n{ ... };\n\n\ntemplate <typename T>\nMyAwesomeAbstractClass*\ncreate_awesome(T param)\n{\n struct ans : MyAwesomeAbstractClass\n {\n // Make the implementation depend on T\n };\n\n return new ans(...);\n}\n</code></pre>\n\n<p>quite neat, since it doesn't pollute the namespace with useless class definitions...</p>\n"}, {'answer_id': 3176148, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 3, 'selected': False, 'text': '<p>One hidden feature, even hidden to the <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43453" rel="nofollow noreferrer">GCC developers</a>, is to initialize an array member using a string literal. Suppose you have a structure that needs to work with a C array, and you want to initialize the array member with a default content</p>\n\n<pre><code>struct Person {\n char name[255];\n Person():name("???") { }\n};\n</code></pre>\n\n<p>This works, and only works with char arrays and string literal initializers. No <code>strcpy</code> is needed!</p>\n'}, {'answer_id': 3176186, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 5, 'selected': False, 'text': '<p>Another hidden feature is that you can call class objects that can be converted to function pointers or references. Overload resolution is done on the result of them, and arguments are perfectly forwarded.</p>\n\n<pre><code>template<typename Func1, typename Func2>\nclass callable {\n Func1 *m_f1;\n Func2 *m_f2;\n\npublic:\n callable(Func1 *f1, Func2 *f2):m_f1(f1), m_f2(f2) { }\n operator Func1*() { return m_f1; }\n operator Func2*() { return m_f2; }\n};\n\nvoid foo(int i) { std::cout << "foo: " << i << std::endl; }\nvoid bar(long il) { std::cout << "bar: " << il << std::endl; }\n\nint main() {\n callable<void(int), void(long)> c(foo, bar);\n c(42); // calls foo\n c(42L); // calls bar\n}\n</code></pre>\n\n<p>These are called "surrogate call functions". </p>\n'}, {'answer_id': 3182557, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 6, 'selected': False, 'text': '<p>Another hidden feature that doesn\'t work in C is the functionality of the unary <code>+</code> operator. You can use it to promote and decay all sorts of things</p>\n\n<h3>Converting an Enumeration to an integer</h3>\n\n<pre><code>+AnEnumeratorValue\n</code></pre>\n\n<p>And your enumerator value that previously had its enumeration type now has the perfect integer type that can fit its value. Manually, you would hardly know that type! This is needed for example when you want to implement an overloaded operator for your enumeration. </p>\n\n<h3>Get the value out of a variable</h3>\n\n<p>You have to use a class that uses an in-class static initializer without an out of class definition, but sometimes it fails to link? The operator may help to create a temporary without making assumptins or dependencies on its type</p>\n\n<pre><code>struct Foo {\n static int const value = 42;\n};\n\n// This does something interesting...\ntemplate<typename T>\nvoid f(T const&);\n\nint main() {\n // fails to link - tries to get the address of "Foo::value"!\n f(Foo::value);\n\n // works - pass a temporary value\n f(+Foo::value);\n}\n</code></pre>\n\n<h3>Decay an array to a pointer</h3>\n\n<p>Do you want to pass two pointers to a function, but it just won\'t work? The operator may help</p>\n\n<pre><code>// This does something interesting...\ntemplate<typename T>\nvoid f(T const& a, T const& b);\n\nint main() {\n int a[2];\n int b[3];\n f(a, b); // won\'t work! different values for "T"!\n f(+a, +b); // works! T is "int*" both time\n}\n</code></pre>\n'}, {'answer_id': 3189052, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 4, 'selected': False, 'text': '<p>The dominance rule is useful, but little known. It says that even if in a non-unique path through a base-class lattice, name-lookup for a partially hidden member is unique if the member belongs to a virtual base-class:</p>\n\n<pre><code>struct A { void f() { } };\n\nstruct B : virtual A { void f() { cout << "B!"; } };\nstruct C : virtual A { };\n\n// name-lookup sees B::f and A::f, but B::f dominates over A::f !\nstruct D : B, C { void g() { f(); } };\n</code></pre>\n\n<p>I\'ve used this to <a href="https://stackoverflow.com/questions/2366879/operator-new-overloading-and-alignment/2366998#2366998">implement alignment-support</a> that automatically figures out the strictest alignment by means of the dominance rule. </p>\n\n<p><em>This does not only apply to virtual functions, but also to typedef names, static/non-virtual members and anything else.</em> I\'ve seen it used to implement overwritable traits in meta-programs. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2328/'] |
75,546 | <p>I am developing a .NET WinForms application which relies on user.config to store various useful settings such as intranet web service URLs. We would like to make it possible to import custom initial settings as part of the installation. The use case for this is if a company has 100 machines they want to install the software on, and they should all have a reference to the intranet web service in question, this should not need to be set up manually on all the machines.</p>
<p>We are currently using a VS2008 setup project to generate the install package.</p>
<p>Our idea so far has been to enable the installer to make a custom initial .config file with the information (from a template), and then put that in place instead of the default one that the setup project installs.</p>
<p>However, I can't see a way to do this other than these few:</p>
<ol>
<li>Hardcode the executable name into a custom installer action (deriving from System.Configuration.Install.Installer), in order to use the ConfigurationManager class to determine the .config file path. This would require manual changes to the installer if the executable name changes.</li>
<li>Roll our own configuration classes or file/folder hierarchy to store the settings. This would basically bar us from the advantages of the isolation mechanism (which is also the obstacle here) that .NET provides, if I understand correctly.</li>
</ol>
<p>Does anyone know of any alternatives, or of ways to make the above two palatable?</p>
<p>I fear the answer may be "don't do this, it defeats the spirit of the mechanism, roll your own settings import mechanism".</p>
| [{'answer_id': 77385, 'author': 'Shachar', 'author_id': 13897, 'author_profile': 'https://Stackoverflow.com/users/13897', 'pm_score': 1, 'selected': False, 'text': '<p>I know that\'s not exactly the answer you\'re looking for, but you should opt for a more "serious" installer. We\'re using Advanced Installer and it\'s a blast, does anything and everything you can think of.</p>\n'}, {'answer_id': 156816, 'author': 'Veldmuis', 'author_id': 18826, 'author_profile': 'https://Stackoverflow.com/users/18826', 'pm_score': 0, 'selected': False, 'text': '<p>If it is acceptable for you to hardcode at least one setting in the config file, you can use this to point to a database or web service or network file path where all the custom config settings can be stored. Using System.Configuration.ConfigurationManager.OpenExeConfiguration() you can then update the config file from this location either on the first run or every time that the application starts up.</p>\n'}, {'answer_id': 163763, 'author': 'KovBal', 'author_id': 19998, 'author_profile': 'https://Stackoverflow.com/users/19998', 'pm_score': 2, 'selected': False, 'text': '<p>If you create this application for larger companies, then you should have a look at <a href="http://technet.microsoft.com/en-us/windowsserver/grouppolicy/default.aspx" rel="nofollow noreferrer">Group Policy</a>. Unfortunately, it\'ll bring your application back to the golden age of registry. I understand, that this would be a huge change in your program, but this is the way to this.</p>\n\n<p>However, if the web service\'s URL is the only thing, you have to setup this way, then GPO might be an overkill. In that case I would hardcode the executable\'s name.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2729/'] |
75,608 | <p>I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries.</p>
<p>I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method.</p>
<p>Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.</p>
| [{'answer_id': 75651, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 0, 'selected': False, 'text': '<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataSet and call ReadXML on it.</p>\n'}, {'answer_id': 75681, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>You want to create an <code>SqlCeDataAdapter</code> and use it <code>.Fill()</code> a dataset. Then serialize the entire dataset via it's <code>.WriteXml()</code> method.</p>\n"}, {'answer_id': 75702, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': True, 'text': '<p>Assuming cmd is your SqlCeCommand....</p>\n\n<pre><code>using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5287/'] |
75,614 | <p>The following question answers how to get large memory pages on Windows :<br>
"<a href="https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows">how do i run my app with large pages in windows</a>".</p>
<p>The problem I'm trying to solve is how do I configure it on Vista and 2008 Server.</p>
<p>Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing.</p>
<p>Anyone have a clue as to what else needs to be configured?</p>
<p>Thanks,
Staffan</p>
| [{'answer_id': 75651, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 0, 'selected': False, 'text': '<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataSet and call ReadXML on it.</p>\n'}, {'answer_id': 75681, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>You want to create an <code>SqlCeDataAdapter</code> and use it <code>.Fill()</code> a dataset. Then serialize the entire dataset via it's <code>.WriteXml()</code> method.</p>\n"}, {'answer_id': 75702, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': True, 'text': '<p>Assuming cmd is your SqlCeCommand....</p>\n\n<pre><code>using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8782/'] |
75,621 | <p>I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned_data field unless I call <code>is_valid()</code>. But <code>is_valid()</code> always fails on unbound forms.</p>
<p>It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML.</p>
<p>For example, if I have:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>is_valid() will fail if this is a GET (since it's unbound), and if I do:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>the first call to do_query triggers exceptions on form.cleaned_data, which is not a valid field because <code>is_valid()</code> has not been called. It seems like I have to do something like:</p>
<pre><code>if request.method == 'GET':
form = MyForm()
do_query(form['start_date'].field.initial, form['end_date'].field.initial)
else:
form = MyForm(request.method.POST)
if form.is_valid():
do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])
</code></pre>
<p>that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one.</p>
<p>Does anyone see a cleaner way to do this?</p>
| [{'answer_id': 75815, 'author': 'Justin Voss', 'author_id': 5616, 'author_profile': 'https://Stackoverflow.com/users/5616', 'pm_score': 0, 'selected': False, 'text': '<p>You can pass a dictionary of initial values to your form:</p>\n\n<pre><code>if request.method == "GET":\n # calculate my_start_date and my_end_date here...\n form = MyForm( { \'start_date\': my_start_date, \'end_date\': my_end_date} )\n...\n</code></pre>\n\n<p>See the <a href="http://docs.djangoproject.com/en/dev/ref/forms/api/" rel="nofollow noreferrer">official forms API documentation</a>, where they demonstrate this.</p>\n\n<p><strong>edit</strong>: Based on answers from other users, maybe this is the cleanest solution:</p>\n\n<pre><code>if request.method == "GET":\n form = MyForm()\n form[\'start_date\'] = form[\'start_date\'].field.initial\n form[\'end_date\'] = form[\'end_date\'].field.initial\nelse:\n form = MyForm(request.method.POST)\nif form.is_valid():\n do_query(form.cleaned_data[\'start_date\'], form.cleaned_data[\'end_date\'])\n</code></pre>\n\n<p>I haven\'t tried this though; can someone confirm that this works? I think this is better than creating a new method, because this approach doesn\'t require other code (possibly not written by you) to know about your new \'magic\' accessor.</p>\n'}, {'answer_id': 75923, 'author': 'Matthew Christensen', 'author_id': 2123, 'author_profile': 'https://Stackoverflow.com/users/2123', 'pm_score': 4, 'selected': True, 'text': "<p>If you add this method to your form class:</p>\n\n<pre><code>def get_cleaned_or_initial(self, fieldname):\n if hasattr(self, 'cleaned_data'):\n return self.cleaned_data.get(fieldname)\n else:\n return self[fieldname].field.initial\n</code></pre>\n\n<p>you could then re-write your code as:</p>\n\n<pre><code>if request.method == 'GET':\n form = MyForm()\nelse:\n form = MyForm(request.method.POST)\n form.is_valid()\n\ndo_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date'))\n</code></pre>\n"}, {'answer_id': 81301, 'author': 'zgoda', 'author_id': 12138, 'author_profile': 'https://Stackoverflow.com/users/12138', 'pm_score': 2, 'selected': False, 'text': '<p><em>Unbound</em> means there is no data associated with form (either initial or provided later), so the validation may fail. As mentioned in other answers (and in your own conclusion), you have to provide initial values and check for both bound data and initial values.</p>\n\n<p>The use case for forms is form processing <strong>and</strong> validation, so you must have some data to validate before you accessing <code>cleaned_data</code>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8247/'] |
75,626 | <p>I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. </p>
<p>For example I would like to accomplish this: </p>
<pre><code><%@ taglib prefix="wf" uri="JspCustomTag" %>
<%
Object myObject = new Object();
%>
<wf:my-tag obj=myObject />
</code></pre>
<p>I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.</p>
| [{'answer_id': 75745, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 0, 'selected': False, 'text': '<p>Use expression language:</p>\n\n<pre>\n <wf:my-tag obj="${myObject}" />\n</pre>\n'}, {'answer_id': 75843, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 3, 'selected': False, 'text': '<p>The original syntax was to reuse \'<%= %>\'</p>\n\n<p>So</p>\n\n<pre><code><wf:my-tag obj="<%= myObject %>" />\n</code></pre>\n\n<p>See <a href="http://java.sun.com/products/jsp/tutorial/TagLibraries16.html#62510" rel="noreferrer">this part of the Sun Tag Library Tutorial</a> for an example</p>\n'}, {'answer_id': 76187, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 2, 'selected': False, 'text': '<p>For me expression language works only if I make that variable accessible, by putting it for example in page context.</p>\n\n<pre><code><% Object myObject = new Object();\n pageContext.setAttribute("myObject", myObject);\n%>\n<wf:my-tag obj="${myObject}" />\n</code></pre>\n\n<p>Otherwise tas receives null.</p>\n\n<p>And <code><wf:my-tag obj="<%= myObject %>" /></code> works with no additional effort. Also <%=%> gives jsp compile-time type validation, while El is validated only in runtime.</p>\n'}, {'answer_id': 355242, 'author': 'Adeel Ansari', 'author_id': 42769, 'author_profile': 'https://Stackoverflow.com/users/42769', 'pm_score': 4, 'selected': False, 'text': '<pre><code><jsp:useBean id="myObject" class="java.lang.Object" scope="page" />\n<wf:my-tag obj="${myObject}" />\n</code></pre>\n\n<p>Its not encouraged to use Scriptlets in JSP page. It kills the purpose of a template language.</p>\n'}, {'answer_id': 1228031, 'author': 'dfrankow', 'author_id': 34935, 'author_profile': 'https://Stackoverflow.com/users/34935', 'pm_score': 5, 'selected': False, 'text': '<p>A slightly different question that I looked for here: "How do you pass an object to a tag file?"</p>\n\n<p>Answer: Use the "type" attribute of the attribute directive:</p>\n\n<pre><code><%@ attribute name="field" \n required="true"\n type="com.mycompany.MyClass" %>\n</code></pre>\n\n<p>The type <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854" rel="noreferrer">defaults to java.lang.String</a>, so without it you\'ll get an error if you try to access object fields saying that it can\'t find the field from type String.</p>\n'}, {'answer_id': 27396614, 'author': 'Mike Clark', 'author_id': 4261022, 'author_profile': 'https://Stackoverflow.com/users/4261022', 'pm_score': 1, 'selected': False, 'text': '<p>You can use "<%= %>" to get the object value directly in your tag :</p>\n\n<pre><code> <wf:my-tag obj="<%= myObject %>"/>\n</code></pre>\n\n<p>and to get the value of any variable within that object you can get that using "obj.parameter" like:</p>\n\n<pre><code><wf:my-tag obj="<%= myObject.variableName %>"/>\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13393/'] |
75,650 | <p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p>
<p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p>
<p>A couple of questions:</p>
<ul>
<li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li>
<li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li>
</ul>
<p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p>
<p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
| [{'answer_id': 75745, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 0, 'selected': False, 'text': '<p>Use expression language:</p>\n\n<pre>\n <wf:my-tag obj="${myObject}" />\n</pre>\n'}, {'answer_id': 75843, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 3, 'selected': False, 'text': '<p>The original syntax was to reuse \'<%= %>\'</p>\n\n<p>So</p>\n\n<pre><code><wf:my-tag obj="<%= myObject %>" />\n</code></pre>\n\n<p>See <a href="http://java.sun.com/products/jsp/tutorial/TagLibraries16.html#62510" rel="noreferrer">this part of the Sun Tag Library Tutorial</a> for an example</p>\n'}, {'answer_id': 76187, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 2, 'selected': False, 'text': '<p>For me expression language works only if I make that variable accessible, by putting it for example in page context.</p>\n\n<pre><code><% Object myObject = new Object();\n pageContext.setAttribute("myObject", myObject);\n%>\n<wf:my-tag obj="${myObject}" />\n</code></pre>\n\n<p>Otherwise tas receives null.</p>\n\n<p>And <code><wf:my-tag obj="<%= myObject %>" /></code> works with no additional effort. Also <%=%> gives jsp compile-time type validation, while El is validated only in runtime.</p>\n'}, {'answer_id': 355242, 'author': 'Adeel Ansari', 'author_id': 42769, 'author_profile': 'https://Stackoverflow.com/users/42769', 'pm_score': 4, 'selected': False, 'text': '<pre><code><jsp:useBean id="myObject" class="java.lang.Object" scope="page" />\n<wf:my-tag obj="${myObject}" />\n</code></pre>\n\n<p>Its not encouraged to use Scriptlets in JSP page. It kills the purpose of a template language.</p>\n'}, {'answer_id': 1228031, 'author': 'dfrankow', 'author_id': 34935, 'author_profile': 'https://Stackoverflow.com/users/34935', 'pm_score': 5, 'selected': False, 'text': '<p>A slightly different question that I looked for here: "How do you pass an object to a tag file?"</p>\n\n<p>Answer: Use the "type" attribute of the attribute directive:</p>\n\n<pre><code><%@ attribute name="field" \n required="true"\n type="com.mycompany.MyClass" %>\n</code></pre>\n\n<p>The type <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854" rel="noreferrer">defaults to java.lang.String</a>, so without it you\'ll get an error if you try to access object fields saying that it can\'t find the field from type String.</p>\n'}, {'answer_id': 27396614, 'author': 'Mike Clark', 'author_id': 4261022, 'author_profile': 'https://Stackoverflow.com/users/4261022', 'pm_score': 1, 'selected': False, 'text': '<p>You can use "<%= %>" to get the object value directly in your tag :</p>\n\n<pre><code> <wf:my-tag obj="<%= myObject %>"/>\n</code></pre>\n\n<p>and to get the value of any variable within that object you can get that using "obj.parameter" like:</p>\n\n<pre><code><wf:my-tag obj="<%= myObject.variableName %>"/>\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3957/'] |
75,652 | <p>or "How do I answer questions on SO in Firefox using gVim inside the textboxes?"</p>
| [{'answer_id': 75664, 'author': 'zigdon', 'author_id': 4913, 'author_profile': 'https://Stackoverflow.com/users/4913', 'pm_score': 2, 'selected': False, 'text': '<p>One way to do this is to use the <a href="http://vimperator.mozdev.org/" rel="nofollow noreferrer">vimperator</a> extension - of course, that does a <em>lot</em> more than what you\'re looking for.</p>\n'}, {'answer_id': 75665, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 7, 'selected': True, 'text': '<p><a href="https://addons.mozilla.org/en-US/firefox/addon/4125" rel="noreferrer">It\'s All Text!</a></p>\n\n<p>From the extension page:</p>\n\n<blockquote>\n <p>At the bottom right corner of any edit\n box, a little edit button will appear.\n Click it. If this is the first time\n you\'ve used "It\'s All Text!" then you\n will be asked to set your preferences,\n most importantly the editor.</p>\n \n <p>The web page will pop up in your\n selected editor. When you save it,\n it\'ll refresh in the web page. Wait\n for the magic yellow glow that means\n that the radiation has taken effect!</p>\n</blockquote>\n'}, {'answer_id': 75670, 'author': 'Erik Forsberg', 'author_id': 8675, 'author_profile': 'https://Stackoverflow.com/users/8675', 'pm_score': 2, 'selected': False, 'text': '<p>The "It\'s all Text" extension, perhaps?</p>\n\n<p><a href="http://addons.mozilla.org/en-US/firefox/addon/4125" rel="nofollow noreferrer">http://addons.mozilla.org/en-US/firefox/addon/4125</a></p>\n'}, {'answer_id': 75672, 'author': 'Jason Terk', 'author_id': 12582, 'author_profile': 'https://Stackoverflow.com/users/12582', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://vimperator.mozdev.org/" rel="noreferrer">Vimperator</a> makes Firefox act very much like VIM:</p>\n\n<blockquote>\n <p>Vimperator is a free browser add-on for Firefox, which makes it look and behave like the Vim text editor. It has similar key bindings, and you could call it a modal web browser, as key bindings differ according to which mode you are in.</p>\n</blockquote>\n\n<p>Once you have the cursor in a text box, hit <kbd>Ctrl</kbd>-<kbd>I</kbd> to open in your editor, which defaults to gvim.</p>\n'}, {'answer_id': 75686, 'author': 'Clinton Dreisbach', 'author_id': 6262, 'author_profile': 'https://Stackoverflow.com/users/6262', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://addons.mozilla.org/en-US/firefox/addon/4125" rel="noreferrer">It\'s All Text!</a> will let you use whatever editor you want. To use vim with it, you\'ll need a small shell script to open it in a terminal:</p>\n\n<pre><code>#!/bin/sh\nexec xterm -e /usr/bin/vim "$@"\n</code></pre>\n\n<p>If you have GVim, you won\'t need the shell, script, obviously.</p>\n'}, {'answer_id': 75994, 'author': 'erichui', 'author_id': 6034, 'author_profile': 'https://Stackoverflow.com/users/6034', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://addons.mozilla.org/en-US/firefox/addon/394" rel="nofollow noreferrer">ViewSourceWith</a> is another addon worth lookng at. It supports more than just edit boxes and text. For example, you can configure it to open images in the GIMP.</p>\n\n<p>Another feature that I find useful is that it can pop-up a dialog box that shows all the js and css scripts used on the page. You can then choose to view/edit file in your preferred editor.</p>\n\n<p>For answering questions on SO, you may also want to get the <a href="http://www.vim.org/scripts/script.php?script_id=1242" rel="nofollow noreferrer">Vim Markdown Syntax file</a></p>\n'}, {'answer_id': 89807, 'author': 'Swaroop C H', 'author_id': 4869, 'author_profile': 'https://Stackoverflow.com/users/4869', 'pm_score': 1, 'selected': False, 'text': '<p>You can also use the <a href="https://addons.mozilla.org/en-US/firefox/addon/394" rel="nofollow noreferrer">ViewSourceWith</a> addon to achieve the same. Just right-click on any text input and you can edit it using Vim.</p>\n'}, {'answer_id': 652203, 'author': 'sotto', 'author_id': 45388, 'author_profile': 'https://Stackoverflow.com/users/45388', 'pm_score': 1, 'selected': False, 'text': "<p>As said by others,\nas a Vi/(g)Vim user you'll probably want to look at the Vimperator addon, which also provides the what you ask: \ninside a textbox, hit <C-i> to launch the external editor.\n(can be defined in _vimperatorrc: set editor=gvim -f )</p>\n"}, {'answer_id': 826143, 'author': 'Hamish Downer', 'author_id': 3189, 'author_profile': 'https://Stackoverflow.com/users/3189', 'pm_score': 2, 'selected': False, 'text': '<p>At the time of writing it is experimental, but the <a href="https://addons.mozilla.org/en-US/firefox/addon/8529" rel="nofollow noreferrer">jV extension</a> looks good. To quote from the page:</p>\n\n<p><em>This extension makes all html textareas into a very stripped-down version of Vi[m]. It\'s modal, supports infinite undo, has register support, search, visual mode, and various movement and editing commands.</em></p>\n'}, {'answer_id': 830078, 'author': 'Hamish Downer', 'author_id': 3189, 'author_profile': 'https://Stackoverflow.com/users/3189', 'pm_score': 2, 'selected': False, 'text': '<p>If you use <a href="http://vimperator.mozdev.org/" rel="nofollow noreferrer">vimperator</a> and have the <a href="http://www.vim.org/scripts/script.php?script_id=1242" rel="nofollow noreferrer">markdown syntax file</a> installed, a useful line for your .vimperatorrc is: </p>\n\n<pre><code>au LocationChange .* :set editor="gvim -f"\nau LocationChange stackoverflow\\.com :set editor="gvim -f -c \'set ft=mkd\'"\n</code></pre>\n\n<p>This will tell vim to do syntax highlighting for markdown when you are on stackoverflow.com, but not when you are any other site. There are similar hacks for wikipedia/mediawiki etc. Enjoy :)</p>\n'}, {'answer_id': 831757, 'author': 'Hamish Downer', 'author_id': 3189, 'author_profile': 'https://Stackoverflow.com/users/3189', 'pm_score': 2, 'selected': False, 'text': '<p>There is an experimental way to directly embed the real vim in firefox using <a href="http://people.ksp.sk/~martin/firefox/extensions/EmbeddedEditor/" rel="nofollow noreferrer">embedded editor</a> - though it requires mozplugger and will only work on Linux.</p>\n'}, {'answer_id': 837650, 'author': 'Simon Hartcher', 'author_id': 459159, 'author_profile': 'https://Stackoverflow.com/users/459159', 'pm_score': 2, 'selected': False, 'text': '<p>When using Vimperator in Windows (I am using Vista) you may need to double-escape the path to gvim.exe to use it as the external editor. Single escaping did not work for me as Vimperator unescapes it twice. Eg:</p>\n\n<pre><code>:set editor="C:\\\\\\\\Program\\\\ Files\\\\ (x86)\\\\\\\\Vim\\\\\\\\vim72\\\\\\\\gvim.exe" -f\n</code></pre>\n\n<p>Then while in a text box you use Ctrl+I and it will open gvim for editing. When you save and exit it will update the text box.</p>\n'}, {'answer_id': 2450051, 'author': 'Nick Edwards', 'author_id': 291838, 'author_profile': 'https://Stackoverflow.com/users/291838', 'pm_score': 1, 'selected': False, 'text': '<p>A hint for Mac users: if you want to use "It\'s all text" with vim, the easiest way is to use <a href="http://code.google.com/p/macvim/" rel="nofollow noreferrer">http://code.google.com/p/macvim/</a> . Point "It\'s all text" to the mvim script that\'s provided along with the .app (you can place this script anywhere, I choose /usr/bin/ so that I can load mvim from the command line)</p>\n'}, {'answer_id': 17477562, 'author': 'lydell', 'author_id': 2010616, 'author_profile': 'https://Stackoverflow.com/users/2010616', 'pm_score': 2, 'selected': False, 'text': '<p>Try out the wasavi extension. You might want to check out the all versions page to make sure you try out the latest version. (Copy of <a href="https://superuser.com/questions/527895/edit-text-areas-using-vi-key-bindings-inside-the-textbox-in-firefox-without-o/615678#615678">this answer</a>.)</p>\n'}, {'answer_id': 26480852, 'author': 'pfrenssen', 'author_id': 350644, 'author_profile': 'https://Stackoverflow.com/users/350644', 'pm_score': 1, 'selected': False, 'text': '<p><a href="https://github.com/ardagnir/pterosaur" rel="nofollow">Pterosaur</a> is a Firefox plugin that allows you to use Vim in all input fields. It uses an actual Vim process in the background so it has all the functionality you expect, including reading your .vimrc configuration and your plugins.</p>\n'}, {'answer_id': 48138707, 'author': 'codeDr', 'author_id': 108153, 'author_profile': 'https://Stackoverflow.com/users/108153', 'pm_score': 0, 'selected': False, 'text': '<p>With Firefox-57 on Linux, I installed textern <a href="https://addons.mozilla.org/en-US/firefox/addon/textern/" rel="nofollow noreferrer">https://addons.mozilla.org/en-US/firefox/addon/textern/</a>, and found it to be a suitable replacement for ViewSourceWith for editing text boxes.</p>\n'}, {'answer_id': 50163409, 'author': 'josch', 'author_id': 784669, 'author_profile': 'https://Stackoverflow.com/users/784669', 'pm_score': 4, 'selected': False, 'text': '<p>The current answers don\'t work anymore now that Mozilla removed XUL in favour of WebExtensions. With recent firefox versions, there are the following options (sorted in descending order by the current popularity on addons.mozilla.org).</p>\n\n<p><a href="https://addons.mozilla.org/en-US/firefox/addon/ghosttext/" rel="noreferrer">GhostText</a> provides instant synchronization between editor and textbox via editor-specific plugins. The project is on <a href="https://github.com/GhostText/GhostText" rel="noreferrer">github</a> and the <a href="https://github.com/falstro/ghost-text-vim" rel="noreferrer">vim extension</a> is written in Tcl.</p>\n\n<p><a href="https://addons.mozilla.org/en-US/firefox/addon/withexeditor/" rel="noreferrer">withExEditor</a> is cross-platform but requires a native application written in node.js. In addition to editing text fields it also allows viewing the source of the page, MathML, SVG and the current selection. The project on <a href="https://github.com/asamuzaK/withExEditor" rel="noreferrer">github</a> and the <a href="https://github.com/asamuzaK/withExEditorHost" rel="noreferrer">native node.js application</a></p>\n\n<p><a href="https://addons.mozilla.org/en-US/firefox/addon/textern/" rel="noreferrer">Textern</a> requires a (currently) Linux-only native application written in Python. Synchronizes the content of the text field while you type in the editor. The extension and the native app can be found on <a href="https://github.com/jlebon/textern" rel="noreferrer">github</a></p>\n'}, {'answer_id': 61411545, 'author': 'David Gay', 'author_id': 1196465, 'author_profile': 'https://Stackoverflow.com/users/1196465', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://addons.mozilla.org/en-US/firefox/addon/tridactyl-vim/" rel="noreferrer">Tridactyl</a> is probably what you\'re looking for nowadays.</p>\n\n<p>It\'s the spiritual successor to the likes of Pentadactyl and Vimperator, which are not available for the current version of Firefox.</p>\n\n<p>If you want something more like It\'s All Text, where the editing area appears right on top of the browser text area rather than launching an editor window, and you\'re willing to use Neovim, check out <a href="https://github.com/glacambre/firenvim" rel="noreferrer">firenvim</a>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13060/'] |
75,675 | <p>How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)?
The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like</p>
<pre><code>sqlite3 db .dump
</code></pre>
<p>but without dumping the schema and selecting which tables to dump.</p>
| [{'answer_id': 75694, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>You could do a select on the tables inserting commas after each field to produce a csv, or use a GUI tool to return all the data and save it to a csv.</p>\n'}, {'answer_id': 79168, 'author': 'harningt', 'author_id': 12713, 'author_profile': 'https://Stackoverflow.com/users/12713', 'pm_score': 2, 'selected': False, 'text': "<p>The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.</p>\n\n<p>Example pseudo code:</p>\n\n<pre><code>SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || \n {for each value} ' quote(' || value || ')' (+ commas until final)\n|| ')' FROM 'tableName' ORDER BY rowid DESC\n</code></pre>\n\n<p>See: <code>src/shell.c:838</code> (for sqlite-3.5.9) for actual code</p>\n\n<p>You might even just take that shell and comment out the schema parts and use that.</p>\n"}, {'answer_id': 199221, 'author': 'CyberFonic', 'author_id': 23999, 'author_profile': 'https://Stackoverflow.com/users/23999', 'pm_score': 8, 'selected': False, 'text': "<p>You're not saying what you wish to do with the dumped file.</p>\n<p>To get a CSV file (which can be imported into almost everything)</p>\n<pre><code>.mode csv \n-- use '.separator SOME_STRING' for something other than a comma.\n.headers on \n.out file.csv \nselect * from MyTable;\n</code></pre>\n<p>To get an SQL file (which can be reinserted into a different SQLite database)</p>\n<pre><code>.mode insert <target_table_name>\n.out file.sql \nselect * from MyTable;\n</code></pre>\n"}, {'answer_id': 422842, 'author': 'polyglot', 'author_id': 45383, 'author_profile': 'https://Stackoverflow.com/users/45383', 'pm_score': 5, 'selected': False, 'text': '<p>Not the best way, but at lease does not need external tools (except grep, which is standard on *nix boxes anyway)</p>\n\n<pre><code>sqlite3 database.db3 .dump | grep \'^INSERT INTO "tablename"\'\n</code></pre>\n\n<p>but you do need to do this command for each table you are looking for though.</p>\n\n<p>Note that this does not include schema.</p>\n'}, {'answer_id': 1938480, 'author': 'Paul Egan', 'author_id': 2211429, 'author_profile': 'https://Stackoverflow.com/users/2211429', 'pm_score': 5, 'selected': False, 'text': '<p>You can specify one or more table arguments to the .dump special command, e.g.<code>sqlite3 db ".dump \'table1\' \'table2\'"</code>.</p>\n'}, {'answer_id': 7526055, 'author': 'jellyfish', 'author_id': 534951, 'author_profile': 'https://Stackoverflow.com/users/534951', 'pm_score': 8, 'selected': False, 'text': '<p>You can do this getting difference of .schema and .dump commands. for example with grep:</p>\n\n<pre><code>sqlite3 some.db .schema > schema.sql\nsqlite3 some.db .dump > dump.sql\ngrep -vx -f schema.sql dump.sql > data.sql\n</code></pre>\n\n<p><code>data.sql</code> file will contain only data without schema, something like this:</p>\n\n<pre><code>BEGIN TRANSACTION;\nINSERT INTO "table1" VALUES ...;\n...\nINSERT INTO "table2" VALUES ...;\n...\nCOMMIT;\n</code></pre>\n\n<p>I hope this helps you.</p>\n'}, {'answer_id': 7974100, 'author': 'Drew', 'author_id': 295290, 'author_profile': 'https://Stackoverflow.com/users/295290', 'pm_score': 3, 'selected': False, 'text': '<p>As an improvement to Paul Egan\'s answer, this can be accomplished as follows:</p>\n\n<pre><code>sqlite3 database.db3 \'.dump "table1" "table2"\' | grep \'^INSERT\'\n</code></pre>\n\n<p>--or--</p>\n\n<pre><code>sqlite3 database.db3 \'.dump "table1" "table2"\' | grep -v \'^CREATE\'\n</code></pre>\n\n<p>The caveat, of course, is that you have to have grep installed. </p>\n'}, {'answer_id': 10619827, 'author': 'Elia Schito', 'author_id': 601782, 'author_profile': 'https://Stackoverflow.com/users/601782', 'pm_score': 2, 'selected': False, 'text': "<p>This version works well with newlines inside inserts:</p>\n\n<p><code>sqlite3 database.sqlite3 .dump | grep -v '^CREATE'</code></p>\n\n<p>In practice excludes all the lines starting with <code>CREATE</code> which is less likely to contain newlines</p>\n"}, {'answer_id': 20014210, 'author': 'retracile', 'author_id': 100073, 'author_profile': 'https://Stackoverflow.com/users/100073', 'pm_score': 4, 'selected': False, 'text': '<p>Any answer which suggests using grep to exclude the <code>CREATE</code> lines or just grab the <code>INSERT</code> lines from the <code>sqlite3 $DB .dump</code> output will fail badly. The <code>CREATE TABLE</code> commands list one column per line (so excluding <code>CREATE</code> won\'t get all of it), and values on the <code>INSERT</code> lines can have embedded newlines (so you can\'t grab just the <code>INSERT</code> lines).</p>\n\n<pre><code>for t in $(sqlite3 $DB .tables); do\n echo -e ".mode insert $t\\nselect * from $t;"\ndone | sqlite3 $DB > backup.sql\n</code></pre>\n\n<p>Tested on sqlite3 version 3.6.20.</p>\n\n<p>If you want to exclude certain tables you can filter them with <code>$(sqlite $DB .tables | grep -v -e one -e two -e three)</code>, or if you want to get a specific subset replace that with <code>one two three</code>.</p>\n'}, {'answer_id': 23658679, 'author': 'Davoud Taghawi-Nejad', 'author_id': 236830, 'author_profile': 'https://Stackoverflow.com/users/236830', 'pm_score': 3, 'selected': False, 'text': '<p>In Python or Java or any high level language the .dump does not work. We need to code the conversion to CSV by hand. I give an Python example. Others, examples would be appreciated:</p>\n\n<pre><code>from os import path \nimport csv \n\ndef convert_to_csv(directory, db_name):\n conn = sqlite3.connect(path.join(directory, db_name + \'.db\'))\n cursor = conn.cursor()\n cursor.execute("SELECT name FROM sqlite_master WHERE type=\'table\';")\n tables = cursor.fetchall()\n for table in tables:\n table = table[0]\n cursor.execute(\'SELECT * FROM \' + table)\n column_names = [column_name[0] for column_name in cursor.description]\n with open(path.join(directory, table + \'.csv\'), \'w\') as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break\n</code></pre>\n\n<p>If you have \'panel data, in other words many individual entries with id\'s add this to the with look and it also dumps summary statistics:</p>\n\n<pre><code> if \'id\' in column_names:\n with open(path.join(directory, table + \'_aggregate.csv\'), \'w\') as csv_file:\n csv_writer = csv.writer(csv_file)\n column_names.remove(\'id\')\n column_names.remove(\'round\')\n sum_string = \',\'.join(\'sum(%s)\' % item for item in column_names)\n cursor.execute(\'SELECT round, \' + sum_string +\' FROM \' + table + \' GROUP BY round;\')\n csv_writer.writerow([\'round\'] + column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break \n</code></pre>\n'}, {'answer_id': 28554255, 'author': 'Walty Yeung', 'author_id': 176423, 'author_profile': 'https://Stackoverflow.com/users/176423', 'pm_score': 0, 'selected': False, 'text': '<p>The answer by retracile should be the closest one, yet it does not work for my case. One insert query just broke in the middle and the export just stopped. Not sure what is the reason. However It works fine during <code>.dump</code>.</p>\n\n<p>Finally I wrote a tool for the split up the SQL generated from <code>.dump</code>:</p>\n\n<p><a href="https://github.com/motherapp/sqlite_sql_parser/" rel="nofollow">https://github.com/motherapp/sqlite_sql_parser/</a> </p>\n'}, {'answer_id': 37296788, 'author': 'Francisco Puga', 'author_id': 930271, 'author_profile': 'https://Stackoverflow.com/users/930271', 'pm_score': 3, 'selected': False, 'text': '<h1>Review of other possible solutions</h1>\n\n<p><strong>Include only INSERTs</strong></p>\n\n<pre><code>sqlite3 database.db3 .dump | grep \'^INSERT INTO "tablename"\'\n</code></pre>\n\n<p>Easy to implement but it will fail if any of your columns include new lines</p>\n\n<p><strong>SQLite insert mode</strong></p>\n\n<pre><code>for t in $(sqlite3 $DB .tables); do\n echo -e ".mode insert $t\\nselect * from $t;"\ndone | sqlite3 $DB > backup.sql\n</code></pre>\n\n<p>This is a nice and customizable solution, but it doesn\'t work if your columns have blob objects like \'Geometry\' type in spatialite</p>\n\n<p><strong>Diff the dump with the schema</strong></p>\n\n<pre><code>sqlite3 some.db .schema > schema.sql\nsqlite3 some.db .dump > dump.sql\ngrep -v -f schema.sql dump > data.sql\n</code></pre>\n\n<p>Not sure why, but is not working for me</p>\n\n<h1>Another (new) possible solution</h1>\n\n<p>Probably there is not a best answer to this question, but one that is working for me is grep the inserts taking into account that be new lines in the column values with an <a href="https://stackoverflow.com/a/7167115/930271">expression like this</a></p>\n\n<pre><code>grep -Pzo "(?s)^INSERT.*\\);[ \\t]*$"\n</code></pre>\n\n<p>To select the tables do be dumped <code>.dump</code> admits a LIKE argument to match the table names, but if this is not enough probably a simple script is better option</p>\n\n<pre><code>TABLES=\'table1 table2 table3\'\n\necho \'\' > /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e ".dump ${t}" | sqlite3 database.db3 | grep -Pzo "(?s)^INSERT.*?\\);$" >> /tmp/backup.sql\ndone\n</code></pre>\n\n<p>or, something more elaborated to respect foreign keys and encapsulate all the dump in only one transaction</p>\n\n<pre><code>TABLES=\'table1 table2 table3\'\n\necho \'BEGIN TRANSACTION;\' > /tmp/backup.sql\necho \'\' >> /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e ".dump ${t}" | sqlite3 $1 | grep -Pzo "(?s)^INSERT.*?\\);$" | grep -v -e \'PRAGMA foreign_keys=OFF;\' -e \'BEGIN TRANSACTION;\' -e \'COMMIT;\' >> /tmp/backup.sql\ndone\n\necho \'\' >> /tmp/backup.sql\necho \'COMMIT;\' >> /tmp/backup.sql\n</code></pre>\n\n<p>Take into account that the grep expression will fail if <code>);</code> is a string present in any of the columns</p>\n\n<p>To restore it (in a database with the tables already created)</p>\n\n<pre><code>sqlite3 -bail database.db3 < /tmp/backup.sql\n</code></pre>\n'}, {'answer_id': 41738349, 'author': 'PeterCo', 'author_id': 2613621, 'author_profile': 'https://Stackoverflow.com/users/2613621', 'pm_score': 2, 'selected': False, 'text': '<p>According to the SQLite documentation for the <a href="https://www.sqlite.org/cli.html" rel="nofollow noreferrer">Command Line Shell For SQLite</a> you can export an SQLite table (or part of a table) as CSV, simply by setting the "mode" to "csv" and then run a query to extract the desired rows of the table:</p>\n\n<pre><code>sqlite> .header on\nsqlite> .mode csv\nsqlite> .once c:/work/dataout.csv\nsqlite> SELECT * FROM tab1;\nsqlite> .exit\n</code></pre>\n\n<p>Then use the ".import" command to import CSV (comma separated value) data into an SQLite table:</p>\n\n<pre><code>sqlite> .mode csv\nsqlite> .import C:/work/dataout.csv tab1\nsqlite> .exit\n</code></pre>\n\n<p>Please read the further documentation about the two cases to consider: (1) Table "tab1" does not previously exist and (2) table "tab1" does already exist. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6068/'] |
75,677 | <p>How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution? What if I want a mean and standard deviation of my choosing?</p>
| [{'answer_id': 75720, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 6, 'selected': False, 'text': '<p>The <a href="http://en.wikipedia.org/wiki/Ziggurat_algorithm" rel="noreferrer">Ziggurat algorithm</a> is pretty efficient for this, although the <a href="http://en.wikipedia.org/wiki/Box-Muller_transform" rel="noreferrer">Box-Muller transform</a> is easier to implement from scratch (and not crazy slow).</p>\n'}, {'answer_id': 75889, 'author': 'hughdbrown', 'author_id': 10293, 'author_profile': 'https://Stackoverflow.com/users/10293', 'pm_score': 2, 'selected': False, 'text': '<p>I would use Box-Muller. Two things about this:</p>\n\n<ol>\n<li>You end up with two values per iteration<br>\nTypically, you cache one value and return the other. On the next call for a sample, you return the cached value.</li>\n<li>Box-Muller gives a Z-score<br>\nYou have to then scale the Z-score by the standard deviation and add the mean to get the full value in the normal distribution.</li>\n</ol>\n'}, {'answer_id': 75910, 'author': 'Brent.Longborough', 'author_id': 9634, 'author_profile': 'https://Stackoverflow.com/users/9634', 'pm_score': 1, 'selected': False, 'text': '<p>The standard Python library module <strong>random</strong> has what you want:</p>\n\n<blockquote>\n <p>normalvariate(mu, sigma)<br>\n Normal distribution. mu is the mean, and sigma is the standard deviation.</p>\n</blockquote>\n\n<p>For the algorithm itself, take a look at the function in random.py in the Python library.</p>\n\n<p>The <a href="http://docs.python.org/lib/module-random.html" rel="nofollow noreferrer">manual entry is here</a> </p>\n'}, {'answer_id': 77976, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<pre><code>function distRandom(){\n do{\n x=random(DISTRIBUTION_DOMAIN);\n }while(random(DISTRIBUTION_RANGE)>=distributionFunction(x));\n return x;\n}\n</code></pre>\n'}, {'answer_id': 86885, 'author': 'Adi', 'author_id': 9090, 'author_profile': 'https://Stackoverflow.com/users/9090', 'pm_score': 5, 'selected': False, 'text': '<p>Changing the distribution of any function to another involves using the inverse of the function you want.</p>\n\n<p>In other words, if you aim for a specific probability function p(x) you get the distribution by integrating over it -> d(x) = integral(p(x)) and use its inverse: Inv(d(x)). Now use the random probability function (which have uniform distribution) and cast the result value through the function Inv(d(x)). You should get random values cast with distribution according to the function you chose.</p>\n\n<p>This is the generic math approach - by using it you can now choose any probability or distribution function you have as long as it have inverse or good inverse approximation.</p>\n\n<p>Hope this helped and thanks for the small remark about using the distribution and not the probability itself.</p>\n'}, {'answer_id': 88547, 'author': 'jilles de wit', 'author_id': 7531, 'author_profile': 'https://Stackoverflow.com/users/7531', 'pm_score': 3, 'selected': False, 'text': '<p>Use the central limit theorem <a href="http://en.wikipedia.org/wiki/Central_limit_theorem" rel="noreferrer">wikipedia entry</a> <a href="http://mathworld.wolfram.com/CentralLimitTheorem.html" rel="noreferrer">mathworld entry</a> to your advantage.</p>\n\n<p>Generate n of the uniformly distributed numbers, sum them, subtract n*0.5 and you have the output of an approximately normal distribution with mean equal to 0 and variance equal to <code>(1/12) * (1/sqrt(N))</code> (see <a href="http://en.wikipedia.org/wiki/Uniform_distribution_(continuous)" rel="noreferrer">wikipedia on uniform distributions</a> for that last one) </p>\n\n<p>n=10 gives you something half decent fast. If you want something more than half decent go for tylers solution (as noted in the <a href="http://en.wikipedia.org/wiki/Normal_distribution#Generating_values_for_normal_random_variables" rel="noreferrer">wikipedia entry on normal distributions</a>)</p>\n'}, {'answer_id': 196941, 'author': 'user5084', 'author_id': 5084, 'author_profile': 'https://Stackoverflow.com/users/5084', 'pm_score': 5, 'selected': False, 'text': '<p>Here is a javascript implementation using the polar form of the Box-Muller transformation.</p>\n\n<pre><code>/*\n * Returns member of set with a given mean and standard deviation\n * mean: mean\n * standard deviation: std_dev \n */\nfunction createMemberInNormalDistribution(mean,std_dev){\n return mean + (gaussRandom()*std_dev);\n}\n\n/*\n * Returns random number in normal distribution centering on 0.\n * ~95% of numbers returned should fall between -2 and 2\n * ie within two standard deviations\n */\nfunction gaussRandom() {\n var u = 2*Math.random()-1;\n var v = 2*Math.random()-1;\n var r = u*u + v*v;\n /*if outside interval [0,1] start over*/\n if(r == 0 || r >= 1) return gaussRandom();\n\n var c = Math.sqrt(-2*Math.log(r)/r);\n return u*c;\n\n /* todo: optimize this algorithm by caching (v*c) \n * and returning next time gaussRandom() is called.\n * left out for simplicity */\n}\n</code></pre>\n'}, {'answer_id': 3265174, 'author': 'Alexandre C.', 'author_id': 373025, 'author_profile': 'https://Stackoverflow.com/users/373025', 'pm_score': 6, 'selected': False, 'text': '<p>There are plenty of methods:</p>\n\n<ul>\n<li>Do <strong>not</strong> use Box Muller. Especially if you draw many gaussian numbers. Box Muller yields a result which is clamped between -6 and 6 (assuming double precision. Things worsen with floats.). And it is really less efficient than other available methods.</li>\n<li>Ziggurat is fine, but needs a table lookup (and some platform-specific tweaking due to cache size issues)</li>\n<li>Ratio-of-uniforms is my favorite, only a few addition/multiplications and a log 1/50th of the time (eg. <a href="http://books.google.fr/books?id=UQW_VL2H56IC&pg=PA368&lpg=PA368&dq=%22ratio+of+uniforms%22+normal+distribution&source=bl&ots=PLY_fm-_az&sig=sh7sfCZ7PeXSpyVcVi37BMhVYPo&hl=fr&ei=BlxATOmbK4HLOOjn9ZkN&sa=X&oi=book_result&ct=result&resnum=8&ved=0CD0Q6AEwBw#v=onepage&q=%22ratio%20of%20uniforms%22%20normal%20distribution&f=false" rel="noreferrer">look there</a>).</li>\n<li>Inverting the CDF <strong>is</strong> efficient (and overlooked, why ?), you have fast implementations of it available if you search google. It is mandatory for Quasi-Random numbers.</li>\n</ul>\n'}, {'answer_id': 7771542, 'author': 'Erik Aronesty', 'author_id': 627042, 'author_profile': 'https://Stackoverflow.com/users/627042', 'pm_score': 3, 'selected': False, 'text': '<p>Where R1, R2 are random uniform numbers:</p>\n<p>NORMAL DISTRIBUTION, with SD of 1:</p>\n<pre><code>sqrt(-2*log(R1))*cos(2*pi*R2)\n</code></pre>\n<p>This is exact... no need to do all those slow loops!</p>\n<p>Reference: <a href="http://dspguide.com/ch2/6.htm" rel="nofollow noreferrer">dspguide.com/ch2/6.htm</a></p>\n'}, {'answer_id': 8932273, 'author': 'Hippo', 'author_id': 1159325, 'author_profile': 'https://Stackoverflow.com/users/1159325', 'pm_score': 0, 'selected': False, 'text': '<p>I thing you should try this in EXCEL: <code>=norminv(rand();0;1)</code>. This will product the random numbers which should be normally distributed with the zero mean and unite variance. "0" can be supplied with any value, so that the numbers will be of desired mean, and by changing "1", you will get the variance equal to the square of your input.</p>\n\n<p>For example: <code>=norminv(rand();50;3)</code> will yield to the normally distributed numbers with MEAN = 50 VARIANCE = 9.</p>\n'}, {'answer_id': 34056202, 'author': 'Konstantin Burlachenko', 'author_id': 1154447, 'author_profile': 'https://Stackoverflow.com/users/1154447', 'pm_score': 0, 'selected': False, 'text': "<p>Q How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution?</p>\n\n<ol>\n<li><p>For software implementation I know couple random generator names which give you a pseudo uniform random sequence in [0,1] (Mersenne Twister, Linear Congruate Generator). Let's call it U(x)</p></li>\n<li><p>It is exist mathematical area which called probibility theory. \nFirst thing: If you want to model r.v. with integral distribution F then you can try just to evaluate F^-1(U(x)). In pr.theory it was proved that such r.v. will have integral distribution F.</p></li>\n<li><p>Step 2 can be appliable to generate r.v.~F without usage of any counting methods when F^-1 can be derived analytically without problems. (e.g. exp.distribution)</p></li>\n<li><p>To model normal distribution you can cacculate y1*cos(y2), where y1~is uniform in[0,2pi]. and y2 is the relei distribution.</p></li>\n</ol>\n\n<p>Q: What if I want a mean and standard deviation of my choosing?</p>\n\n<p>You can calculate sigma*N(0,1)+m.</p>\n\n<p>It can be shown that such shifting and scaling lead to N(m,sigma)</p>\n"}, {'answer_id': 36389129, 'author': 'Pepijn Schmitz', 'author_id': 1147600, 'author_profile': 'https://Stackoverflow.com/users/1147600', 'pm_score': 2, 'selected': False, 'text': '<p>It seems incredible that I could add something to this after eight years, but for the case of Java I would like to point readers to the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextGaussian--" rel="nofollow">Random.nextGaussian()</a> method, which generates a Gaussian distribution with mean 0.0 and standard deviation 1.0 for you.</p>\n\n<p>A simple addition and/or multiplication will change the mean and standard deviation to your needs.</p>\n'}, {'answer_id': 47537485, 'author': 'madx', 'author_id': 3138238, 'author_profile': 'https://Stackoverflow.com/users/3138238', 'pm_score': 1, 'selected': False, 'text': '<p>This is a Matlab implementation using the polar form of the <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform" rel="nofollow noreferrer">Box-Muller</a> transformation:</p>\n\n<p>Function <code>randn_box_muller.m</code>:</p>\n\n<pre><code>function [values] = randn_box_muller(n, mean, std_dev)\n if nargin == 1\n mean = 0;\n std_dev = 1;\n end\n\n r = gaussRandomN(n);\n values = r.*std_dev - mean;\nend\n\nfunction [values] = gaussRandomN(n)\n [u, v, r] = gaussRandomNValid(n);\n\n c = sqrt(-2*log(r)./r);\n values = u.*c;\nend\n\nfunction [u, v, r] = gaussRandomNValid(n)\n r = zeros(n, 1);\n u = zeros(n, 1);\n v = zeros(n, 1);\n\n filter = r==0 | r>=1;\n\n % if outside interval [0,1] start over\n while n ~= 0\n u(filter) = 2*rand(n, 1)-1;\n v(filter) = 2*rand(n, 1)-1;\n r(filter) = u(filter).*u(filter) + v(filter).*v(filter);\n\n filter = r==0 | r>=1;\n n = size(r(filter),1);\n end\nend\n</code></pre>\n\n<p>And invoking <code>histfit(randn_box_muller(10000000),100);</code> this is the result:\n<a href="https://i.stack.imgur.com/s4LeV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s4LeV.png" alt="Box-Muller Matlab Histfit"></a></p>\n\n<p>Obviously it is really inefficient compared with the Matlab built-in <a href="https://it.mathworks.com/help/matlab/ref/randn.html" rel="nofollow noreferrer">randn</a>.</p>\n'}, {'answer_id': 53217176, 'author': 'great_minds_think_alike', 'author_id': 10625359, 'author_profile': 'https://Stackoverflow.com/users/10625359', 'pm_score': 0, 'selected': False, 'text': '<p>I have the following code which maybe could help:</p>\n\n<pre><code>set.seed(123)\nn <- 1000\nu <- runif(n) #creates U\nx <- -log(u)\ny <- runif(n, max=u*sqrt((2*exp(1))/pi)) #create Y\nz <- ifelse (y < dnorm(x)/2, -x, NA)\nz <- ifelse ((y > dnorm(x)/2) & (y < dnorm(x)), x, z)\nz <- z[!is.na(z)]\n</code></pre>\n'}, {'answer_id': 54334875, 'author': 'peterweethetbeter', 'author_id': 10928083, 'author_profile': 'https://Stackoverflow.com/users/10928083', 'pm_score': 0, 'selected': False, 'text': '<p>It is also easier to use the implemented function rnorm() since it is faster than writing a random number generator for the normal distribution. See the following code as prove</p>\n\n<pre><code>n <- length(z)\nt0 <- Sys.time()\nz <- rnorm(n)\nt1 <- Sys.time()\nt1-t0\n</code></pre>\n'}, {'answer_id': 60476443, 'author': 'Alessandro Jacopson', 'author_id': 15485, 'author_profile': 'https://Stackoverflow.com/users/15485', 'pm_score': 1, 'selected': False, 'text': "<p>This is my JavaScript implementation of <strong>Algorithm P</strong> (<em>Polar method for normal deviates</em>) from Section 3.4.1 of Donald Knuth's book <em>The Art of Computer Programming</em>:</p>\n\n<pre><code>function normal_random(mean,stddev)\n{\n var V1\n var V2\n var S\n do{\n var U1 = Math.random() // return uniform distributed in [0,1[\n var U2 = Math.random()\n V1 = 2*U1-1\n V2 = 2*U2-1\n S = V1*V1+V2*V2\n }while(S >= 1)\n if(S===0) return 0\n return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))\n}\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8062/'] |
75,691 | <p>I am writing picture editing windows forms application using vb.net/c#. i have a client requirement to capture the photo from digital still camera attached to computer. </p>
<p>how can i capture a photo from USB connected digital still camera device in my windows application ?</p>
| [{'answer_id': 75728, 'author': 'Alex Duggleby', 'author_id': 5790, 'author_profile': 'https://Stackoverflow.com/users/5790', 'pm_score': 1, 'selected': False, 'text': '<p>Usually the camera is displayed as a removable drive when attached.</p>\n\n<p>So for a Winforms application just let the user select the drive and the picture you want to upload. You can do any processing once you have the FileStream of the picture.</p>\n\n<p>In ASP.net you are going to need a FileUpload Control where again the user can select the drive and picture to upload. Processing this time would be via MemoryStream on the HttpRequest.Files object.</p>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 75730, 'author': 'Sean McMains', 'author_id': 2041950, 'author_profile': 'https://Stackoverflow.com/users/2041950', 'pm_score': 0, 'selected': False, 'text': "<p>This depends on your camera.</p>\n\n<p>Many cameras will simply mount as USB mass storage devices. If this is the case, then you can just copy the file from the visible file system like you would any other file on an external disk.</p>\n\n<p>If the camera doesn't make its contents available in this way, you'll need to look at the camera driver documentation to see how they recommend interacting with it.</p>\n"}, {'answer_id': 75740, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 0, 'selected': False, 'text': '<p>It will depend on the brand of camera. Here is a link to start with for <a href="http://www.usa.canon.com/consumer/controller?act=SDKHomePageAct&keycode=Sdk_Lic&fcategoryid=314&modelid=7474&id=3464" rel="nofollow noreferrer">Canon</a>.</p>\n'}, {'answer_id': 75754, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 2, 'selected': False, 'text': "<p>I assume you want to activate the action of taking a picture from the computer which the camera is attached to. If that is the case then the first thing I would do is search for an API for that particular camera model. I don't believe there is a standard protocol/framework for interacting with digital cameras besides accessing the memory card within the camera.</p>\n"}, {'answer_id': 75898, 'author': 'Ilya', 'author_id': 6807, 'author_profile': 'https://Stackoverflow.com/users/6807', 'pm_score': 2, 'selected': False, 'text': '<p>This is depend on the interface the camera exporting. If this is standard mass storage interface you just use standard file interface, i.e you will see the camera as removable disk and can use standard Create/Read/Write/File operation.<br>\nMany new cameras have ptp (Picture transport protocol) interface. So you will need using <a href="http://msdn.microsoft.com/en-us/library/aa139779.aspx" rel="nofollow noreferrer">Windows Image Acquisition</a> API.</p>\n\n<p>You might find useful following <a href="http://www.codeproject.com/KB/dotnet/wiascriptingdotnet.aspx" rel="nofollow noreferrer">Link</a>. If i understand correctly this is a sample code for exactly what are you looking for. Google is your friend :) </p>\n\n<p>Another piece of info: many cameras will support both mass storage and ptp interfaces and it will be selectable by camera user interface. In case of automatic mode camera probably will switch to ptp interface.</p>\n'}, {'answer_id': 599954, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': True, 'text': "<p>If you use the Windows Image Acquisition Library, you'll see events there for capturing camera new picture events. I had a similar requirement and wrote a test rig; we went down to the local camera store and tried every camera they had. The only cameras we could find that supported this functionality were the Nikon D-series cameras.</p>\n\n<p>We found that with most cameras, you can't even take a picture when they are plugged in. When you plug them in to the USB port, most cameras will switch into a mode where the only thing they'll do is transfer data. The quick way to find out if a camera will work at all is to plug it into a PC, then try to snap a picture. If it lets you do that you have a chance. It also needs to support PTP.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13337/'] |
75,700 | <p>I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.
<br><br>I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.<br><br>
A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?</p>
<hr>
<p>In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?<br><br>
That's what I have with JPA, two different Spring beans that are transaction managers.</p>
| [{'answer_id': 78479, 'author': 'toolkit', 'author_id': 3295, 'author_profile': 'https://Stackoverflow.com/users/3295', 'pm_score': 4, 'selected': True, 'text': '<p>I guess you have 2 choices</p>\n\n<p>If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I\'m not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple <a href="http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.html" rel="noreferrer">TransactionProxyFactoryBean</a> to define transaction boundaries, eg:</p>\n\n<pre><code><bean id="firstRealService" class="com.acme.FirstServiceImpl"/>\n<bean id="firstService" \n class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">\n <property name="transactionManager" ref="firstJpaTm"/>\n <property name="target" ref="firstRealService"/>\n <property name="transactionAttributes">\n <props>\n <prop key="insert*">PROPAGATION_REQUIRED</prop>\n <prop key="update*">PROPAGATION_REQUIRED</prop>\n <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>\n </props>\n </property>\n</bean>\n<!-- similar for your second service -->\n</code></pre>\n\n<p>If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The <a href="http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/jpa/JpaTransactionManager.html" rel="noreferrer">API</a> states:</p>\n\n<blockquote>\n <p>This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.</p>\n</blockquote>\n\n<p>What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:</p>\n\n<pre><code><tx:annotation-driven transaction-manager="txManager"/>\n\n<bean id="txManager" \n class="org.springframework.transaction.jta.JtaTransactionManager">\n <property name="transactionManagerName" value="appserver/jndi/path" />\n</bean>\n</code></pre>\n\n<p>If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven\'t tried this myself yet)</p>\n\n<p>As for configuring the Jpa persistence provider, I\'m not that familiar. What JPA persistence provider are you using?</p>\n\n<p>The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate\'s JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.</p>\n\n<p>Hope this helps</p>\n'}, {'answer_id': 280875, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>The only situation in which you can have two Spring transaction managers is if you never have both transactions open at one time. This is not intrinsically to do with distributed transactions - the same restrictions apply even if you want the two datasources to have completely separate (but potentially overlapping in time) transaction lifecyles.</p>\n\n<p>Internally Spring's transaction managers all use Spring's TransactionSynchronizationManager which keeps a bunch of critical state in static ThreadLocal variables, so transaction managers are guaranteed to stomp all over each other's state.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13143/'] |
75,701 | <p>Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor. Will the destructor be called when the DLL is unloaded?</p>
| [{'answer_id': 75788, 'author': 'Philip Rieck', 'author_id': 12643, 'author_profile': 'https://Stackoverflow.com/users/12643', 'pm_score': 2, 'selected': False, 'text': "<p>It should be called when either the application ends or the DLL is unloaded, whichever comes first. Note that this is somewhat dependent on the actual runtime you're compiling against. </p>\n\n<p>Also, beware non-trivial destructors as there are both timing and ordering issues. Your DLL may be unloaded <strong>after</strong> a DLL your destructor relies on, which would obviously cause issues.</p>\n"}, {'answer_id': 75855, 'author': 'INS', 'author_id': 13136, 'author_profile': 'https://Stackoverflow.com/users/13136', 'pm_score': 1, 'selected': False, 'text': '<p>When DllMain with fdwReason = DLL_PROCESS_DETACH parameter is called it means the DLL is unloaded by the application. This is the time before the destructor of global/static objects gets called.</p>\n'}, {'answer_id': 76273, 'author': 'Mark Ransom', 'author_id': 5987, 'author_profile': 'https://Stackoverflow.com/users/5987', 'pm_score': 3, 'selected': False, 'text': '<p>This page from Microsoft goes into the details of DLL initialization and destruction of globals:<br>\n<a href="http://msdn.microsoft.com/en-us/library/988ye33t.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/988ye33t.aspx</a></p>\n'}, {'answer_id': 76677, 'author': 'MSN', 'author_id': 6210, 'author_profile': 'https://Stackoverflow.com/users/6210', 'pm_score': 3, 'selected': False, 'text': '<p>If you want to see the actual code that gets executed when linking a .dll, take a look at <code>%ProgramFiles%\\Visual Studio 8\\vc\\crt\\src\\dllcrt0.c</code>.</p>\n\n<p>From inspection, destructors will be called via <code>_cexit()</code> when the internal reference count maintained by the dll CRT hits zero.</p>\n'}, {'answer_id': 78235, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 6, 'selected': True, 'text': '<p>In a Windows C++ DLL, all global objects (including static members of classes) will be constructed just before the calling of the DllMain with DLL_PROCESS_ATTACH, and they will be destroyed just after the call of the DllMain with DLL_PROCESS_DETACH.</p>\n<p>Now, you must consider three problems:</p>\n<p>0 - Of course, global non-const objects are evil (but you already know that, so I\'ll avoid mentionning multithreading, locks, god-objects, etc.)</p>\n<p>1 - The order of construction of objects or different compilation units (i.e. CPP files) is not guaranteed, so you can\'t hope the object A will be constructed before B if the two objects are instanciated in two different CPPs. This is important if B depends on A. The solution is to move all global objects in the same CPP file, as inside the same compilation unit, the order of instanciation of the objects will be the order of construction (and the inverse of the order of destruction)</p>\n<p>2 - There are things that are forbidden to do in the DllMain. Those things are probably forbidden, too, in the constructors. So avoid locking something. See Raymond Chen\'s excellent blog on the subject:</p>\n<ul>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20040127-00/?p=40873" rel="nofollow noreferrer">Some reasons not to do anything scary in your DllMain</a></li>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20040128-00/?p=40853" rel="nofollow noreferrer">Another reason not to do anything scary in your DllMain: Inadvertent deadlock</a></li>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20140821-00/?p=183" rel="nofollow noreferrer">Some reasons not to do anything scary in your DllMain, part 3</a></li>\n</ul>\n<p>In this case, lazy initialization could be interesting: The classes remain in an "un-initialized" state (internal pointers are NULL, booleans are false, whatever) until you call one of their methods, at which point they\'ll initialize themselves. If you use those objects inside the main (or one of the main\'s descendant functions), you\'ll be ok because they will be called after execution of DllMain.</p>\n<p>3 - Of course, if some global objects in DLL A depend on global objects in DLL B, you should be very very careful about DLL loading order, and thus dependancies. In this case, DLLs with direct or indirect circular dependancies will cause you an insane amount of headaches. The best solution is to break the circular dependancies.</p>\n<p>P.S.: Note that in C++, constructor can throw, and you don\'t want an exception in the middle of a DLL loading, so be sure your global objects won\'t be using exception without a very, very good reason. As correctly written destructors are not authorized to throw, the DLL unloading should be ok in this case.</p>\n'}, {'answer_id': 31164412, 'author': 'Konstantin Burlachenko', 'author_id': 1154447, 'author_profile': 'https://Stackoverflow.com/users/1154447', 'pm_score': 2, 'selected': False, 'text': '<p>In windows binary image files with extension *.exe, *.dll are in <a href="https://msdn.microsoft.com/en-us/windows/hardware/gg463119.aspx" rel="nofollow">PE format</a>\nSuch files have Entry Point. You can view it with dumpbin tool like </p>\n\n<blockquote>\n <p>dumpbin /headers dllname.dll</p>\n</blockquote>\n\n<p>If you use C runtime from Microsoft, then your entry point will be something like\n *CRTStartup or *DllMainCRTStartup</p>\n\n<p>Such functions perform initialization of c and c++ runtime and delegate execution to (main, WinMain) or to DllMain respectively.</p>\n\n<p>If you use Microsofts VC compiler then you can watch at source code of this functions in yours VC directory:</p>\n\n<ul>\n<li>crt0.c</li>\n<li>dllcrt0.c</li>\n</ul>\n\n<p>DllMainCRTStartup process all things need to init/deinit your global variables from .data sections in normal scenario, when it retrive notification DLL_PROCESS_DETACH during dll unload. For example:</p>\n\n<ul>\n<li>main or WinMain of startup thread of program returns control flow</li>\n<li>you explictly call FreeLibrary and use-dll-counter is zero</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13313/'] |
75,704 | <p>I see that within MySQL there are <code>Cast()</code> and <code>Convert()</code> functions to create integers from values, but is there any way to check to see if a value is an integer? Something like <code>is_int()</code> in PHP is what I am looking for.</p>
| [{'answer_id': 75739, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 4, 'selected': False, 'text': '<p>Match it against a regular expression.</p>\n<p>c.f. <a href="http://forums.mysql.com/read.php?60,1907,38488#msg-38488" rel="noreferrer">http://forums.mysql.com/read.php?60,1907,38488#msg-38488</a> as quoted below:</p>\n<blockquote>\n<p>Re: IsNumeric() clause in MySQL??\n<br />Posted by: kevinclark ()\n<br />Date: August 08, 2005 01:01PM</p>\n<p><br />I agree. Here is a function I created for MySQL 5:</p>\n</blockquote>\n\n<pre><code>CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint\nRETURN sIn REGEXP \'^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$\';\n</code></pre>\n<blockquote>\n<p><br />This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.</p>\n</blockquote>\n'}, {'answer_id': 75880, 'author': 'Jumpy', 'author_id': 9416, 'author_profile': 'https://Stackoverflow.com/users/9416', 'pm_score': 9, 'selected': True, 'text': "<p>I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do</p>\n\n<pre><code>select field from table where field REGEXP '^-?[0-9]+$';\n</code></pre>\n\n<p>this is reasonably fast. If your field is numeric, just test for</p>\n\n<pre><code>ceil(field) = field\n</code></pre>\n\n<p>instead.</p>\n"}, {'answer_id': 5244724, 'author': 'Jayjitraj', 'author_id': 376948, 'author_profile': 'https://Stackoverflow.com/users/376948', 'pm_score': 3, 'selected': False, 'text': '<p>Here is the simple solution for it\nassuming the data type is varchar </p>\n\n<pre><code>select * from calender where year > 0\n</code></pre>\n\n<p>It will return true if the year is numeric else false </p>\n'}, {'answer_id': 10626708, 'author': 'Bill Kelly', 'author_id': 1399626, 'author_profile': 'https://Stackoverflow.com/users/1399626', 'pm_score': 1, 'selected': False, 'text': "<p>I have tried using the regular expressions listed above, but they do not work for the following:</p>\n\n<pre><code>SELECT '12 INCHES' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n</code></pre>\n\n<p>The above will return <code>1</code> (<code>TRUE</code>), meaning the test of the string '12 INCHES' against the regular expression above, returns <code>TRUE</code>. It looks like a number based on the regular expression used above. In this case, because the 12 is at the beginning of the string, the regular expression interprets it as a number. </p>\n\n<p>The following will return the right value (i.e. <code>0</code>) because the string starts with characters instead of digits</p>\n\n<pre><code>SELECT 'TOP 10' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n</code></pre>\n\n<p>The above will return <code>0</code> (<code>FALSE</code>) because the beginning of the string is text and not numeric.</p>\n\n<p>However, if you are dealing with strings that have a mix of numbers and letters that begin with a number, you will not get the results you want. REGEXP will interpret the string as a valid number when in fact it is not.</p>\n"}, {'answer_id': 11693466, 'author': 'Tom Auger', 'author_id': 467386, 'author_profile': 'https://Stackoverflow.com/users/467386', 'pm_score': 2, 'selected': False, 'text': '<p>What about:</p>\n\n<pre><code>WHERE table.field = "0" or CAST(table.field as SIGNED) != 0\n</code></pre>\n\n<p>to test for numeric and the corrolary:</p>\n\n<pre><code>WHERE table.field != "0" and CAST(table.field as SIGNED) = 0\n</code></pre>\n'}, {'answer_id': 12577316, 'author': 'Tarun Sood', 'author_id': 1696374, 'author_profile': 'https://Stackoverflow.com/users/1696374', 'pm_score': 4, 'selected': False, 'text': "<p>Suppose we have column with alphanumeric field having entries like</p>\n\n<pre><code>a41q\n1458\nxwe8\n1475\nasde\n9582\n.\n.\n.\n.\n.\nqe84\n</code></pre>\n\n<p>and you want highest numeric value from this db column (in this case it is 9582) then this query will help you</p>\n\n<pre><code>SELECT Max(column_name) from table_name where column_name REGEXP '^[0-9]+$'\n</code></pre>\n"}, {'answer_id': 20761038, 'author': 'Riad', 'author_id': 1957432, 'author_profile': 'https://Stackoverflow.com/users/1957432', 'pm_score': 3, 'selected': False, 'text': "<p>This also works:</p>\n\n<pre><code>CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>SELECT CAST('a123' AS UNSIGNED) // returns 0\nSELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0\n</code></pre>\n"}, {'answer_id': 31694100, 'author': 'minhas23', 'author_id': 2458916, 'author_profile': 'https://Stackoverflow.com/users/2458916', 'pm_score': 3, 'selected': False, 'text': "<p>To check if a value is Int in Mysql, we can use the following query.\nThis query will give the rows with Int values</p>\n\n<pre><code>SELECT col1 FROM table WHERE concat('',col * 1) = col;\n</code></pre>\n"}, {'answer_id': 34655769, 'author': 'PodTech.io', 'author_id': 1842743, 'author_profile': 'https://Stackoverflow.com/users/1842743', 'pm_score': 1, 'selected': False, 'text': "<p>This works well for VARCHAR where it begins with a number or not..</p>\n\n<pre><code>WHERE concat('',fieldname * 1) != fieldname \n</code></pre>\n\n<p>may have restrictions when you get to the larger NNNNE+- numbers</p>\n"}, {'answer_id': 41845958, 'author': 'Tim', 'author_id': 7467766, 'author_profile': 'https://Stackoverflow.com/users/7467766', 'pm_score': 0, 'selected': False, 'text': "<p>for me the only thing that works is:</p>\n\n<pre><code>CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT\nRETURN SIN REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$';\n</code></pre>\n\n<p>from kevinclark all other return useless stuff for me in case of <code>234jk456</code> or <code>12 inches</code></p>\n"}, {'answer_id': 49898031, 'author': 'Raymond Nijland', 'author_id': 2548147, 'author_profile': 'https://Stackoverflow.com/users/2548147', 'pm_score': 2, 'selected': False, 'text': '<p>The best i could think of a variable is a int Is a combination with MySQL\'s functions <code>CAST()</code> and <code>LENGTH()</code>. <br /> \nThis method will work on strings, integers, doubles/floats datatypes.</p>\n\n<pre><code>SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int\n</code></pre>\n\n<p>see demo <a href="http://sqlfiddle.com/#!9/ff40cd/44" rel="nofollow noreferrer">http://sqlfiddle.com/#!9/ff40cd/44</a></p>\n\n<blockquote>\n <p>it will fail if the column has a single character value. if column has\n a value \'A\' then Cast(\'A\' as UNSIGNED) will evaluate to 0 and\n LENGTH(0) will be 1. so LENGTH(Cast(\'A\' as UNSIGNED))=LENGTH(0) will\n evaluate to 1=1 => 1</p>\n</blockquote>\n\n<p>True Waqas Malik totally fogotten to test that case. the patch is. </p>\n\n<pre><code>SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;\n</code></pre>\n\n<p><strong>Results</strong></p>\n\n<pre><code>**Query #1**\n\n SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #2**\n\n SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #3**\n\n SELECT "1", (LENGTH(CAST("1" AS UNSIGNED))) = CASE WHEN CAST("1" AS UNSIGNED) = 0 THEN CAST("1" AS UNSIGNED) ELSE (LENGTH("1")) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #4**\n\n SELECT "1.1", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1.1" AS UNSIGNED) = 0 THEN CAST("1.1" AS UNSIGNED) ELSE (LENGTH("1.1")) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #5**\n\n SELECT "1a", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1a" AS UNSIGNED) = 0 THEN CAST("1a" AS UNSIGNED) ELSE (LENGTH("1a")) END AS is_int;\n\n| 1a | is_int |\n| --- | ------ |\n| 1a | 0 |\n\n---\n**Query #6**\n\n SELECT "1.1a", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("1.1a" AS UNSIGNED) = 0 THEN CAST("1.1a" AS UNSIGNED) ELSE (LENGTH("1.1a")) END AS is_int;\n\n| 1.1a | is_int |\n| ---- | ------ |\n| 1.1a | 0 |\n\n---\n**Query #7**\n\n SELECT "a1", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("a1" AS UNSIGNED) = 0 THEN CAST("a1" AS UNSIGNED) ELSE (LENGTH("a1")) END AS is_int;\n\n| a1 | is_int |\n| --- | ------ |\n| a1 | 0 |\n\n---\n**Query #8**\n\n SELECT "a1.1", (LENGTH(CAST("a1.1" AS UNSIGNED))) = CASE WHEN CAST("a1.1" AS UNSIGNED) = 0 THEN CAST("a1.1" AS UNSIGNED) ELSE (LENGTH("a1.1")) END AS is_int;\n\n| a1.1 | is_int |\n| ---- | ------ |\n| a1.1 | 0 |\n\n---\n**Query #9**\n\n SELECT "a", (LENGTH(CAST("a" AS UNSIGNED))) = CASE WHEN CAST("a" AS UNSIGNED) = 0 THEN CAST("a" AS UNSIGNED) ELSE (LENGTH("a")) END AS is_int;\n\n| a | is_int |\n| --- | ------ |\n| a | 0 |\n</code></pre>\n\n<p>see <a href="https://www.db-fiddle.com/f/NNXJ9cPwxjNPz9NknsSGU/0" rel="nofollow noreferrer">demo</a> </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8224/'] |
75,705 | <p>I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction?</p>
<p>Thanks for your time.</p>
| [{'answer_id': 75846, 'author': 'Kearns', 'author_id': 6500, 'author_profile': 'https://Stackoverflow.com/users/6500', 'pm_score': 2, 'selected': False, 'text': '<p>FoxPro 2.0 files were exactly the same as dBase III files with an extra bit for any field that was of type "memo" (not sure the exact name, it\'s been a while). That means that if you just use a <a href="http://www.connectionstrings.com/?carrier=visualfoxpro" rel="nofollow noreferrer">FoxPro 2.x method</a> for accessing the files, it should work.</p>\n'}, {'answer_id': 75915, 'author': 'Fionnuala', 'author_id': 2548, 'author_profile': 'https://Stackoverflow.com/users/2548', 'pm_score': 3, 'selected': False, 'text': '<p>Something like ... ?</p>\n\n<pre><code> ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _\n"Data Source=e:\\My Documents\\dBase;Extended Properties=dBase III"\nDim dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString )\ndBaseConnection.Open()\n</code></pre>\n\n<p>From: <a href="http://bytes.com/forum/thread112085.html" rel="noreferrer">http://bytes.com/forum/thread112085.html</a></p>\n'}, {'answer_id': 779865, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>This is a nice aproach, i didn\'t tested, but i will soon...</p>\n\n<p><a href="http://www.c-sharpcorner.com/uploadfile/rfederico/xbaseenginerfv12022005011623am/xbaseenginerfv.aspx" rel="nofollow noreferrer">http://www.c-sharpcorner.com/uploadfile/rfederico/xbaseenginerfv12022005011623am/xbaseenginerfv.aspx</a></p>\n'}, {'answer_id': 10492908, 'author': 'Dejan Janjušević', 'author_id': 828023, 'author_profile': 'https://Stackoverflow.com/users/828023', 'pm_score': 3, 'selected': False, 'text': '<p>I realize this is an old thread, but in case someone gets here by google (like I have few days ago).. As I wrote <a href="https://stackoverflow.com/questions/3206029/optimal-way-to-handle-dbf-from-c-sharp/10492849#10492849">here</a>, the elegant solution is to use <a href="http://linqtovfp.codeplex.com/" rel="nofollow noreferrer">LINQ to VFP</a> to read from and write to DBF files. I tested it with some dBase III files. It goes like this:</p>\n\n<p>You define your table to match the DBF definition like this:</p>\n\n<pre><code>public partial class MyTable \n{\n public System.Int32 ID { get; set; }\n public System.Decimal Field1 { get; set; }\n public System.String Field2 { get; set; }\n public System.String Field3 { get; set; }\n}\n</code></pre>\n\n<p>You define the context like this:</p>\n\n<pre><code>public partial class Context : DbEntityContextBase \n{\n public Context(string connectionString)\n : this(connectionString, typeof(ContextAttributes).FullName) \n {\n }\n\n public Context(string connectionString, string mappingId)\n : this(VfpQueryProvider.Create(connectionString, mappingId)) \n {\n }\n\n public Context(VfpQueryProvider provider)\n : base(provider) \n {\n }\n\n public virtual IEntityTable<MyTable> MyTables \n {\n get { return this.GetTable<MyTable>(); }\n }\n}\n</code></pre>\n\n<p>You define context attributes like this:</p>\n\n<pre><code>public partial class ContextAttributes : Context \n{\n public ContextAttributes(string connectionString)\n : base(connectionString) {\n }\n\n [Table(Name="mytable")]\n [Column(Member="ID", IsPrimaryKey=true)]\n [Column(Member="Field1")]\n [Column(Member="Field2")]\n [Column(Member="Field3")]\n public override IEntityTable<MyTable> MyTables \n {\n get { return base.MyTables; }\n }\n}\n</code></pre>\n\n<p>You also need a connection string, you can define it in app.config like this (<code>Data\\</code> relative path is used as the source of DBF files in this case):</p>\n\n<pre><code><connectionStrings>\n <add name="VfpData" providerName="System.Data.OleDb"\n connectionString="Provider=VFPOLEDB.1;Data Source=Data\\;"/>\n</connectionStrings>\n</code></pre>\n\n<p>And finally, you can perform reading and writing to and from DBF files as simple as:</p>\n\n<pre><code>// Construct a new context\nvar context = new Context(ConfigurationManager.ConnectionStrings["VfpData"].ConnectionString);\n\n// Write to MyTable.dbf\nvar my = new MyTable\n{\n ID = 1,\n Field1 = 10,\n Field2 = "foo",\n Field3 = "bar"\n}\ncontext.MyTables.Insert(my);\n\n// Read from MyTable.dbf\nConsole.WriteLine("Count: " + context.MyTables.Count());\nforeach (var o in context.MyTables)\n{\n Console.WriteLine(o.Field2 + " " + o.Field3);\n}\n</code></pre>\n'}, {'answer_id': 36814803, 'author': 'DRapp', 'author_id': 74195, 'author_profile': 'https://Stackoverflow.com/users/74195', 'pm_score': 0, 'selected': False, 'text': '<p>I have offered many answers on working with database files (more specifically VFP, but the Microsoft VFP OleDb provider will recognize older dbase files. You can do a search to find more of these links via:</p>\n\n<p>user:74195[vfp][oledb]</p>\n\n<p>First, I would start with getting the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=14839" rel="nofollow noreferrer">Microsoft VFP OleDb Provider</a> download.</p>\n\n<p>Next, if you already have some dbf files you are trying to connect to for testing, you need to establish a connection. The connection must point to the PATH where the files are located, not the specific .dbf file. So, if you have a folder with 20 tables in it, once you connect to the PATH, you can query from any/all the tables via standard VFP-SQL Syntax (common with many sql the overall structure, but different based on some functions like string, date and number manipulations).</p>\n\n<p>Learn about PARAMETERIZING your queries. With VFP OleDb, parameters are done with the "?" character as a place-holder, so the parameters need to be added in the exact same sequence as they appear in the query. The "?" can appear as field values, join conditions, where criteria, etc.</p>\n\n<p>The following are a FEW to get you started to HOPEFULLY get you started with a valid connection, query, then insert/update/delete with parameters.</p>\n\n<ol>\n<li><p><a href="https://stackoverflow.com/questions/33746435/how-to-query-a-foxpro-dbf-file-with-ndx-index-file-using-the-oledb-driver-in-c/33746532#33746532">Sample showing a connection string and simple query from a table</a></p></li>\n<li><p><a href="https://stackoverflow.com/questions/32578233/create-dbf-file-from-sql-table-records/32696552#32696552">Shows a parameterized sql-insert</a>but in this case gets the data from another data source, such as sql-server and creating a VFP/dbf style table from it. It goes through cycling through records and pulling values for each parameter and inserting.</p></li>\n<li><p><a href="https://stackoverflow.com/questions/30648602/oledb-update-command-not-changing-data/30650636#30650636">and another showing parameterized SQL-update</a></p></li>\n</ol>\n\n<p>Good luck, and there are plenty of others who answer on VFP and OleDb Access, these are just some that I have specifically participated in and show functional implementations that may have something you may otherwise may have missed.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10333/'] |
75,712 | <p>I'm using membership and roles for authentication in my vb .net application. We have about 5 roles in the application with certain roles filling out a specific profile value. Example is the role is store and the profile value is store number. Obviously if you work for headquarters you don't have a store number so I don't care about it. Each store can also have more than 1 employee.</p>
<p>I need to get the users for a specific store number. Meaning I would only want the users that belong to store number 101 to show up that list. The way that we are doing this now is going through all the users and adding the users that fit the criteria into a sorted list. This functions but the problem is when you start passing about 3,000 users or so. It just becomes to slow to be any good. </p>
<p>How would you guys find a different way of doing it? I really don't want to do custom stored procedure or changing the underlying classes because I'm afraid of it all breaking on a later version of .net that they change membership and roles.</p>
| [{'answer_id': 75970, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 0, 'selected': False, 'text': "<p>You're using the built-in .NET role manager that saves to a SQL Server instance I take it? What format are your user object in when you're currently looking at them to evaluate the criteria? If you post a code sample I have an idea...</p>\n"}, {'answer_id': 75984, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 1, 'selected': False, 'text': "<p>This is really the sort of thing you want to filter on in SQL. I don't think there is any trick to get around doing a linear scan of your data and get the results you want.</p>\n\n<p>If doing this in SQL isn't an option then maybe you can avoid creating a second list and just sort your main user array and have the display only display the ones you care about. That would save the memory copy time at least.</p>\n"}, {'answer_id': 76517, 'author': 'Alfonso Pajares', 'author_id': 12369, 'author_profile': 'https://Stackoverflow.com/users/12369', 'pm_score': 0, 'selected': False, 'text': '<pre><code> Public Shared Function LoadALLUsersInRole(ByVal Code As Integer, ByVal Role As String) As ArrayList\n Dim pb As ProfileBase\n Dim usersArrayList As New ArrayList\n Dim i As Integer\n Dim AllUsersInRole() As String = Roles.GetUsersInRole(Role)\n\n For i = 0 To AllUsersInRole.Length - 1\n\n pb = ProfileBase.Create(AllUsersInRole(i), True)\n\n \'Check to see if the current user in the collect belongs to this Store.\n If CType(pb.GetPropertyValue("Store.Code"), Integer) = Code Then \n usersArrayList.Add(AllUsersInRole(i)) \n End If\n pb = Nothing\n Next\n\n Return usersArrayList\n End Function\n</code></pre>\n\n<p>That is the example code of how I\'m doing it. The reason that I don\'t want to do it on the SOL side is that I would have a huge dependency on the fact that membership and roles doesn\'t change.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12369/'] |
75,713 | <p>I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties.</p>
<p>Here's the class I'm using as a datasource:</p>
<pre><code>public interface IPerson
{
string UserId { get; set; }
string UserName { get; set; }
string Email { get; set; }
}
public class Person : EntityBase, IPerson
{
public virtual string UserId { get; set; }
public string UserName { get; set; }
public virtual string Email { get; set; }
}
</code></pre>
<p>Here's the XAML (an excerpt):</p>
<pre><code><TextBox Name="userIdTextBox" Text="{Binding UserId}" />
<TextBox Name="userNameTextBox" Text="{Binding UserName}" />
<TextBox Name="emailTextBox" Text="{Binding Email}" />
</code></pre>
<p>Here's the code behind (again, an excerpt):</p>
<pre><code>var person = PolicyInjection.Wrap<IPerson>(new Person());
person.UserId = "jdoe";
person.UserName = "John Doe";
person.Email = "[email protected]";
this.DataContext = person;
</code></pre>
<p>Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block.</p>
<p>I'm getting this error at runtime:</p>
<pre><code>System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'
</code></pre>
| [{'answer_id': 77322, 'author': 'Robert Jeppesen', 'author_id': 9436, 'author_profile': 'https://Stackoverflow.com/users/9436', 'pm_score': 3, 'selected': True, 'text': "<p>I'm not familiar with entlib's policy injection, but I'm pretty sure that your problem lies there, and not in the fact that you're using an interface.<br>\nIf you were to replace</p>\n\n<pre><code>var person = PolicyInjection.Wrap<IPerson>(new Person());\n</code></pre>\n\n<p>with </p>\n\n<pre><code>IPerson person = new Person();\n</code></pre>\n\n<p>surely it would work?</p>\n"}, {'answer_id': 77356, 'author': 'Senkwe', 'author_id': 6419, 'author_profile': 'https://Stackoverflow.com/users/6419', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t see much wrong with the code. Technically you\'re binding an instance of the Person class (ie it doesn\'t make sense to try and bind to an interface anyway) I don\'t know what your PolicyInjection.Wrap method does, but I\'m assuming it returns a concrete Person class? Anyway, I just tried this on my end and it works fine...</p>\n\n<pre><code>public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n IPerson person = new Person() { FirstName = "Hovito" };\n\n this.DataContext = person;\n }\n}\n\npublic class Person : IPerson\n{\n public virtual string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\npublic interface IPerson\n{\n string FirstName { get; set; }\n string LastName { get; set; }\n}\n</code></pre>\n\n<p>I would suggest you look into that PolicyInjection class a bit more. Find out if it really does return a Person type as you expect.</p>\n'}, {'answer_id': 77391, 'author': 'cranley', 'author_id': 10308, 'author_profile': 'https://Stackoverflow.com/users/10308', 'pm_score': 1, 'selected': False, 'text': "<p>We bind to almost nothing but Interfaces in our project, all without problem. The problem you're experiencing is due to entlib... but I'm not familiar enough with entlib to help you there. WPF can, however, bind to Interfaces.</p>\n"}, {'answer_id': 9040770, 'author': 'Philipp Munin', 'author_id': 508797, 'author_profile': 'https://Stackoverflow.com/users/508797', 'pm_score': 0, 'selected': False, 'text': '<p>Try to specify property path explicitly in your XAML:</p>\n\n<pre><code><TextBox Name="userIdTextBox" Text="{Binding (myns:IPerson.UserId)}" /> \n<TextBox Name="userNameTextBox" Text="{Binding (myns:IPerson.UserName)}" /> \n<TextBox Name="emailTextBox" Text="{Binding (myns:IPerson.Email)}" /> \n</code></pre>\n\n<p>I guess the type generated by policy injection is based on Person class, but is dynamic and internal. As far as I know XAML data binding engine can work only with public types.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6542/'] |
75,714 | <p>Note: I am using .Net 1.1, although I am not completely against answer that use higher versions.</p>
<p>I am displaying some dynamically generated objects in a PropertyGrid. These objects have numeric, text, and enumeration properties. Currently I am having issues setting the default value for the enumerations so that they don't always appear bold in the list. The enumerations themselves are also dynamically generated and appear to work fine with the exception of the default value.</p>
<p>First, I would like to show how I generate the enumerations in the case that it is causing the error. The first line uses a custom class to query the database. Simply replace this line with a DataAdapter or your preferred method of filling a DataSet with Database values. I am using the string values in column 1 to create my enumeration.</p>
<pre><code>private Type GetNewObjectType(string field, ModuleBuilder module, DatabaseAccess da)
//Query the database.
System.Data.DataSet ds = da.QueryDB(query);
EnumBuilder eb = module.DefineEnum(field, TypeAttributes.Public, typeof(int));
for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if(ds.Tables[0].Rows[i][1] != DBNull.Value)
{
string text = Convert.ToString(ds.Tables[0].Rows[i][1]);
eb.DefineLiteral(text, i);
}
}
return eb.CreateType();
</code></pre>
<p>Now on to how the type is created. This is largely based of the sample code provided <a href="http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx" rel="nofollow noreferrer">here</a>. Essentially, think of pFeature as a database row. We loop through the columns and use the column name as the new property name and use the column value as the default value; that is the goal at least.</p>
<pre><code>// create a dynamic assembly and module
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "tmpAssembly";
AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule");
// create a new type builder
TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class);
// Loop over the attributes that will be used as the properties names in out new type
for(int i = 0; i < pFeature.Fields.FieldCount; i++)
{
string propertyName = pFeature.Fields.get_Field(i).Name;
object val = pFeature.get_Value(i);
Type type = GetNewObjectType(propertyName, module, da);
// Generate a private field
FieldBuilder field = typeBuilder.DefineField("_" + propertyName, type, FieldAttributes.Private);
// Generate a public property
PropertyBuilder property =
typeBuilder.DefineProperty(propertyName,
PropertyAttributes.None,
type,
new Type[0]);
//Create the custom attribute to set the description.
Type[] ctorParams = new Type[] { typeof(string) };
ConstructorInfo classCtorInfo =
typeof(DescriptionAttribute).GetConstructor(ctorParams);
CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder(
classCtorInfo,
new object[] { "This is the long description of this property." });
property.SetCustomAttribute(myCABuilder);
//Set the default value.
ctorParams = new Type[] { type };
classCtorInfo = typeof(DefaultValueAttribute).GetConstructor(ctorParams);
if(type.IsEnum)
{
//val contains the text version of the enum. Parse it to the enumeration value.
object o = Enum.Parse(type, val.ToString(), true);
myCABuilder = new CustomAttributeBuilder(
classCtorInfo,
new object[] { o });
}
else
{
myCABuilder = new CustomAttributeBuilder(
classCtorInfo,
new object[] { val });
}
property.SetCustomAttribute(myCABuilder);
// The property set and property get methods require a special set of attributes:
MethodAttributes GetSetAttr =
MethodAttributes.Public |
MethodAttributes.HideBySig;
// Define the "get" accessor method for current private field.
MethodBuilder currGetPropMthdBldr =
typeBuilder.DefineMethod("get_value",
GetSetAttr,
type,
Type.EmptyTypes);
// Intermediate Language stuff...
ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for current private field.
MethodBuilder currSetPropMthdBldr =
typeBuilder.DefineMethod("set_value",
GetSetAttr,
null,
new Type[] { type });
// Again some Intermediate Language stuff...
ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
}
// Generate our type
Type generatedType = typeBuilder.CreateType();
</code></pre>
<p>Finally, we use that type to create an instance of it and load in the default values so we can later display it using the PropertiesGrid.</p>
<pre><code>// Now we have our type. Let's create an instance from it:
object generatedObject = Activator.CreateInstance(generatedType);
// Loop over all the generated properties, and assign the default values
PropertyInfo[] properties = generatedType.GetProperties();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(generatedType);
for(int i = 0; i < properties.Length; i++)
{
string field = properties[i].Name;
DefaultValueAttribute dva = (DefaultValueAttribute)props[field].Attributes[typeof(DefaultValueAttribute)];
object o = dva.Value;
Type pType = properties[i].PropertyType;
if(pType.IsEnum)
{
o = Enum.Parse(pType, o.ToString(), true);
}
else
{
o = Convert.ChangeType(o, pType);
}
properties[i].SetValue(generatedObject, o, null);
}
return generatedObject;
</code></pre>
<p>However, this causes an error when we try to get the default value for an enumeration. The DefaultValueAttribute dva does not get set and thus causes an exception when we try to use it.</p>
<p>If we change this code segment:</p>
<pre><code> if(type.IsEnum)
{
object o = Enum.Parse(type, val.ToString(), true);
myCABuilder = new CustomAttributeBuilder(
classCtorInfo,
new object[] { o });
}
</code></pre>
<p>to this:</p>
<pre><code> if(type.IsEnum)
{
myCABuilder = new CustomAttributeBuilder(
classCtorInfo,
new object[] { 0 });
}
</code></pre>
<p>There are no problems getting the DefaultValueAttribute dva; however, the field is then bolded in the PropertiesGrid because it does not match the default value.</p>
<p>Can anyone figure out why I cannot get the DefaultValueAttribute when I set the default value to my generated enumeration? As you can probably guess, I am still new to Reflection, so this is all pretty new to me.</p>
<p>Thanks.</p>
<p>Update: In response to alabamasucks.blogspot, using ShouldSerialize would certainly solve my problem. I was able to create the method using a normal class; however, I am unsure on how to do this for a generated type. From what I can figure out, I would need to use MethodBuilder and generate the IL to check if the field is equal to the default value. Sounds simple enough. I want to represent this in IL code:</p>
<pre><code>public bool ShouldSerializepropertyName()
{
return (field != val);
}
</code></pre>
<p>I was able to get the IL code using ildasm.exe from similar code, but I have a couple of questions. How do I use the val variable in the IL code? In my example, I used a int with the value of 0.</p>
<pre><code>IL_0000: ldc.i4.s 0
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldarg.0
IL_0005: ldfld int32 TestNamespace.TestClass::field
IL_000a: ceq
IL_000c: ldc.i4.0
IL_000d: ceq
IL_000f: stloc.1
IL_0010: br.s IL_0012
IL_0012: ldloc.1
IL_0013: ret
</code></pre>
<p>This certainly can get tricky because IL has a different load command for each type. Currently, I use ints, doubles, strings, and enumerations, so the code will have to be adaptive based on the type. </p>
<p>Does anyone have an idea how to do this? Or am I heading in the wrong direction?</p>
| [{'answer_id': 80194, 'author': 'Eric W', 'author_id': 14972, 'author_profile': 'https://Stackoverflow.com/users/14972', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not sure how to get the attribute to work, but there is another option that may be easier.</p>\n\n<p>In addition to checking for the DefaultValueAttribute, the PropertyGrid also uses reflection to look for a method named "ShouldSerializeProperty Name", where [Property Name] is the name of the property in question. This method should return a boolean that is true if the property is set to a non-default value and false otherwise. It would probably be easier for you to use reflection to create a method that returns the correct value then to fix up the attribute.</p>\n'}, {'answer_id': 201521, 'author': 'csgero', 'author_id': 21764, 'author_profile': 'https://Stackoverflow.com/users/21764', 'pm_score': 2, 'selected': False, 'text': '<p>You should try it with the DefaultValueAttribute taking a String and a Type parameter, passing in the string enum value (val.ToString), and the type of your enum.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
75,722 | <p>In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:</p>
<pre><code>using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// use sr, and have everything cleaned up when done.
}
}
}
</code></pre>
<p>In C++, I'm used to being able to use destructors to do it like this:</p>
<pre><code>{
FileStream fs("c:\file.txt", FileMode.Open);
BufferedStream bs(fs);
StreamReader sr(bs);
// use sr, and have everything cleaned up when done.
}
</code></pre>
<p>Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?</p>
| [{'answer_id': 75741, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': -1, 'selected': False, 'text': "<p>The using statement is syntactic sugar that converts to:</p>\n\n<pre><code> try\n {\n obj declaration\n ...\n }\n finally\n {\n obj.Dispose();\n }\n</code></pre>\n\n<p>You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.</p>\n"}, {'answer_id': 75751, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 1, 'selected': False, 'text': "<p>Instead of nesting using statements, you can just write out the .Dispose calls manually - but you'll almost certainly miss one at some point.</p>\n\n<p>Either run FxCop or something else that can make sure that all IDisposable-implementing type instances have a .Dispose() call, or deal with the nesting.</p>\n"}, {'answer_id': 75755, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 6, 'selected': True, 'text': '<p>You don\'t have to nest with multiple usings:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // all three get disposed when you\'re done\n}\n</code></pre>\n'}, {'answer_id': 75761, 'author': 'Bob Wintemberg', 'author_id': 12999, 'author_profile': 'https://Stackoverflow.com/users/12999', 'pm_score': 3, 'selected': False, 'text': '<p>You can put using statements together before the opening braces like so:</p>\n\n<pre><code> using (StreamWriter w1 = File.CreateText("W1"))\n using (StreamWriter w2 = File.CreateText("W2"))\n {\n // code here\n }\n</code></pre>\n\n<p><a href="http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx</a></p>\n'}, {'answer_id': 75764, 'author': 'JeffFoster', 'author_id': 9853, 'author_profile': 'https://Stackoverflow.com/users/9853', 'pm_score': 2, 'selected': False, 'text': '<p>You could use this syntax to condense things down a bit:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n}\n</code></pre>\n\n<p>This is one of those rare occasions where not using { } for all blocks makes sense IMHO.</p>\n'}, {'answer_id': 75778, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': '<p>you can omit the curly braces, like:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // use sr, and have everything cleaned up when done.\n}\n</code></pre>\n\n<p>or use the regular try finally approach:</p>\n\n<pre><code>FileStream fs = new FileStream("c:\\file.txt", FileMode.Open);\nBufferedStream bs = new BufferedStream(fs);\nStreamReader sr = new StreamReader(bs);\ntry\n{\n // use sr, and have everything cleaned up when done.\n}finally{\n sr.Close(); // should be enough since you hand control to the reader\n}\n</code></pre>\n'}, {'answer_id': 75836, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 0, 'selected': False, 'text': '<p>This makes for a much larger net plus in lines of code, but a tangible gain in readability:</p>\n\n<pre><code>using (StreamWrapper wrapper = new StreamWrapper("c:\\file.txt", FileMode.Open))\n{\n // do stuff using wrapper.Reader\n}\n</code></pre>\n\n<p>Where StreamWrapper is defined here:</p>\n\n<pre><code>private class StreamWrapper : IDisposable\n{\n private readonly FileStream fs;\n private readonly BufferedStream bs;\n private readonly StreamReader sr;\n\n public StreamWrapper(string fileName, FileMode mode)\n {\n fs = new FileStream(fileName, mode);\n bs = new BufferedStream(fs);\n sr = new StreamReader(bs);\n }\n\n public StreamReader Reader\n {\n get { return sr; }\n }\n\n public void Dispose()\n {\n sr.Dispose();\n bs.Dispose();\n fs.Dispose();\n }\n}\n</code></pre>\n\n<p>With some effort, StreamWrapper could be refactored to be more generic and reusable.</p>\n'}, {'answer_id': 76587, 'author': 'Jesse C. Slicer', 'author_id': 3312, 'author_profile': 'https://Stackoverflow.com/users/3312', 'pm_score': 1, 'selected': False, 'text': '<p>I have implemented solutions like <a href="https://stackoverflow.com/questions/75722/is-there-a-better-deterministic-disposal-pattern-than-nested-usings-in-c#75836">Michael Meadows</a>\'s before, but his <code>StreamWrapper</code> code doesn\'t take into account if the <code>Dispose()</code> methods called on the member variables throw an exception for one reason or another, the subsequent <code>Dispose()</code>es will not be called and resources could dangle. The safer way for that one to work is:</p>\n\n<pre><code> var exceptions = new List<Exception>();\n\n try\n {\n this.sr.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.bs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.fs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n if (exceptions.Count > 0)\n {\n throw new AggregateException(exceptions);\n }\n }\n</code></pre>\n'}, {'answer_id': 78362, 'author': 'Joel Lucsy', 'author_id': 645, 'author_profile': 'https://Stackoverflow.com/users/645', 'pm_score': 0, 'selected': False, 'text': '<p>It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:</p>\n\n<pre><code>using (Stream Reader sr = new StreamReader( new BufferedStream( new FileStream("c:\\file.txt", FileMode.Open))))\n{\n // all three get disposed when you\'re done\n}\n</code></pre>\n'}, {'answer_id': 6076898, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>for this example let us assume you have:</p>\n\n<p>a file named 1.xml under c:\\</p>\n\n<p>a textbox named textBox1, with the multi-line properties set ON.</p>\n\n<pre><code>const string fname = @"c:\\1.xml";\n\nStreamReader sr=new StreamReader(new BufferedStream(new FileStream(fname,FileMode.Open,FileAccess.Read,FileShare.Delete)));\ntextBox1.Text = sr.ReadToEnd();\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8701/'] |
75,732 | <p>I've seen numerous people mentions that you shouldn't use widths and padding or margins on the same element with CSS. Why is that?</p>
| [{'answer_id': 75758, 'author': 'Stephen Deken', 'author_id': 7154, 'author_profile': 'https://Stackoverflow.com/users/7154', 'pm_score': 4, 'selected': True, 'text': '<p>Because some browsers treat the width as the total width of the element including the padding and the margins, and others treat the width as the base width to which the padding and margins are added. As a result your design will look different in different browsers.</p>\n\n<p>For more information, see the <a href="http://www.w3.org/TR/CSS2/box.html" rel="noreferrer">W3C page on Box Model</a> and <a href="http://www.quirksmode.org/css/box.html" rel="noreferrer">quirksmode\'s take</a>.</p>\n'}, {'answer_id': 75789, 'author': 'Peter Boughton', 'author_id': 9360, 'author_profile': 'https://Stackoverflow.com/users/9360', 'pm_score': 2, 'selected': False, 'text': "<p>I've never come across a problem caused by using width, padding and/or margin together.</p>\n\n<p>So long as you have a valid DOCTYPE and are not in Quirks Mode, you will have a predictable box model and therefor should use whichever is most appropriate out of margin/padding to represent what you are trying to do.</p>\n\n<p>Note:\nMargin applies outside of borders, padding applies inside of borders.\nWidth means inner width of the container, the Total width = margin+border+padding+width (remembering that the first three are added for both left and right hand side).</p>\n"}, {'answer_id': 75797, 'author': 'Chris Serra', 'author_id': 13435, 'author_profile': 'https://Stackoverflow.com/users/13435', 'pm_score': 0, 'selected': False, 'text': "<p>Are you stating that padding and/or margin values shouldn't co-exist with a DOM element that also has a width value assigned to it? If so, that is only true if you do not want to write CSS that is compatible with both IE as well as browsers which implement web standards (e.g. Firefox). It would be difficult to achieve the layout you're looking for usually without some margin or padding value. But I suggest that you write CSS that is compatible for both browsers. If this is not what you are asking, then please correct me :)</p>\n"}, {'answer_id': 75811, 'author': 'spinodal', 'author_id': 11374, 'author_profile': 'https://Stackoverflow.com/users/11374', 'pm_score': 0, 'selected': False, 'text': '<p>The reason may be the famous <a href="http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug" rel="nofollow noreferrer">box model problem</a>.</p>\n\n<p>Summary: IE renders <em>width</em> different then the standard rendering if padding and margin used with width or height.</p>\n'}, {'answer_id': 75833, 'author': 'Jonathan Arkell', 'author_id': 11052, 'author_profile': 'https://Stackoverflow.com/users/11052', 'pm_score': 0, 'selected': False, 'text': '<p>I can think of 2 reasons:</p>\n\n<p>1) the old "box model" of IE is really flaky, so when you have an element with the style { width: 300px; padding: 30px; margin: 20px;} it\'s outline might not actually match up to the expected 400px (300 px size, plus 2 30px padding, plus 2 20 px margin. I think its actual width would be 340, as it rolls the padding into the width calculation.</p>\n\n<p>which brings is to...</p>\n\n<p>2) Some people find the calculations a little confusing. </p>\n\n<p>That said, I personally use widths along with padding and margins and have no problems with it. If you limit yourself to not using widths when using paddings/margins, that means you are peppering your code with a lot of non-semantic cruft. It does mean you have to be aware of what the various browsers are going to do with the element, but this is why we browsertest.</p>\n'}, {'answer_id': 76987, 'author': 'David Heggie', 'author_id': 4309, 'author_profile': 'https://Stackoverflow.com/users/4309', 'pm_score': 2, 'selected': False, 'text': '<p>A lot of people still cling to notions about faulty box-models in IE and reckon that if you start messing around with element widths, padding and margins, you\'re going to get into trouble.</p>\n\n<p>That\'s pretty outdated advice - assuming you\'re using <a href="http://alistapart.com/articles/doctype/" rel="nofollow noreferrer">a correct doctype</a>, all fairly modern browsers (including IE6+) will work to the same box model, and you shouldn\'t really have too many issues related to it.</p>\n\n<p>This being CSS, you will obviously have a million <em>other</em> cross-browser issues, but the infamous IE box-model is becoming a thing of the past.</p>\n'}, {'answer_id': 78455, 'author': 'nickf', 'author_id': 9021, 'author_profile': 'https://Stackoverflow.com/users/9021', 'pm_score': 0, 'selected': False, 'text': '<p>One important point to note is that it can make using percentage widths almost impossible. Take this for example, if you want your "content" div to take the full width, but have a 10px padding:</p>\n\n<pre><code>#content {\n width: 100%;\n padding: 0 10px;\n}\n</code></pre>\n\n<p>That works in the (sensible, but incorrect) IE model, but in standards compliant browsers your div will occupy a width of 100% + 20px which is no good. The solution is to use another "inner" container.</p>\n\n<pre><code><div id="content">\n <div class="inner">\n content here.\n </div>\n</div>\n\n#content {\n width: 100%;\n}\n#content .inner {\n padding: 0 10px;\n}\n</code></pre>\n\n<p>It\'s a bit annoying have the extra markup, but it makes a lot of things easier in the long run.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12930/'] |
75,746 | <pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
<p>I often find myself wanting to do things like this (<code>EmployeeNumber</code> is a <code>Nullable<int></code> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that</p>
<blockquote>
<p>There is no implicit conversion between 'null' and 'int'</p>
</blockquote>
<p>even though both types would be valid in an assignment operation to a nullable int on their own.</p>
<p>Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the <code>.Text</code> string if it's not null.</p>
<p>As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...</p>
<p>Does anyone know a more elegant solution?</p>
| [{'answer_id': 75795, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 2, 'selected': False, 'text': '<p>You can cast the output of Convert:</p>\n\n<pre><code>EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text)\n</code></pre>\n'}, {'answer_id': 75822, 'author': 'Alex Lyman', 'author_id': 5897, 'author_profile': 'https://Stackoverflow.com/users/5897', 'pm_score': 7, 'selected': True, 'text': "<p>The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a <code>null</code> and an <code>Int32</code>, and the type can not be determined (there are real reasons it can't just assume <code>Nullable<Int32></code>).</p>\n<p>If you really want to use it in this way, you must cast one of the values to <code>Nullable<Int32></code> yourself, so C# can resolve the type:</p>\n<pre><code>EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? (int?)null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n<p>or</p>\n<pre><code>EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n"}, {'answer_id': 75944, 'author': 'NerdFury', 'author_id': 6146, 'author_profile': 'https://Stackoverflow.com/users/6146', 'pm_score': 3, 'selected': False, 'text': '<p>I think a utility method could help make this cleaner.</p>\n\n<pre><code>public static class Convert\n{\n public static T? To<T>(string value, Converter<string, T> converter) where T: struct\n {\n return string.IsNullOrEmpty(value) ? null : (T?)converter(value);\n }\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);\n</code></pre>\n'}, {'answer_id': 76049, 'author': 'user13493', 'author_id': 13493, 'author_profile': 'https://Stackoverflow.com/users/13493', 'pm_score': 3, 'selected': False, 'text': "<p>While Alex provides the correct and proximal answer to your question, I prefer to use <code>TryParse</code>:</p>\n\n<pre><code>int value;\nint? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)\n ? (int?)value\n : null;\n</code></pre>\n\n<p>It's safer and takes care of cases of invalid input as well as your empty string scenario. Otherwise if the user inputs something like <code>1b</code> they will be presented with an error page with the unhandled exception caused in <code>Convert.ToInt32(string)</code>.</p>\n"}, {'answer_id': 29851598, 'author': 'Sandeep', 'author_id': 1604050, 'author_profile': 'https://Stackoverflow.com/users/1604050', 'pm_score': 1, 'selected': False, 'text': '<pre><code>//Some operation to populate Posid.I am not interested in zero or null\nint? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;\nvar x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;\n</code></pre>\n\n<p>EDIT: \nBrief explanation of above, I was trying to get the value of <code>Posid</code> (if its nonnull <code>int</code> and having value greater than 0) in varibale <code>X1</code>. I had to use <code>(int?)</code> on <code>Posid.Value</code> to get the conditional operator not throwing any compilation error.\nJust a FYI <code>GetHolidayCount</code> is a <code>WCF</code> method that could give <code>null</code> or any number.\nHope that helps</p>\n'}, {'answer_id': 62727948, 'author': 'Glorfindel', 'author_id': 4751173, 'author_profile': 'https://Stackoverflow.com/users/4751173', 'pm_score': 0, 'selected': False, 'text': '<p>As of <a href="https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed--and-" rel="nofollow noreferrer">C# 9.0</a>, this will finally be possible:</p>\n<blockquote>\n<h3>Target typed ?? and ?:</h3>\n<p>Sometimes conditional ?? and ?: expressions don’t have an obvious shared type between the branches. Such cases fail today, but C# 9.0 will allow them if there’s a target type that both branches convert to:</p>\n<pre><code>Person person = student ?? customer; // Shared base type\nint? result = b ? 0 : null; // nullable value type\n</code></pre>\n</blockquote>\n<p>That means the code block in the question will also compile without errors.</p>\n<pre><code>EmployeeNumber =\nstring.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12975/'] |
75,747 | <p>I've built a web part for Sharepoint that retrieves data from an external service. I'd like to display the items in a way that's UI-compatible with Sharepoint (fits in with its surroundings.)</p>
<p>I'm aware of the "DataFormWebPart" but was unable to get one working properly. It requires a valid DataSource and I was unable to build one from the results of a web service call... Part of the problem is that my web service wrappers don't expose the XML return info, rather I have a bunch of deserialized objects. There doesn't seem to be an easy way to turn actual objects into a datasource, or populate a "generic" datasource from object data.</p>
<p>I could use an SPGridView to get the same UI, but the grid control doesn't have much in the way of smarts -and- it forces every field into its own column. I'd prefer to render each list item as a single cell with complex rendering (for instance the way that StackOverflow shows its lists of questions.) I'd also like to get as much of the Sharepoint-standard UI as possible, such as the sorting, filtering, and paging controls.</p>
<p>So, first: Has anyone here written a Sharepoint control that does this, and if so do you have sample code to share? If not: am I overlooking some useful control, whether MS-supplied or available in an external library?</p>
<p>Thanks!
Steve</p>
| [{'answer_id': 76981, 'author': 'Nat', 'author_id': 13813, 'author_profile': 'https://Stackoverflow.com/users/13813', 'pm_score': 0, 'selected': False, 'text': '<p>Problem with SharePoint is that there are a bunch of different ways to do this. If your data is not changing too often and is not overly large it may be worth considering entering it into a list for display.\nIf you have the Enterprise licence it may be worth getting your data into the BDC and using it there. \nyou may have to convert the objects into xml or use the serialised objects with the XML webpart for display. This still has the issue of custom rendering using XSLT.</p>\n'}, {'answer_id': 78305, 'author': 'sachaa', 'author_id': 1152057, 'author_profile': 'https://Stackoverflow.com/users/1152057', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s a great article that explains how to configure BDC connections to web services using the BDC Definition Editor:</p>\n\n<p><strong>Creating a Web Service Connection by Using the Business Data Catalog Definition Editor</strong>\n<a href="http://msdn.microsoft.com/en-us/library/bb737887.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb737887.aspx</a></p>\n'}, {'answer_id': 79548, 'author': 'naspinski', 'author_id': 14777, 'author_profile': 'https://Stackoverflow.com/users/14777', 'pm_score': 0, 'selected': False, 'text': '<p>The best way to do this IMO is to make a Web Part. As a Web Part the UI will be automatically rendered to be the same as the theme the site is using (unless you override it) and it will be able to be placed anywhere by anyone with admin privileges.</p>\n\n<ul>\n<li><a href="http://www.naspinski.net/post/WSS-30MOSS-2007-Web-Part-Tutorial.aspx" rel="nofollow noreferrer">Tutorial on making a Web Part</a></li>\n<li><a href="http://naspinski.net/post/Packaging-and-Deploying-a-SharePoint-2007-Web-Part.aspx" rel="nofollow noreferrer">Tutorial on packaging and deploying a Web Part</a></li>\n<li><a href="http://naspinski.net/post/Free-SharePoint-2007-Web-Part-Time-Zones.aspx" rel="nofollow noreferrer">Example Web Part Source Code</a></li>\n</ul>\n'}, {'answer_id': 79624, 'author': 'Mashed Potato', 'author_id': 14396, 'author_profile': 'https://Stackoverflow.com/users/14396', 'pm_score': 3, 'selected': True, 'text': '<blockquote>\n <p>Sharepoint: Best way to display lists\n of non-Sharepoint content with\n “compatible” UI?</p>\n</blockquote>\n\n<p>Take a look at the built in sharepoint web controls:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.aspx" rel="nofollow noreferrer">Microsoft.SharePoint.WebControls Namespace</a></p>\n\n<p>It contains all the controls used in sharepoint. I\'d tell you more, but the documentation is very thorough.</p>\n'}, {'answer_id': 638211, 'author': 'LeonZandman', 'author_id': 76220, 'author_profile': 'https://Stackoverflow.com/users/76220', 'pm_score': 0, 'selected': False, 'text': '<p>You could create a custom web part and use an SPGridView. You say you don\'t like it, because it forces every field into its own column, but that\'s not true. You can create a template (ITemplate) for every column and fully customize what\'s shown inside it, just like you would using a normal ASP.Net GridView. Using this approach I\'ve added the little "New" images right next to a list item\'s Title, just like SharePoint does itself.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7104/'] |
75,752 | <p>I'm building a quick csv from a mysql table with a query like:</p>
<pre><code>select DATE(date),count(date) from table group by DATE(date) order by date asc;
</code></pre>
<p>and just dumping them to a file in perl over a:</p>
<pre><code>while(my($date,$sum) = $sth->fetchrow) {
print CSV "$date,$sum\n"
}
</code></pre>
<p>There are date gaps in the data, though:</p>
<pre><code>| 2008-08-05 | 4 |
| 2008-08-07 | 23 |
</code></pre>
<p>I would like to pad the data to fill in the missing days with zero-count entries to end up with:</p>
<pre><code>| 2008-08-05 | 4 |
| 2008-08-06 | 0 |
| 2008-08-07 | 23 |
</code></pre>
<p>I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. </p>
<p>Any genius ideas/slaps in the face for why me am being so dumb?</p>
<hr>
<p>I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons:</p>
<ul>
<li>I know the date range I'll be looking for every time</li>
<li>The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed</li>
</ul>
<p>The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!</p>
| [{'answer_id': 75807, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 3, 'selected': False, 'text': '<p>When I had to deal with this problem, to fill in missing dates I actually created a reference table that just contained all dates I\'m interested in and joined the data table on the date field. It\'s crude, but it works. </p>\n\n<pre><code>SELECT DATE(r.date),count(d.date) \nFROM dates AS r \nLEFT JOIN table AS d ON d.date = r.date \nGROUP BY DATE(r.date) \nORDER BY r.date ASC;\n</code></pre>\n\n<p>As for output, I\'d just use <a href="http://dev.mysql.com/doc/refman/5.0/en/select.html" rel="noreferrer">SELECT INTO OUTFILE</a> instead of generating the CSV by hand. Leaves us free from worrying about escaping special characters as well.</p>\n'}, {'answer_id': 75837, 'author': 'Ben', 'author_id': 11522, 'author_profile': 'https://Stackoverflow.com/users/11522', 'pm_score': -1, 'selected': False, 'text': "<p>I don't know if this would work, but how about if you created a new table which contained all the possible dates (that might be the problem with this idea, if the range of dates is going to change unpredictably...) and then do a left join on the two tables? I guess it's a crazy solution if there are a vast number of possible dates, or no way to predict the first and last date, but if the range of dates is either fixed or easy to work out, then this might work.</p>\n"}, {'answer_id': 75865, 'author': 'coffeepac', 'author_id': 13421, 'author_profile': 'https://Stackoverflow.com/users/13421', 'pm_score': 2, 'selected': False, 'text': '<p>not dumb, this isn\'t something that MySQL does, inserting the empty date values. I do this in perl with a two-step process. First, load all of the data from the query into a hash organised by date. Then, I create a Date::EzDate object and increment it by day, so...</p>\n\n<pre><code>my $current_date = Date::EzDate->new();\n$current_date->{\'default\'} = \'{YEAR}-{MONTH NUMBER BASE 1}-{DAY OF MONTH}\';\nwhile ($current_date <= $final_date)\n{\n print "$current_date\\t|\\t%hash_o_data{$current_date}"; # EzDate provides for automatic stringification in the format specfied in \'default\'\n $current_date++;\n}\n</code></pre>\n\n<p>where final date is another EzDate object or a string containing the end of your date range. </p>\n\n<p>EzDate isn\'t on CPAN right now, but you can probably find another perl mod that will do date compares and provide a date incrementor. </p>\n'}, {'answer_id': 75890, 'author': 'Alexandr Ciornii', 'author_id': 13467, 'author_profile': 'https://Stackoverflow.com/users/13467', 'pm_score': 0, 'selected': False, 'text': '<p>Use some Perl module to do date calculations, like recommended DateTime or Time::Piece (core from 5.10). Just increment date and print date and 0 until date will match current.</p>\n'}, {'answer_id': 75928, 'author': 'GSerg', 'author_id': 11683, 'author_profile': 'https://Stackoverflow.com/users/11683', 'pm_score': 5, 'selected': True, 'text': '<p>When you need something like that on server side, you usually create a table which contains all possible dates between two points in time, and then left join this table with query results. Something like this:</p>\n\n<pre class="lang-sql prettyprint-override"><code>create procedure sp1(d1 date, d2 date)\n declare d datetime;\n\n create temporary table foo (d date not null);\n\n set d = d1\n while d <= d2 do\n insert into foo (d) values (d)\n set d = date_add(d, interval 1 day)\n end while\n\n select foo.d, count(date)\n from foo left join table on foo.d = table.date\n group by foo.d order by foo.d asc;\n\n drop temporary table foo;\nend procedure\n</code></pre>\n\n<p>In this particular case it would be better to put a little check on the client side, if current date is not previos+1, put some addition strings.</p>\n'}, {'answer_id': 76081, 'author': '8jean', 'author_id': 10011, 'author_profile': 'https://Stackoverflow.com/users/10011', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a <a href="http://search.cpan.org/perldoc?DateTime" rel="nofollow noreferrer">DateTime</a> object:</p>\n\n<pre><code>use DateTime;\nmy $dt;\n\nwhile ( my ($date, $sum) = $sth->fetchrow ) {\n if (defined $dt) {\n print CSV $dt->ymd . ",0\\n" while $dt->add(days => 1)->ymd lt $date;\n }\n else {\n my ($y, $m, $d) = split /-/, $date;\n $dt = DateTime->new(year => $y, month => $m, day => $d);\n }\n print CSV, "$date,$sum\\n";\n}\n</code></pre>\n\n<p>What the above code does is it keeps the last printed date stored in a\n<code>DateTime</code> object <code>$dt</code>, and when the current date is more than one day\nin the future, it increments <code>$dt</code> by one day (and prints it a line to\n<code>CSV</code>) until it is the same as the current date.</p>\n\n<p>This way you don\'t need extra tables, and don\'t need to fetch all your\nrows in advance.</p>\n'}, {'answer_id': 76147, 'author': 'castaway', 'author_id': 4840, 'author_profile': 'https://Stackoverflow.com/users/4840', 'pm_score': 1, 'selected': False, 'text': '<p>Since you don\'t know where the gaps are, and yet you want all the values (presumably) from the first date in your list to the last one, do something like:</p>\n\n<pre><code>use DateTime;\nuse DateTime::Format::Strptime;\nmy @row = $sth->fetchrow;\nmy $countdate = strptime("%Y-%m-%d", $firstrow[0]);\nmy $thisdate = strptime("%Y-%m-%d", $firstrow[0]);\n\nwhile ($countdate) {\n # keep looping countdate until it hits the next db row date\n if(DateTime->compare($countdate, $thisdate) == -1) {\n # counter not reached next date yet\n print CSV $countdate->ymd . ",0\\n";\n $countdate = $countdate->add( days => 1 );\n $next;\n }\n\n # countdate is equal to next row\'s date, so print that instead\n print CSV $thisdate->ymd . ",$row[1]\\n";\n\n # increase both\n @row = $sth->fetchrow;\n $thisdate = strptime("%Y-%m-%d", $firstrow[0]);\n $countdate = $countdate->add( days => 1 );\n}\n</code></pre>\n\n<p>Hmm, that turned out to be more complicated than I thought it would be.. I hope it makes sense!</p>\n'}, {'answer_id': 6156000, 'author': 'theazureshadow', 'author_id': 177633, 'author_profile': 'https://Stackoverflow.com/users/177633', 'pm_score': 1, 'selected': False, 'text': "<p>I think the simplest general solution to the problem would be to create an <code>Ordinal</code> table with the highest number of rows that you need (in your case 31*3 = 93).</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS `Ordinal` (\n `n` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`n`)\n);\nINSERT INTO `Ordinal` (`n`)\nVALUES (NULL), (NULL), (NULL); #etc\n</code></pre>\n\n<p>Next, do a <code>LEFT JOIN</code> from <code>Ordinal</code> onto your data. Here's a simple case, getting every day in the last week:</p>\n\n<pre><code>SELECT CURDATE() - INTERVAL `n` DAY AS `day`\nFROM `Ordinal` WHERE `n` <= 7\nORDER BY `n` ASC\n</code></pre>\n\n<p>The two things you would need to change about this are the starting point and the interval. I have used <code>SET @var = 'value'</code> syntax for clarity.</p>\n\n<pre><code>SET @end = CURDATE() - INTERVAL DAY(CURDATE()) DAY;\nSET @begin = @end - INTERVAL 3 MONTH;\nSET @period = DATEDIFF(@end, @begin);\n\nSELECT @begin + INTERVAL (`n` + 1) DAY AS `date`\nFROM `Ordinal` WHERE `n` < @period\nORDER BY `n` ASC;\n</code></pre>\n\n<p>So the final code would look something like this, if you were joining to get the number of messages per day over the last three months:</p>\n\n<pre><code>SELECT COUNT(`msg`.`id`) AS `message_count`, `ord`.`date` FROM (\n SELECT ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH) + INTERVAL (`n` + 1) DAY AS `date`\n FROM `Ordinal`\n WHERE `n` < (DATEDIFF((CURDATE() - INTERVAL DAY(CURDATE()) DAY), ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH)))\n ORDER BY `n` ASC\n) AS `ord`\nLEFT JOIN `Message` AS `msg`\n ON `ord`.`date` = `msg`.`date`\nGROUP BY `ord`.`date`\n</code></pre>\n\n<p>Tips and Comments:</p>\n\n<ul>\n<li>Probably the hardest part of your query was determining the number of days to use when limiting <code>Ordinal</code>. By comparison, transforming that integer sequence into dates was easy.</li>\n<li>You can use <code>Ordinal</code> for all of your uninterrupted-sequence needs. Just make sure it contains more rows than your longest sequence.</li>\n<li>You can use multiple queries on <code>Ordinal</code> for multiple sequences, for example listing every weekday (1-5) for the past seven (1-7) weeks.</li>\n<li>You could make it faster by storing dates in your <code>Ordinal</code> table, but it would be less flexible. This way you only need one <code>Ordinal</code> table, no matter how many times you use it. Still, if the speed is worth it, try the <code>INSERT INTO ... SELECT</code> syntax.</li>\n</ul>\n"}, {'answer_id': 16318007, 'author': 'Igor Kryltsov', 'author_id': 1051674, 'author_profile': 'https://Stackoverflow.com/users/1051674', 'pm_score': 2, 'selected': False, 'text': "<p>I hope you will figure out the rest.</p>\n\n<pre><code>select * from (\nselect date_add('2003-01-01 00:00:00.000', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) as date from\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n1,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n2,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n3,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n4,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n5\n) a\nwhere date >'2011-01-02 00:00:00.000' and date < NOW()\norder by date\n</code></pre>\n\n<p>With </p>\n\n<pre><code>select n3.num*100+n2.num*10+n1.num as date\n</code></pre>\n\n<p>you will get a column with numbers from 0 to max(n3)*100+max(n2)*10+max(n1)</p>\n\n<p>Since here we have max n3 as 3, SELECT will return 399, plus 0 -> 400 records (dates in calendar).</p>\n\n<p>You can tune your dynamic calendar by limiting it, for example, from min(date) you have to now(). </p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13196/'] |
75,759 | <p>What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.</p>
| [{'answer_id': 75787, 'author': 'Jan Krüger', 'author_id': 12471, 'author_profile': 'https://Stackoverflow.com/users/12471', 'pm_score': 1, 'selected': False, 'text': "<p>Most people use symbols (that's the <code>:foo_bar</code> syntax). They're sort of unique opaque values. Symbols don't belong to any enum-style type so they're not really a faithful representation of C's enum type but this is pretty much as good as it gets.</p>\n"}, {'answer_id': 75801, 'author': 'emk', 'author_id': 12089, 'author_profile': 'https://Stackoverflow.com/users/12089', 'pm_score': 6, 'selected': False, 'text': "<p>The most idiomatic way to do this is to use symbols. For example, instead of:</p>\n\n<pre><code>enum {\n FOO,\n BAR,\n BAZ\n}\n\nmyFunc(FOO);\n</code></pre>\n\n<p>...you can just use symbols:</p>\n\n<pre><code># You don't actually need to declare these, of course--this is\n# just to show you what symbols look like.\n:foo\n:bar\n:baz\n\nmy_func(:foo)\n</code></pre>\n\n<p>This is a bit more open-ended than enums, but it fits well with the Ruby spirit.</p>\n\n<p>Symbols also perform very well. Comparing two symbols for equality, for example, is much faster than comparing two strings.</p>\n"}, {'answer_id': 76046, 'author': 'mlibby', 'author_id': 13468, 'author_profile': 'https://Stackoverflow.com/users/13468', 'pm_score': 9, 'selected': True, 'text': '<p>Two ways. Symbols (<code>:foo</code> notation) or constants (<code>FOO</code> notation).</p>\n<p>Symbols are appropriate when you want to enhance readability without littering code with literal strings.</p>\n<pre><code>postal_code[:minnesota] = "MN"\npostal_code[:new_york] = "NY"\n</code></pre>\n<p>Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.</p>\n<pre><code>module Foo\n BAR = 1\n BAZ = 2\n BIZ = 4\nend\n \nflags = Foo::BAR | Foo::BAZ # flags = 3\n</code></pre>\n<p>Added 2021-01-17</p>\n<p>If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there\'s a mashup of both approaches</p>\n<pre><code>COMMODITY_TYPE = {\n currency: 1,\n investment: 2,\n}\n\ndef commodity_type_string(value)\n COMMODITY_TYPE.key(value)\nend\n\nCOMMODITY_TYPE[:currency]\n</code></pre>\n<p>This approach inspired by andrew-grimm\'s answer <a href="https://stackoverflow.com/a/5332950/13468">https://stackoverflow.com/a/5332950/13468</a></p>\n<p>I\'d also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language\'s enum that you care about</p>\n'}, {'answer_id': 76722, 'author': 'mislav', 'author_id': 11687, 'author_profile': 'https://Stackoverflow.com/users/11687', 'pm_score': 2, 'selected': False, 'text': '<p>It all depends how you use Java or C# enums. How you use it will dictate the solution you\'ll choose in Ruby.</p>\n\n<p>Try the native <code>Set</code> type, for instance:</p>\n\n<pre><code>>> enum = Set[\'a\', \'b\', \'c\']\n=> #<Set: {"a", "b", "c"}>\n>> enum.member? "b"\n=> true\n>> enum.member? "d"\n=> false\n>> enum.add? "b"\n=> nil\n>> enum.add? "d"\n=> #<Set: {"a", "b", "c", "d"}>\n</code></pre>\n'}, {'answer_id': 164514, 'author': 'Jonke', 'author_id': 15638, 'author_profile': 'https://Stackoverflow.com/users/15638', 'pm_score': 2, 'selected': False, 'text': "<p>Symbols is the ruby way. However, sometimes one need to talk to some C code or something or Java that expose some enum for various things.</p>\n\n<hr>\n\n<pre><code>#server_roles.rb\nmodule EnumLike\n\n def EnumLike.server_role\n server_Symb=[ :SERVER_CLOUD, :SERVER_DESKTOP, :SERVER_WORKSTATION]\n server_Enum=Hash.new\n i=0\n server_Symb.each{ |e| server_Enum[e]=i; i +=1}\n return server_Symb,server_Enum\n end\n\nend\n</code></pre>\n\n<hr>\n\n<p>This can then be used like this</p>\n\n<hr>\n\n<pre><code>require 'server_roles'\n\nsSymb, sEnum =EnumLike.server_role()\n\nforeignvec[sEnum[:SERVER_WORKSTATION]]=8\n</code></pre>\n\n<hr>\n\n<p>This is can of course be made abstract and you can roll our own Enum class </p>\n"}, {'answer_id': 612357, 'author': 'dlamblin', 'author_id': 459, 'author_profile': 'https://Stackoverflow.com/users/459', 'pm_score': 2, 'selected': False, 'text': '<p>Someone went ahead and wrote a ruby gem called <a href="http://renum.rubyforge.org/" rel="nofollow noreferrer">Renum</a>. It claims to get the closest Java/C# like behavior. Personally I\'m still learning Ruby, and I was a little shocked when I wanted to make a specific class contain a static enum, possibly a hash, that it wasn\'t exactly easily found via google.</p>\n'}, {'answer_id': 1494092, 'author': 'Philippe Monnet', 'author_id': 23308, 'author_profile': 'https://Stackoverflow.com/users/23308', 'pm_score': 0, 'selected': False, 'text': '<p>Another approach is to use a Ruby class with a hash containing names and values as described in the following <a href="http://www.rubyfleebie.com/enumerations-and-ruby/" rel="nofollow noreferrer">RubyFleebie blog post</a>. This allows you to convert easily between values and constants (especially if you add a class method to lookup the name for a given value).</p>\n'}, {'answer_id': 2573093, 'author': 'goreorto', 'author_id': 308517, 'author_profile': 'https://Stackoverflow.com/users/308517', 'pm_score': 0, 'selected': False, 'text': "<p>I think the best way to implement enumeration like types is with symbols since the pretty much behave as integer (when it comes to performace, object_id is used to make comparisons ); you don't need to worry about indexing and they look really neat in your code xD</p>\n"}, {'answer_id': 5332215, 'author': 'dB.', 'author_id': 123094, 'author_profile': 'https://Stackoverflow.com/users/123094', 'pm_score': 3, 'selected': False, 'text': '<p>Check out the ruby-enum gem, <a href="https://github.com/dblock/ruby-enum" rel="noreferrer">https://github.com/dblock/ruby-enum</a>.</p>\n\n<pre><code>class Gender\n include Enum\n\n Gender.define :MALE, "male"\n Gender.define :FEMALE, "female"\nend\n\nGender.all\nGender::MALE\n</code></pre>\n'}, {'answer_id': 5332950, 'author': 'Andrew Grimm', 'author_id': 38765, 'author_profile': 'https://Stackoverflow.com/users/38765', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re worried about typos with symbols, make sure your code raises an exception when you access a value with a non-existent key. You can do this by using <code>fetch</code> rather than <code>[]</code>:</p>\n\n<pre><code>my_value = my_hash.fetch(:key)\n</code></pre>\n\n<p>or by making the hash raise an exception by default if you supply a non-existent key:</p>\n\n<pre><code>my_hash = Hash.new do |hash, key|\n raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"\nend\n</code></pre>\n\n<p>If the hash already exists, you can add on exception-raising behaviour:</p>\n\n<pre><code>my_hash = Hash[[[1,2]]]\nmy_hash.default_proc = proc do |hash, key|\n raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"\nend\n</code></pre>\n\n<p>Normally, you don\'t have to worry about typo safety with constants. If you misspell a constant name, it\'ll usually raise an exception.</p>\n'}, {'answer_id': 5675566, 'author': 'Alexey', 'author_id': 126529, 'author_profile': 'https://Stackoverflow.com/users/126529', 'pm_score': 6, 'selected': False, 'text': "<p>I use the following approach:</p>\n\n<pre><code>class MyClass\n MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']\nend\n</code></pre>\n\n<p>I like it for the following advantages:</p>\n\n<ol>\n<li>It groups values visually as one whole</li>\n<li>It does some compilation-time checking (in contrast with just using symbols)</li>\n<li>I can easily access the list of all possible values: just <code>MY_ENUM</code></li>\n<li>I can easily access distinct values: <code>MY_VALUE_1</code></li>\n<li>It can have values of any type, not just Symbol</li>\n</ol>\n\n<p>Symbols may be better cause you don't have to write the name of outer class, if you are using it in another class (<code>MyClass::MY_VALUE_1</code>)</p>\n"}, {'answer_id': 6170494, 'author': 'Charles', 'author_id': 48483, 'author_profile': 'https://Stackoverflow.com/users/48483', 'pm_score': 6, 'selected': False, 'text': '<p>I\'m surprised that no one has offered something like the following (harvested from the <a href="https://github.com/cstrahan/rapi/blob/master/lib/rapi.rb" rel="noreferrer">RAPI</a> gem):</p>\n\n<pre><code>class Enum\n\n private\n\n def self.enum_attr(name, num)\n name = name.to_s\n\n define_method(name + \'?\') do\n @attrs & num != 0\n end\n\n define_method(name + \'=\') do |set|\n if set\n @attrs |= num\n else\n @attrs &= ~num\n end\n end\n end\n\n public\n\n def initialize(attrs = 0)\n @attrs = attrs\n end\n\n def to_i\n @attrs\n end\nend\n</code></pre>\n\n<p>Which can be used like so:</p>\n\n<pre><code>class FileAttributes < Enum\n enum_attr :readonly, 0x0001\n enum_attr :hidden, 0x0002\n enum_attr :system, 0x0004\n enum_attr :directory, 0x0010\n enum_attr :archive, 0x0020\n enum_attr :in_rom, 0x0040\n enum_attr :normal, 0x0080\n enum_attr :temporary, 0x0100\n enum_attr :sparse, 0x0200\n enum_attr :reparse_point, 0x0400\n enum_attr :compressed, 0x0800\n enum_attr :rom_module, 0x2000\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>>> example = FileAttributes.new(3)\n=> #<FileAttributes:0x629d90 @attrs=3>\n>> example.readonly?\n=> true\n>> example.hidden?\n=> true\n>> example.system?\n=> false\n>> example.system = true\n=> true\n>> example.system?\n=> true\n>> example.to_i\n=> 7\n</code></pre>\n\n<p>This plays well in database scenarios, or when dealing with C style constants/enums (as is the case when using <a href="https://github.com/ffi/ffi/" rel="noreferrer">FFI</a>, which RAPI makes extensive use of).</p>\n\n<p>Also, you don\'t have to worry about typos causing silent failures, as you would with using a hash-type solution.</p>\n'}, {'answer_id': 9482922, 'author': 'Masuschi', 'author_id': 1238002, 'author_profile': 'https://Stackoverflow.com/users/1238002', 'pm_score': 2, 'selected': False, 'text': '<p>I have implemented enums like that </p>\n\n<pre><code>module EnumType\n\n def self.find_by_id id\n if id.instance_of? String\n id = id.to_i\n end \n values.each do |type|\n if id == type.id\n return type\n end\n end\n nil\n end\n\n def self.values\n [@ENUM_1, @ENUM_2] \n end\n\n class Enum\n attr_reader :id, :label\n\n def initialize id, label\n @id = id\n @label = label\n end\n end\n\n @ENUM_1 = Enum.new(1, "first")\n @ENUM_2 = Enum.new(2, "second")\n\nend\n</code></pre>\n\n<p>then its easy to do operations </p>\n\n<pre><code>EnumType.ENUM_1.label\n</code></pre>\n\n<p>...</p>\n\n<pre><code>enum = EnumType.find_by_id 1\n</code></pre>\n\n<p>...</p>\n\n<pre><code>valueArray = EnumType.values\n</code></pre>\n'}, {'answer_id': 9582957, 'author': 'Anu', 'author_id': 1252072, 'author_profile': 'https://Stackoverflow.com/users/1252072', 'pm_score': 1, 'selected': False, 'text': '<pre><code>irb(main):016:0> num=[1,2,3,4]\nirb(main):017:0> alph=[\'a\',\'b\',\'c\',\'d\']\nirb(main):018:0> l_enum=alph.to_enum\nirb(main):019:0> s_enum=num.to_enum\nirb(main):020:0> loop do\nirb(main):021:1* puts "#{s_enum.next} - #{l_enum.next}"\nirb(main):022:1> end\n</code></pre>\n\n<p>Output:</p>\n\n<p>1 - a<br>\n2 - b<br>\n3 - c<br>\n4 - d</p>\n'}, {'answer_id': 11432676, 'author': 'Hossein', 'author_id': 1107992, 'author_profile': 'https://Stackoverflow.com/users/1107992', 'pm_score': 2, 'selected': False, 'text': '<pre><code>module Status\n BAD = 13\n GOOD = 24\n\n def self.to_str(status)\n for sym in self.constants\n if self.const_get(sym) == status\n return sym.to_s\n end\n end\n end\n\nend\n\n\nmystatus = Status::GOOD\n\nputs Status::to_str(mystatus)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>GOOD\n</code></pre>\n'}, {'answer_id': 11455651, 'author': 'johnnypez', 'author_id': 366277, 'author_profile': 'https://Stackoverflow.com/users/366277', 'pm_score': 4, 'selected': False, 'text': "<p>This is my approach to enums in Ruby. I was going for short and sweet, not necessarily the the most C-like. Any thoughts?</p>\n<pre><code>module Kernel\n def enum(values)\n Module.new do |mod|\n values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }\n\n def mod.inspect\n "#{self.name} {#{self.constants.join(', ')}}"\n end\n end\n end\nend\n\nStates = enum %w(Draft Published Trashed)\n=> States {Draft, Published, Trashed} \n\nStates::Draft\n=> 1\n\nStates::Published\n=> 2\n\nStates::Trashed\n=> 4\n\nStates::Draft | States::Trashed\n=> 5\n</code></pre>\n"}, {'answer_id': 13764335, 'author': 'Oded Niv', 'author_id': 1056158, 'author_profile': 'https://Stackoverflow.com/users/1056158', 'pm_score': 4, 'selected': False, 'text': '<p>I know it\'s been a long time since the guy posted this question, but I had the same question and this post didn\'t give me the answer. I wanted an easy way to see what the number represents, easy comparison, and most of all ActiveRecord support for lookup using the column representing the enum.</p>\n\n<p>I didn\'t find anything, so I made an awesome implementation called <a href="https://github.com/toplex/enum" rel="nofollow noreferrer">yinum</a> which allowed everything I was looking for. Made ton of specs, so I\'m pretty sure it\'s safe.</p>\n\n<p>Some example features:</p>\n\n<pre><code>COLORS = Enum.new(:COLORS, :red => 1, :green => 2, :blue => 3)\n=> COLORS(:red => 1, :green => 2, :blue => 3)\nCOLORS.red == 1 && COLORS.red == :red\n=> true\n\nclass Car < ActiveRecord::Base \n attr_enum :color, :COLORS, :red => 1, :black => 2\nend\ncar = Car.new\ncar.color = :red / "red" / 1 / "1"\ncar.color\n=> Car::COLORS.red\ncar.color.black?\n=> false\nCar.red.to_sql\n=> "SELECT `cars`.* FROM `cars` WHERE `cars`.`color` = 1"\nCar.last.red?\n=> true\n</code></pre>\n'}, {'answer_id': 14087590, 'author': 'Daniel Doubleday', 'author_id': 1104754, 'author_profile': 'https://Stackoverflow.com/users/1104754', 'pm_score': 0, 'selected': False, 'text': '<p>Another way to mimic an enum with consistent equality handling (shamelessly adopted from Dave Thomas). Allows open enums (much like symbols) and closed (predefined) enums.</p>\n\n<pre><code>class Enum\n def self.new(values = nil)\n enum = Class.new do\n unless values\n def self.const_missing(name)\n const_set(name, new(name))\n end\n end\n\n def initialize(name)\n @enum_name = name\n end\n\n def to_s\n "#{self.class}::#@enum_name"\n end\n end\n\n if values\n enum.instance_eval do\n values.each { |e| const_set(e, enum.new(e)) }\n end\n end\n\n enum\n end\nend\n\nGenre = Enum.new %w(Gothic Metal) # creates closed enum\nArchitecture = Enum.new # creates open enum\n\nGenre::Gothic == Genre::Gothic # => true\nGenre::Gothic != Architecture::Gothic # => true\n</code></pre>\n'}, {'answer_id': 16046129, 'author': 'jjk', 'author_id': 1965639, 'author_profile': 'https://Stackoverflow.com/users/1965639', 'pm_score': 2, 'selected': False, 'text': '<p>This seems a bit superfluous, but this is a methodology that I have used a few times, especially where I am integrating with xml or some such.</p>\n\n<pre><code>#model\nclass Profession\n def self.pro_enum\n {:BAKER => 0, \n :MANAGER => 1, \n :FIREMAN => 2, \n :DEV => 3, \n :VAL => ["BAKER", "MANAGER", "FIREMAN", "DEV"]\n }\n end\nend\n\nProfession.pro_enum[:DEV] #=>3\nProfession.pro_enum[:VAL][1] #=>MANAGER\n</code></pre>\n\n<p>This gives me the rigor of a c# enum and it is tied to the model.</p>\n'}, {'answer_id': 27349423, 'author': 'Vedant Agarwala', 'author_id': 1396264, 'author_profile': 'https://Stackoverflow.com/users/1396264', 'pm_score': 4, 'selected': False, 'text': '<p>If you are using Rails 4.2 or greater you can use Rails enums.</p>\n\n<p>Rails now has enums by default without the need for including any gems.</p>\n\n<p>This is very similar (and more with features) to Java, C++ enums.</p>\n\n<p>Quoted from <a href="http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html" rel="noreferrer">http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html</a> :</p>\n\n<pre><code>class Conversation < ActiveRecord::Base\n enum status: [ :active, :archived ]\nend\n\n# conversation.update! status: 0\nconversation.active!\nconversation.active? # => true\nconversation.status # => "active"\n\n# conversation.update! status: 1\nconversation.archived!\nconversation.archived? # => true\nconversation.status # => "archived"\n\n# conversation.update! status: 1\nconversation.status = "archived"\n\n# conversation.update! status: nil\nconversation.status = nil\nconversation.status.nil? # => true\nconversation.status # => nil\n</code></pre>\n'}, {'answer_id': 27574382, 'author': 'Daniel Lubarov', 'author_id': 714009, 'author_profile': 'https://Stackoverflow.com/users/714009', 'pm_score': 3, 'selected': False, 'text': "<p>Perhaps the best lightweight approach would be</p>\n\n<pre><code>module MyConstants\n ABC = Class.new\n DEF = Class.new\n GHI = Class.new\nend\n</code></pre>\n\n<p>This way values have associated names, as in Java/C#:</p>\n\n<pre><code>MyConstants::ABC\n=> MyConstants::ABC\n</code></pre>\n\n<p>To get all values, you can do</p>\n\n<pre><code>MyConstants.constants\n=> [:ABC, :DEF, :GHI] \n</code></pre>\n\n<p>If you want an enum's ordinal value, you can do</p>\n\n<pre><code>MyConstants.constants.index :GHI\n=> 2\n</code></pre>\n"}, {'answer_id': 32149803, 'author': 'dark_src', 'author_id': 371572, 'author_profile': 'https://Stackoverflow.com/users/371572', 'pm_score': 1, 'selected': False, 'text': '<p>Sometimes all I need is to be able to fetch enum\'s value and identify its name similar to java world.</p>\n\n<pre><code>module Enum\n def get_value(str)\n const_get(str)\n end\n def get_name(sym)\n sym.to_s.upcase\n end\n end\n\n class Fruits\n include Enum\n APPLE = "Delicious"\n MANGO = "Sweet"\n end\n\n Fruits.get_value(\'APPLE\') #\'Delicious\'\n Fruits.get_value(\'MANGO\') # \'Sweet\'\n\n Fruits.get_name(:apple) # \'APPLE\'\n Fruits.get_name(:mango) # \'MANGO\'\n</code></pre>\n\n<p>This to me serves the purpose of enum and keeps it very extensible too. You can add more methods to the Enum class and viola get them for free in all the defined enums. for example. get_all_names and stuff like that.</p>\n'}, {'answer_id': 34498312, 'author': 'ka8725', 'author_id': 1178074, 'author_profile': 'https://Stackoverflow.com/users/1178074', 'pm_score': 2, 'selected': False, 'text': '<p>Recently we released a <a href="https://github.com/mezuka/enum" rel="nofollow">gem</a> that implements <strong>Enums in Ruby</strong>. In my <a href="http://railsguides.net/safe-enums-in-ruby/" rel="nofollow">post</a> you will find the answers on your questions. Also I described there why our implementation is better than existing ones (actually there are many implementations of this feature in Ruby yet as gems). </p>\n'}, {'answer_id': 45097718, 'author': 'Roger', 'author_id': 549010, 'author_profile': 'https://Stackoverflow.com/users/549010', 'pm_score': 3, 'selected': False, 'text': '<p>Another solution is using OpenStruct. Its pretty straight forward and clean.</p>\n\n<p><a href="https://ruby-doc.org/stdlib-2.3.1/libdoc/ostruct/rdoc/OpenStruct.html" rel="noreferrer">https://ruby-doc.org/stdlib-2.3.1/libdoc/ostruct/rdoc/OpenStruct.html</a></p>\n\n<p>Example:</p>\n\n<pre><code># bar.rb\nrequire \'ostruct\' # not needed when using Rails\n\n# by patching Array you have a simple way of creating a ENUM-style\nclass Array\n def to_enum(base=0)\n OpenStruct.new(map.with_index(base).to_h)\n end\nend\n\nclass Bar\n\n MY_ENUM = OpenStruct.new(ONE: 1, TWO: 2, THREE: 3)\n MY_ENUM2 = %w[ONE TWO THREE].to_enum\n\n def use_enum (value)\n case value\n when MY_ENUM.ONE\n puts "Hello, this is ENUM 1"\n when MY_ENUM.TWO\n puts "Hello, this is ENUM 2"\n when MY_ENUM.THREE\n puts "Hello, this is ENUM 3"\n else\n puts "#{value} not found in ENUM"\n end\n end\n\nend\n\n# usage\nfoo = Bar.new \nfoo.use_enum 1\nfoo.use_enum 2\nfoo.use_enum 9\n\n\n# put this code in a file \'bar.rb\', start IRB and type: load \'bar.rb\'\n</code></pre>\n'}, {'answer_id': 48199917, 'author': 'horun', 'author_id': 3940165, 'author_profile': 'https://Stackoverflow.com/users/3940165', 'pm_score': 1, 'selected': False, 'text': '<p>Try the inum.\n<a href="https://github.com/alfa-jpn/inum" rel="nofollow noreferrer">https://github.com/alfa-jpn/inum</a></p>\n\n<pre class="lang-js prettyprint-override"><code>class Color < Inum::Base\n define :RED\n define :GREEN\n define :BLUE\nend\n</code></pre>\n\n<pre class="lang-js prettyprint-override"><code>Color::RED \nColor.parse(\'blue\') # => Color::BLUE\nColor.parse(2) # => Color::GREEN\n</code></pre>\n\n<p>see more <a href="https://github.com/alfa-jpn/inum#usage" rel="nofollow noreferrer">https://github.com/alfa-jpn/inum#usage</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4110/'] |
75,763 | <p>1.exe doesn't give enough time for me to launch the IDE and attach 1.exe to the debugger to break into.</p>
| [{'answer_id': 75799, 'author': 'Clinton Pierce', 'author_id': 8173, 'author_profile': 'https://Stackoverflow.com/users/8173', 'pm_score': 0, 'selected': False, 'text': "<p>I assume you have the source to 1.exe (if you're debugging it), then just insert a statement near the beginning that will cause it to hang around long enough to attach a debugger. ( getch() if you're desperate and it's not interactive. )</p>\n\n<p>After the attach, just skip to the next statement and let it go.</p>\n"}, {'answer_id': 75803, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 0, 'selected': False, 'text': '<p>You could put in some preprocessor commands for debug builds - just remember to build your release in release mode:</p>\n\n<pre><code>#ifdef DEBUG\nThread.Sleep(10000);\n#endif\n</code></pre>\n'}, {'answer_id': 75814, 'author': 'Alex Duggleby', 'author_id': 5790, 'author_profile': 'https://Stackoverflow.com/users/5790', 'pm_score': 3, 'selected': False, 'text': '<p>I would suggest taking the same approach as with NT services in this case. They will also start and usually not give you enough time to attach the debugger for the start-up routines.</p>\n\n<p>Details are described here: <a href="http://www.debuginfo.com/articles/debugstartup.html" rel="noreferrer">http://www.debuginfo.com/articles/debugstartup.html</a></p>\n\n<p>In short you add a registry entry for the second exe:</p>\n\n<blockquote>\n <p>HKLM\\Software\\Microsoft\\Windows\n NT\\CurrentVersion\\Image File Execution\n Options\\2.exe Debugger =\n "c:\\progs\\msvs\\common7\\ide\\devenv.exe\n /debugexe" (REG_SZ)</p>\n</blockquote>\n\n<p>Change the c:\\progrs\\msms\\ to match your settings.</p>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 75854, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 0, 'selected': False, 'text': '<p>How is 1.exe launched? If you can launch it using CreateProcess(), you can start the process in a suspended state, attach the debugger, then release the new process.</p>\n'}, {'answer_id': 75876, 'author': 'Michael Ratanapintha', 'author_id': 1879, 'author_profile': 'https://Stackoverflow.com/users/1879', 'pm_score': 0, 'selected': False, 'text': '<p>If you are willing to consider a debugger other than Visual Studio, <a href="http://www.microsoft.com/whdc/devtools/debugging/install64bit.mspx" rel="nofollow noreferrer">WinDBG</a> can auto-debug child processes (native code only).</p>\n'}, {'answer_id': 76367, 'author': 'Alex Reitbort', 'author_id': 11525, 'author_profile': 'https://Stackoverflow.com/users/11525', 'pm_score': 0, 'selected': False, 'text': '<p>You did not mention what language you are using. But if you using C# or VB.NET you can add Debug.Break() or Stop to trigger the prompt to attach debugger to the process.</p>\n\n<p>Or as mentioned above just use something like Console.Readline() or MessageBox.Show() to pause starting of process untill you can attach debugger to it.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13432/'] |
75,777 | <p>I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter.</p>
<p>Then I read on the SDK: </p>
<blockquote>
<p>Setting the Margin property on a
docked control has no effect on the
distance of the control from the the
edges of its container.</p>
</blockquote>
<p>Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?</p>
| [{'answer_id': 75850, 'author': 'Philip Rieck', 'author_id': 12643, 'author_profile': 'https://Stackoverflow.com/users/12643', 'pm_score': 4, 'selected': True, 'text': '<p>The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit. However, it is best used for spacing just as you assume. Just read the documentation for that specific layout engine.</p>\n\n<p>It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit. Obviously, if you write a custom layout provider, you can use Margin however you see fit.</p>\n'}, {'answer_id': 75911, 'author': 'OwenP', 'author_id': 2547, 'author_profile': 'https://Stackoverflow.com/users/2547', 'pm_score': 3, 'selected': False, 'text': '<p>Like Philip Rieck said, the margin property is only respected by container controls that perform layout. Here\'s an example that makes it fairly clear how the <code>TableLayoutPanel</code> respects the Margin property:</p>\n\n<pre><code>using System.Drawing;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n\n TableLayoutPanel pnl = new TableLayoutPanel();\n pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));\n pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));\n pnl.Dock = DockStyle.Fill;\n this.Controls.Add(pnl);\n\n Button btn1 = new Button();\n btn1.Text = "No margin";\n btn1.Dock = DockStyle.Fill;\n\n Button btn2 = new Button();\n btn2.Margin = new Padding(25);\n btn2.Text = "Margin";\n btn2.Dock = DockStyle.Fill;\n\n pnl.Controls.Add(btn1, 0, 0);\n pnl.Controls.Add(btn2, 1, 0);\n }\n }\n}</code></pre>\n\n<p>I believe the only .NET 2.0 built-in controls that respect this property are <code>FlowLayoutPanel</code> and <code>TableLayoutPanel</code>; hopefully third-party components respect it as well. It has basically no effect in other scenarios.</p>\n'}, {'answer_id': 47569131, 'author': 'Pavel K', 'author_id': 1948038, 'author_profile': 'https://Stackoverflow.com/users/1948038', 'pm_score': 0, 'selected': False, 'text': '<p>Control.Margin property could be also useful at design time if you do not use layout container, but rather place controls manually.</p>\n\n<p>It affects the distance between manually dragged controls at which <a href="https://stackoverflow.com/questions/1376622/change-spacing-of-snaplines-in-visual-studio#answer-15649647">snaplines appear</a>.</p>\n\n<p>E.g. for default margin value of 3 for text box you would have this snaplines:</p>\n\n<p><a href="https://i.stack.imgur.com/HR89v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HR89v.png" alt="enter image description here"></a></p>\n\n<p>And for margin of 10 - these (label has margin of 3 in both cases):</p>\n\n<p><a href="https://i.stack.imgur.com/rlKfs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rlKfs.png" alt="enter image description here"></a></p>\n\n<p>So if you have some strict guidelines for you UI then you just set the margins as you need and drag controls to the snaplines.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12597/'] |
75,785 | <p>Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.</p>
<p>Related resources:</p>
<ul>
<li><a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a></li>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/</a></li>
</ul>
| [{'answer_id': 84987, 'author': 'Philip Rieck', 'author_id': 12643, 'author_profile': 'https://Stackoverflow.com/users/12643', 'pm_score': 8, 'selected': True, 'text': '<p><strong>Please Note:</strong> This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I\'ll keep the code here (and possibly update it), I\'ve also <strong>created a <a href="https://github.com/PhilipRieck/WpfAppBar" rel="noreferrer">WpfAppBar project on github</a></strong>. Feel free to send pull requests. </p>\n\n<p>That same project also builds to a <a href="https://www.nuget.org/packages/WpfAppBar/" rel="noreferrer">WpfAppBar nuget package</a> </p>\n\n<hr>\n\n<p>I took the code from the first link provided in the question ( <a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a> ) and modified it to do two things:</p>\n\n<ol>\n<li>Work with WPF</li>\n<li>Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window.</li>\n</ol>\n\n<p>This approach doesn\'t create a base class.</p>\n\n<p>To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn\'t been created yet (like in the constructor), an error will occur.</p>\n\n<p>Make the window an appbar:</p>\n\n<pre><code>AppBarFunctions.SetAppBar( this, ABEdge.Right );\n</code></pre>\n\n<p>Restore the window to a normal window:</p>\n\n<pre><code>AppBarFunctions.SetAppBar( this, ABEdge.None );\n</code></pre>\n\n<p>Here\'s the full code to the file - <strong>note</strong> you\'ll want to change the namespace on line 7 to something apropriate.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{ \n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport("User32.dll", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; } \n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, \n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo \n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if( s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle, \n OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top),\n OriginalSize = \n new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle; \n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, \n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if( edge == ABEdge.None)\n {\n if( info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true; \n info.CallbackId = RegisterWindowMessage("AppBarMessage");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None; \n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow); \n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = 0;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth);\n }\n else\n {\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = 0;\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight);\n }\n else\n {\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, \n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, \n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n</code></pre>\n'}, {'answer_id': 624235, 'author': 'Shuft', 'author_id': 1587, 'author_profile': 'https://Stackoverflow.com/users/1587', 'pm_score': 2, 'selected': False, 'text': '<p>Very happy to have found this question. Above class is really useful, but doesnt quite cover all the bases of AppBar implementation. </p>\n\n<p>To fully implement all the behaviour of an AppBar (cope with fullscreen apps etc) you\'re going to want to read this MSDN article too.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/bb776821.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb776821.aspx</a></p>\n'}, {'answer_id': 779175, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Sorry, the last code I posted didn't work when the Taskbar is resized. The following code change seems to work better:</p>\n\n<blockquote>\n<pre><code> SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n\n if (barData.uEdge == (int)ABEdge.Top)\n barData.rc.bottom = barData.rc.top + (int)Math.Round(appbarWindow.ActualHeight);\n else if (barData.uEdge == (int)ABEdge.Bottom)\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n</code></pre>\n</blockquote>\n"}, {'answer_id': 1117766, 'author': 'logicnp', 'author_id': 51919, 'author_profile': 'https://Stackoverflow.com/users/51919', 'pm_score': 1, 'selected': False, 'text': '<p>As a commercial alternative, see the ready-to-use <a href="http://www.ssware.com/shlobj/shlobj.htm" rel="nofollow noreferrer">ShellAppBar</a> component for WPF which supports all cases and secnarios such as taskbar docked to left,right,top,bottom edge, support for multiple monitors, drag-docking, autohide , etc etc. It may save you time and money over trying to handle all these cases yourself.</p>\n\n<p><strong>DISCLAIMER</strong>: I work for LogicNP Software, the developer of ShellAppBar.</p>\n'}, {'answer_id': 5610186, 'author': 'Dmitry Andreev', 'author_id': 700625, 'author_profile': 'https://Stackoverflow.com/users/700625', 'pm_score': 2, 'selected': False, 'text': '<p>Sorry for my English... Here is the Philip Rieck\'s solution with some corrects. It correctly works with Taskbar position and size changes.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace wpf_appbar\n{\n public enum ABEdge : int\n {\n Left,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n public RECT(Rect r)\n {\n Left = (int)r.Left;\n Right = (int)r.Right;\n Top = (int)r.Top;\n Bottom = (int)r.Bottom;\n }\n public static bool operator ==(RECT r1, RECT r2)\n {\n return r1.Bottom == r2.Bottom && r1.Left == r2.Left && r1.Right == r2.Right && r1.Top == r2.Top;\n }\n public static bool operator !=(RECT r1, RECT r2)\n {\n return !(r1 == r2);\n }\n public override bool Equals(object obj)\n {\n return base.Equals(obj);\n }\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n private enum TaskBarPosition : int\n {\n Left,\n Top,\n Right,\n Bottom\n }\n\n [StructLayout(LayoutKind.Sequential)]\n class TaskBar\n {\n public TaskBarPosition Position;\n public TaskBarPosition PreviousPosition;\n public RECT Rectangle;\n public RECT PreviousRectangle;\n public int Width;\n public int PreviousWidth;\n public int Height;\n public int PreviousHeight;\n public TaskBar()\n {\n Refresh();\n }\n public void Refresh()\n {\n APPBARDATA msgData = new APPBARDATA();\n msgData.cbSize = Marshal.SizeOf(msgData);\n SHAppBarMessage((int)ABMsg.ABM_GETTASKBARPOS, ref msgData);\n PreviousPosition = Position;\n PreviousRectangle = Rectangle;\n PreviousHeight = Height;\n PreviousWidth = Width;\n Rectangle = msgData.rc;\n Width = Rectangle.Right - Rectangle.Left;\n Height = Rectangle.Bottom - Rectangle.Top;\n int h = (int)SystemParameters.PrimaryScreenHeight;\n int w = (int)SystemParameters.PrimaryScreenWidth;\n if (Rectangle.Bottom == h && Rectangle.Top != 0) Position = TaskBarPosition.Bottom;\n else if (Rectangle.Top == 0 && Rectangle.Bottom != h) Position = TaskBarPosition.Top;\n else if (Rectangle.Right == w && Rectangle.Left != 0) Position = TaskBarPosition.Right;\n else if (Rectangle.Left == 0 && Rectangle.Right != w) Position = TaskBarPosition.Left;\n }\n }\n\n [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport("User32.dll", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public ABEdge PreviousEdge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n PreviousEdge = Edge;\n ABSetPos(Edge, PreviousEdge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo\n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.None,\n PreviousEdge = ABEdge.None,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n info.PreviousEdge = info.Edge;\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage("AppBarMessage");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, info.PreviousEdge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n static TaskBar tb = new TaskBar();\n\n private static void ABSetPos(ABEdge edge, ABEdge prevEdge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n RECT wa = new RECT(SystemParameters.WorkArea);\n tb.Refresh();\n switch (edge)\n {\n case ABEdge.Top:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Top = wa.Top - (prevEdge == ABEdge.Top ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - ((tb.Position != TaskBarPosition.Top && tb.PreviousPosition == TaskBarPosition.Top) ? tb.Height : 0) + ((tb.Position == TaskBarPosition.Top && tb.PreviousPosition != TaskBarPosition.Top) ? tb.Height : 0);\n barData.rc.Bottom = barData.rc.Top + (int)Math.Round(appbarWindow.ActualHeight);\n break;\n case ABEdge.Bottom:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Bottom = wa.Bottom + (prevEdge == ABEdge.Bottom ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - 1 + ((tb.Position != TaskBarPosition.Bottom && tb.PreviousPosition == TaskBarPosition.Bottom) ? tb.Height : 0) - ((tb.Position == TaskBarPosition.Bottom && tb.PreviousPosition != TaskBarPosition.Bottom) ? tb.Height : 0);\n barData.rc.Top = barData.rc.Bottom - (int)Math.Round(appbarWindow.ActualHeight);\n break;\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n switch (barData.uEdge)\n {\n case (int)ABEdge.Bottom:\n if (tb.Position == TaskBarPosition.Bottom && tb.PreviousPosition == tb.Position)\n {\n barData.rc.Top += (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n case (int)ABEdge.Top:\n if (tb.Position == TaskBarPosition.Top && tb.PreviousPosition == tb.Position)\n {\n if (tb.PreviousHeight - tb.Height > 0) barData.rc.Top -= (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n }\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.Left, (double)barData.rc.Top, (double)(barData.rc.Right - barData.rc.Left), (double)(barData.rc.Bottom - barData.rc.Top));\n appbarWindow.Dispatcher.BeginInvoke(new ResizeDelegate(DoResize), DispatcherPriority.ApplicationIdle, appbarWindow, rect);\n }\n }\n}\n</code></pre>\n\n<p>The same code you can write for the Left and Right edges.\nGood job, Philip Rieck, thank you!</p>\n'}, {'answer_id': 18896608, 'author': 'Miky Jadro', 'author_id': 2795750, 'author_profile': 'https://Stackoverflow.com/users/2795750', 'pm_score': 2, 'selected': False, 'text': '<p>I modified code from Philip Rieck (btw. Thanks a lot) to work in multiple display settings. Here\'s my solution.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{\n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public int dwFlags;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport("User32.dll", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n [DllImport("User32.dll", CharSet = CharSet.Auto)]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport("User32.dll", CharSet = CharSet.Auto)]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO mi);\n\n\n private const int MONITOR_DEFAULTTONEAREST = 0x2;\n private const int MONITORINFOF_PRIMARY = 0x1;\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo\n = new Dictionary<Window, RegisterInfo>();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage("AppBarMessage");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n private static void GetActualScreenData(ABEdge edge, Window appbarWindow, ref int leftOffset, ref int topOffset, ref int actualScreenWidth, ref int actualScreenHeight)\n {\n IntPtr handle = new WindowInteropHelper(appbarWindow).Handle;\n IntPtr monitorHandle = MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST);\n\n MONITORINFO mi = new MONITORINFO();\n mi.cbSize = Marshal.SizeOf(mi);\n\n if (GetMonitorInfo(monitorHandle, ref mi))\n {\n if (mi.dwFlags == MONITORINFOF_PRIMARY)\n {\n return;\n }\n leftOffset = mi.rcWork.left;\n topOffset = mi.rcWork.top;\n actualScreenWidth = mi.rcWork.right - leftOffset;\n actualScreenHeight = mi.rcWork.bottom - mi.rcWork.top;\n }\n }\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n int leftOffset = 0;\n int topOffset = 0;\n int actualScreenWidth = (int)SystemParameters.PrimaryScreenWidth;\n int actualScreenHeight = (int)SystemParameters.PrimaryScreenHeight;\n\n GetActualScreenData(edge, appbarWindow, ref leftOffset, ref topOffset, ref actualScreenWidth, ref actualScreenHeight);\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = actualScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = leftOffset;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth) + leftOffset;\n }\n else\n {\n barData.rc.right = actualScreenWidth + leftOffset;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = leftOffset;\n barData.rc.right = actualScreenWidth + leftOffset;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight) + topOffset;\n }\n else\n {\n barData.rc.bottom = actualScreenHeight + topOffset;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top,\n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n</code></pre>\n'}, {'answer_id': 33272341, 'author': 'Hugh', 'author_id': 5347352, 'author_profile': 'https://Stackoverflow.com/users/5347352', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve spent some weeks exploring this challenge and finally created a very solid NuGet package delivering this functionality in very friendly way. Simply create a new WPF app then change the main window\'s class from Window to DockWindow (in the XAML) and that\'s it!</p>\n\n<p>Get the package <a href="https://www.nuget.org/packages/Canyonix.UI.Windows/1.0.1" rel="nofollow">here</a> and see the Git repo for a demonstration app.</p>\n'}, {'answer_id': 43024177, 'author': 'Mitch', 'author_id': 138200, 'author_profile': 'https://Stackoverflow.com/users/138200', 'pm_score': 3, 'selected': False, 'text': '<p>There is an excellent MSDN article from 1996 which is entertainingly up to date: <a href="http://web.archive.org/web/20170704171718/https://www.microsoft.com/msj/archive/S274.aspx" rel="nofollow noreferrer">Extend the Windows 95 Shell with Application Desktop Toolbars</a>. Following its guidance produces an WPF based appbar which handles a number of scenarios that the other answers on this page do not:</p>\n\n<ul>\n<li>Allow dock to any side of the screen</li>\n<li>Allow dock to a particular monitor</li>\n<li>Allow resizing of the appbar (if desired)</li>\n<li>Handle screen layout changes and monitor disconnections</li>\n<li>Handle <kbd>Win</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> and attempts to minimize or move the window</li>\n<li>Handle co-operation with other appbars (OneNote et al.)</li>\n<li>Handle per-monitor DPI scaling</li>\n</ul>\n\n<p>I have both a <a href="https://github.com/mgaffigan/WpfAppBar" rel="nofollow noreferrer">demo app and the implementation of <code>AppBarWindow</code> on GitHub</a>.</p>\n\n<p>Example use:</p>\n\n<pre><code><apb:AppBarWindow x:Class="WpfAppBarDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n xmlns:apb="clr-namespace:WpfAppBar;assembly=WpfAppBar"\n DataContext="{Binding RelativeSource={RelativeSource Self}}" Title="MainWindow" \n DockedWidthOrHeight="200" MinHeight="100" MinWidth="100">\n <Grid>\n <Button x:Name="btClose" Content="Close" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="23" Margin="10,10,0,0" Click="btClose_Click"/>\n <ComboBox x:Name="cbMonitor" SelectedItem="{Binding Path=Monitor, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="10,38,0,0"/>\n <ComboBox x:Name="cbEdge" SelectedItem="{Binding Path=DockMode, Mode=TwoWay}" HorizontalAlignment="Left" Margin="10,65,0,0" VerticalAlignment="Top" Width="120"/>\n\n <Thumb Width="5" HorizontalAlignment="Right" Background="Gray" x:Name="rzThumb" Cursor="SizeWE" DragCompleted="rzThumb_DragCompleted" />\n </Grid>\n</apb:AppBarWindow>\n</code></pre>\n\n<p>Codebehind:</p>\n\n<pre><code>public partial class MainWindow\n{\n public MainWindow()\n {\n InitializeComponent();\n\n this.cbEdge.ItemsSource = new[]\n {\n AppBarDockMode.Left,\n AppBarDockMode.Right,\n AppBarDockMode.Top,\n AppBarDockMode.Bottom\n };\n this.cbMonitor.ItemsSource = MonitorInfo.GetAllMonitors();\n }\n\n private void btClose_Click(object sender, RoutedEventArgs e)\n {\n Close();\n }\n\n private void rzThumb_DragCompleted(object sender, DragCompletedEventArgs e)\n {\n this.DockedWidthOrHeight += (int)(e.HorizontalChange / VisualTreeHelper.GetDpi(this).PixelsPerDip);\n }\n}\n</code></pre>\n\n<p>Changing docked position:</p>\n\n<blockquote>\n <p><a href="https://i.stack.imgur.com/f13P8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f13P8.gif" alt="AppBar docked to edges"></a></p>\n</blockquote>\n\n<p>Resizing with thumb:</p>\n\n<blockquote>\n <p><a href="https://i.stack.imgur.com/ifgn8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifgn8.gif" alt="Resize"></a></p>\n</blockquote>\n\n<p>Cooperation with other appbars:</p>\n\n<blockquote>\n <p><a href="https://i.stack.imgur.com/PiydR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PiydR.gif" alt="Coordination"></a></p>\n</blockquote>\n\n<p>Clone <a href="https://github.com/mgaffigan/WpfAppBar" rel="nofollow noreferrer">from GitHub</a> if you want to use it. The library itself is only three files, and can easily be dropped in a project.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7301/'] |
75,786 | <p>(Eclipse 3.4, Ganymede)</p>
<p>I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down.</p>
<p>It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.)</p>
<p>I have tried the following steps (without success):</p>
<ul>
<li>I selected <code>Targeted Runtimes</code> under the Project <code>Properties</code><br>
The <code>Tomcat v5.5</code> option was disabled and The UI displayed this message:<br>
<code>If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.</code> </li>
<li>I then clicked on the <code>Uninstall Facets...</code> link.<br>
Under the <code>Runtimes</code> tab, only <code>Tomcat 6</code> displayed.<br>
For <code>Dynamic Web Module</code>, I selected version <code>2.4</code> in place of <code>2.5</code>.<br>
Under the <code>Runtimes</code> tab, <code>Tomcat 5.5</code> now displayed.<br>
However, the UI now displayed this message:<br>
<code>Cannot change version of project facet Dynamic Web Module to 2.4.</code><br>
The <code>Finish</code> button was disabled - so I reached a dead-end.</li>
</ul>
<p>I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project.</p>
<p>As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy.</p>
<p>Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened?</p>
<p>Thanks<br>
Pete</p>
| [{'answer_id': 76205, 'author': 'William', 'author_id': 9193, 'author_profile': 'https://Stackoverflow.com/users/9193', 'pm_score': 7, 'selected': True, 'text': '<p>This is kind of hacking eclipse and you can get into trouble doing this but this should work:</p>\n\n<p>Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: <code>org.eclipse.wst.common.project.facet.core.xml</code> you should see a line that says: \n<code>\n <installed facet="jst.web" version="2.5"/>\n</code>\nChange that to 2.4 and save.</p>\n\n<p>Just make sure that your project isn\'t using anything specific for 2.5 and you should be good.</p>\n\n<p>Also check your web.xml has the correct configuration:</p>\n\n<pre><code><web-app version="2.4" \n xmlns="http://java.sun.com/xml/ns/j2ee" \n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">\n</code></pre>\n'}, {'answer_id': 78299, 'author': 'William', 'author_id': 9193, 'author_profile': 'https://Stackoverflow.com/users/9193', 'pm_score': 0, 'selected': False, 'text': "<p>Sorry it seems I can't post a comment without enough Rep so...</p>\n\n<p>I think it's too difficult for eclipse to degrade safely to a lower standard because it can't really know if you've used something from the newer web standard. So if it just allows you do to that it could cause your program to fail on an older version.</p>\n\n<p>You can always be backward compatible but not forwards compatible.</p>\n"}, {'answer_id': 2356592, 'author': 'Venkat', 'author_id': 194565, 'author_profile': 'https://Stackoverflow.com/users/194565', 'pm_score': 3, 'selected': False, 'text': '<p>This may be old but I tried and found the following in eclipse Galilio. </p>\n\n<p>Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: org.eclipse.wst.common.project.facet.core.Delete the content of this file and right click on the project and click on properties. Go to Project Facats in the popup window there you can click on runtime tabs and convert your project to the new facet you want.</p>\n'}, {'answer_id': 4051477, 'author': 'xgomez', 'author_id': 59067, 'author_profile': 'https://Stackoverflow.com/users/59067', 'pm_score': 0, 'selected': False, 'text': "<p>You can try to uncheck the facet, apply, change the value of the facet and check. It works for me in Eclipse Helios SR1.</p>\n\n<p>So the main difference is that I do it with 'Dynamic Web Module'.</p>\n\n<p>I hope it works for you too.</p>\n"}, {'answer_id': 4830219, 'author': 'Karthik', 'author_id': 594073, 'author_profile': 'https://Stackoverflow.com/users/594073', 'pm_score': 3, 'selected': False, 'text': '<p>if you are using Maven, then shutdown eclipse, then type <code>>mvn eclipse:eclipse -Dwtpversion=2.0</code>, and restart the eclipse. </p>\n'}, {'answer_id': 5571788, 'author': 'sarabrab', 'author_id': 695500, 'author_profile': 'https://Stackoverflow.com/users/695500', 'pm_score': 0, 'selected': False, 'text': '<p>I saw the same thing, then I changed the web-app version value in the <code>web.xml</code>. Doing so could fix this for you.</p>\n'}, {'answer_id': 5956380, 'author': 'Dante', 'author_id': 682844, 'author_profile': 'https://Stackoverflow.com/users/682844', 'pm_score': -1, 'selected': False, 'text': '<p>If you are using maven you can generated the eclipse settings using the maven eclipse plugin. </p>\n\n<p>For the jst.web version the Maven eclipse pluging takes into account the dependencies of the project. If you have a servlet api dependency defined :</p>\n\n<pre><code><dependency>\n <groupId>org.apache.tomcat</groupId>\n <artifactId>servlet-api</artifactId>\n <version>6.0.32</version>\n</dependency> \n</code></pre>\n\n<p>You jst.web parameter will be 6.0 </p>\n\n<pre><code><faceted-project>\n ...\n <installed facet="jst.web" version="6.0"/>\n ...\n</faceted-project>\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13360/'] |
75,798 | <p>I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? </p>
<p>Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. </p>
<p>Ruby has similar issues and although I do like Ruby <strong>much</strong> better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. </p>
<p>Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?</p>
| [{'answer_id': 76198, 'author': 'Trausti Thor', 'author_id': 6801, 'author_profile': 'https://Stackoverflow.com/users/6801', 'pm_score': 1, 'selected': False, 'text': '<p>cakephp.org</p>\n\n<p>Cakephp is really good, really close to ruby on rails (1.2). It is in php, works very well on shared hosts and is easy to implement. </p>\n\n<p>The only downside is that the documentation is somewhat lacking, but you quickly get it and quickly start doing cool stuff.</p>\n\n<p>I totally recommend cakephp.</p>\n'}, {'answer_id': 77693, 'author': 'zuber', 'author_id': 9812, 'author_profile': 'https://Stackoverflow.com/users/9812', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n <p>However it\'s written in Python which\n means there\'s little real support in\n the way of deployment/packaging,\n debugging, profilers and other tools\n that make building and maintaining\n applications much easier.</p>\n</blockquote>\n\n<p>Python has:</p>\n\n<ol>\n<li>a <a href="http://docs.python.org/lib/module-pdb.html" rel="noreferrer">great interactive debugger</a>, which makes very good use of Python <a href="http://en.wikipedia.org/wiki/REPL" rel="noreferrer">REPL</a>. </li>\n<li><a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="noreferrer">easy_install</a> anv <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> for dependency management, packaging and deployment.</li>\n<li><a href="http://docs.python.org/lib/profile.html" rel="noreferrer">profiling features</a> comparable to other languages</li>\n</ol>\n\n<p>So IMHO you shouldn\'t worry about this things, use Python and Django and live happily :-)</p>\n\n<p>Lucky for you, newest version of <a href="http://blog.leosoto.com/2008/08/django-on-jython-its-here.html" rel="noreferrer">Django runs on Jython</a>, so you don\'t need to leave your whole Java ecosystem behind.</p>\n\n<p>Speaking of frameworks, I evaluated this year:</p>\n\n<ol>\n<li><a href="http://pylonshq.com/" rel="noreferrer">Pylons</a> (Python)</li>\n<li><a href="http://webpy.org/" rel="noreferrer">webpy</a> (Python)</li>\n<li><a href="http://www.symfony-project.org/" rel="noreferrer">Symfony</a> (PHP)</li>\n<li><a href="http://www.cakephp.org/" rel="noreferrer">CakePHP</a> (PHP)</li>\n</ol>\n\n<p>None of this frameworks comes close to the power of Django or Ruby on Rails. Based on my collegue opinion I could recommend you <a href="http://www.kohanaphp.com/home" rel="noreferrer">kohana</a> framework. The downside is, it\'s written in PHP and, as far as I know, PHP doesn\'t have superb tools for debugging, profiling and packaging of apps.</p>\n\n<p><strong>Edit:</strong> Here is a very good <a href="http://bud.ca/blog/pony" rel="noreferrer">article about packaging and deployment of Python apps</a> (specifically Django apps). It\'s a hot topic in Django community now.</p>\n'}, {'answer_id': 78424, 'author': 'Christopher Cashell', 'author_id': 13091, 'author_profile': 'https://Stackoverflow.com/users/13091', 'pm_score': 2, 'selected': False, 'text': '<p>I have two friends who originally started writing an application using Ruby on Rails, but ran into a number of issues and limitations. After about 8 weeks of working on it, they decided to investigate other alternatives.</p>\n\n<p>They settled on the <a href="http://www.catalystframework.org" rel="nofollow noreferrer">Catalyst Framework</a>, and Perl. That was about 4 months ago now, and they\'ve repeatedly talked about how much better the application is going, and how much more flexibility they have.</p>\n\n<p>With Perl, you have all of CPAN available to you, along with the large quantity of tools included. I\'d suggest taking a look at it, at least.</p>\n'}, {'answer_id': 81699, 'author': 'zgoda', 'author_id': 12138, 'author_profile': 'https://Stackoverflow.com/users/12138', 'pm_score': 1, 'selected': False, 'text': '<p>Personally I made some rather big projects with Django, but I can compare only with said "montrosities" (Spring, EJB) and really low-level stuff like Twisted.</p>\n\n<p>Web frameworks using interpreted languages are mostly in its infancy and all of them (actively maintained, that is) are getting better with every day.</p>\n'}, {'answer_id': 83075, 'author': 'Powerlord', 'author_id': 15880, 'author_profile': 'https://Stackoverflow.com/users/15880', 'pm_score': 1, 'selected': False, 'text': '<p>By "good deployment" are you comparing it with Java\'s EAR files, which allow you to deploy web applications by uploading a single file to a J2EE server? (And, to a lesser extent, WAR files; EAR files can have WAR files for dependent projects)</p>\n\n<p>I don\'t think Django or Rails have gotten quite to that point yet, but I could be wrong... zuber pointed out an article with more details on the Python side.</p>\n\n<p><a href="http://www.capify.org/" rel="nofollow noreferrer">Capistrano</a> may help out on the Ruby side.</p>\n\n<p>Unfortunately, I haven\'t really worked with either Python or Ruby that much, so I can\'t help out on profilers or debuggers.</p>\n'}, {'answer_id': 97778, 'author': 'S.Lott', 'author_id': 10661, 'author_profile': 'https://Stackoverflow.com/users/10661', 'pm_score': 2, 'selected': False, 'text': '<p>The "good deployment" issue -- for Python -- doesn\'t have the Deep Significance that it has for Java.</p>\n\n<p>Python deployment for Django is basically "move the files". You can run straight out of the subversion trunk directory if you want to.</p>\n\n<p>You can, without breaking much of a sweat, using the Python <a href="http://docs.python.org/dist/dist.html" rel="nofollow noreferrer">distutils</a> and build yourself a distribution kit that puts your Django apps into Python\'s site-packages. I\'m not a big fan of it, but it\'s really easy to do. </p>\n\n<p>Since my stuff runs in Linux, I have simple "install.py" scripts that move stuff out of the Subversion directories into <code>/opt/this</code> and <code>/opt/that</code> directories. I use an explicit path settings in my Apache configuration to name those directories where the applications live.</p>\n\n<p>Patching can be done by editing the files in place. (A bad policy.) I prefer to edit in the SVN location and rerun my little install to be sure I actually have all the files under control.</p>\n'}, {'answer_id': 460360, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Grails.</p>\n\n<p>Grails just looks like Rails (Ruby),but it uses groovy which is simpler than java. It uses java technology and you can use any java lib without any trouble.</p>\n\n<p>I also choose Grails over simplicity and there are lots of java lib (such as jasper report, jawr etc) and I am glad that now they join with SpringSource which makes their base solid.</p>\n'}, {'answer_id': 1955727, 'author': 'hendrixski', 'author_id': 24920, 'author_profile': 'https://Stackoverflow.com/users/24920', 'pm_score': 6, 'selected': True, 'text': "<p>You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts:</p>\n\n<p><strong>IDE's:</strong>\nDjango works really well in Eclipse, Grails works really well in IntelliJ Idea.</p>\n\n<p><strong>Debugging:</strong>\nPractically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspecting variables, etc... never need a print statement for either. Sometimes django error messages can be useless but Grails error messages are usually pretty lengthy and hard to parse through.</p>\n\n<p><strong>Time to run a unit test:</strong>\ndjango: 2 seconds.\nGrails: 20 seconds (the tests themselves both run in a fraction of a second, it's the part about loading the framework to run them that takes the rest... as you can see, Grails is frustratingly slow to load).</p>\n\n<p><strong>Deployment:</strong>\nDjango: copy & paste one file into an apache config, and to redeploy, just change the code and reload apache.\nGrails: create a .war file, deploy it on tomcat, rinse and repeat to redeploy.</p>\n\n<p><strong>Programming languages:</strong>\nGroovy is TOTALLY awesome. I love it, more so than Python. But I certainly have no complaints. </p>\n\n<p><strong>Plugins:</strong>\nGrails: lots of broken plugins (and can use every java lib ever).\nDjango: a few stable plugins, but enough to do most of what you need.</p>\n\n<p><strong>Database:</strong>\nDjango: schema migrations using South, and generally intuitive relations.\nGrails: no schema migrations, and by default it deletes the database on startup... WTF</p>\n\n<p><strong>Usage:</strong>\nDjango: startups (especially in the Gov 2.0 space), independent web dev shops.\nGrails: enterprise</p>\n\n<p>Hope that helps!</p>\n"}, {'answer_id': 1997668, 'author': 'Brian Hibbert', 'author_id': 242986, 'author_profile': 'https://Stackoverflow.com/users/242986', 'pm_score': 3, 'selected': False, 'text': "<p>The statement that <em>grails deletes the database on start-up</em> is completely wrong. It's behavior on start-up is completely configurable and easy to configure. I generally use create-drop when running an app in dev mode. I use update when I run in test and production.</p>\n\n<p>I also love the bootstrap processing that lets me pre-configure test users, data, etc by environment in Grails. </p>\n\n<p>I'd love to see someone who has really built and deployed some commercial projects comment on the pros / cons. Be a really interesting read.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13436/'] |
75,805 | <p>On my journey into the depths of custom ASP.NET control development I am obviously getting my head around the ASP.NET PostBack model and how it affects control development.</p>
<p>I understand that controls have no "lifetime" in ASP.NET, and therefore must be re-initialized on each and every page load. We overcome this by persisting the objects values/parameters to the ViewState.</p>
<p>Many articles I read therefore suggest not using PostBack since this can add considerable overhead to the Page. <strong>I am not looking for how to disable it, I know that.</strong> </p>
<p>What I am looking for is:</p>
<p><strong>What alternatives to we have to using the PostBack model to initialize controls?</strong></p>
<p>I know we <em>could</em> use the QueryString, but that seems awfully messy, and obviously unreliable.</p>
<p><strong>Ideally you could give me an overview of the architecture/design of a different approach and the pro's/con's of it..</strong></p>
<p>Many thanks ^_^</p>
| [{'answer_id': 75859, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 3, 'selected': True, 'text': "<p>Well, Session State is a server-side solution, with its own pile of cruft to deal with if you want to avoid ViewState altogether. Really though, using ViewState in a custom control is all fine and good - just be picky about what you store - only store deltas from the declared control state, don't store anything you're going to get on postback anyway (e.g. from a DB call), etc.</p>\n"}, {'answer_id': 75869, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 1, 'selected': False, 'text': "<p>You have to store the values somewhere, so you are limited to the query string and hidden form fields. If you relate that to HTTP, basically it's either GET or POST parameters.</p>\n\n<p>I suppose you could use cookies, but that would be really messy.</p>\n"}, {'answer_id': 75871, 'author': 'mdb', 'author_id': 8562, 'author_profile': 'https://Stackoverflow.com/users/8562', 'pm_score': 1, 'selected': False, 'text': '<ol>\n<li><p>Store your object state in the session context: this will shift the burden of keeping state from the client to the server, which <em>may</em> be acceptable for small-scale intranet apps. For sites on the capital-I Internet, this won\'t work;</p></li>\n<li><p>AJAX-enable your control: in this case, only state <em>changes</em> need to be posted back. Picking the right framework is key here; see <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/" rel="nofollow noreferrer">http://www.asp.net/ajax/ajaxcontroltoolkit/samples/</a> for the official MS approach; many others are possible.</p></li>\n</ol>\n'}, {'answer_id': 75878, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': '<p>I think you still mis-understand controls somewhat. Controls only have the problem you describe when you add them to the page dynamically. If you declare your controls upfront in the aspx code then they build along with the page.</p>\n'}, {'answer_id': 235983, 'author': 'sliderhouserules', 'author_id': 31385, 'author_profile': 'https://Stackoverflow.com/users/31385', 'pm_score': 1, 'selected': False, 'text': "<p>If you're truly looking for alternatives to the PostBack model altogether, then I would suggest researching the ASP.NET MVC Framework. I would love to kick WebForms to the curb and do all my stuff in MVC, but alas, legacy code is a tarbaby and rewriting is almost never the answer, so I plug onwards...</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832/'] |
75,809 | <p>Given the case I made <strong>two independent changes</strong> in <em>one</em> file: eg. added a new method and changed another method.</p>
<p>I often don't want to commit both changes as <strong>one</strong> commit, but as <strong>two</strong> independent commits.</p>
<p>On a git repository I would use the <strong>Interactive Mode</strong> of <a href="http://linux.die.net/man/1/git-add" rel="noreferrer">git-add(1)</a> to split the <em>hunk</em> into smaller ones:</p>
<pre><code> git add --patch
</code></pre>
<p>What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in)</p>
<p><strong>Update:</strong><br/>
In <a href="http://tomayko.com/writings/the-thing-about-git" rel="noreferrer">The Thing About Git</a>, Ryan calls it: <em>“The Tangled Working Copy Problem.”</em></p>
| [{'answer_id': 75881, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 3, 'selected': False, 'text': '<p>I used to do this:</p>\n\n<ul>\n<li>In my editor (I use vim), edit the file so that only one of the changes appear</li>\n<li>Save the file (but don\'t quit the editor)</li>\n<li>Commit the changed file to svn</li>\n<li>Hit "undo" in the editor enough times for the second set of changes reappear</li>\n<li>Save the file again</li>\n<li>Commit the second set of changes.</li>\n</ul>\n\n<p>This is a simplistic approach that assumes one set of changes is reasonably easy to undo. For more complex situations, I would give up and commit both changes without worrying about it.</p>\n\n<p>Now that I use git, this is something I hope I\'ll never have to do again!</p>\n'}, {'answer_id': 75901, 'author': 'Spike', 'author_id': 13111, 'author_profile': 'https://Stackoverflow.com/users/13111', 'pm_score': 5, 'selected': False, 'text': '<p>I have done this using <a href="http://tortoisesvn.tigris.org/" rel="noreferrer" title="TortoiseSVN">TortoiseSVN</a>.</p>\n\n<p>The built in merge utility allows you to show a diff between the repository version and your working copy.</p>\n\n<p>Use the <em>create backup</em> function of the diff utility</p>\n\n<ol>\n<li>Go to commit your file as if you were going to commit all your changes.</li>\n<li>In the commit window, double click the file to show a diff.</li>\n<li>In the diff settings, click the option to <em>backup original file</em>. </li>\n<li>Right-click the changes you don\'t want, and use select <em>use other text block</em>.</li>\n<li>Save the diff <strong>exactly once</strong>. The backup will be overwritten each time you save. This is why you only want to save once.</li>\n<li>Commit the change.</li>\n<li>Overwrite the original with the created .bak file (which will have all your original changes).</li>\n<li>Commit your file.</li>\n</ol>\n\n<p>You should now have all your changes committed, using two separate commits.</p>\n'}, {'answer_id': 75918, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 2, 'selected': False, 'text': '<p>I use either a local darcs repo, or just merge the changes in gradually. With merging (opendiff opens FileMerge, a merge program that comes with Xcode; replace with your favorite merge tool):</p>\n\n<pre><code>cp file file.new\nsvn revert file\nopendiff file.new file -merge file\n</code></pre>\n\n<p>merge the related changes, save the merge, quit the merge program</p>\n\n<pre><code>svn ci -m \'first hunk\' file\nmv file.new file\nsvn ci -m \'second hunk\' file\n</code></pre>\n\n<p>if more than one unrelated hunk in the file, rinse and repeat (but why would you wait so long before committing?!)</p>\n\n<p>Also, if you know git, you can use <a href="http://git.or.cz/course/svn.html" rel="noreferrer">git-svn</a> to maintain a local git repo and sync your commits to an svn master server; works great in my limited experience.</p>\n'}, {'answer_id': 75950, 'author': 'Chris', 'author_id': 13488, 'author_profile': 'https://Stackoverflow.com/users/13488', 'pm_score': 5, 'selected': False, 'text': "<p>Try using <code>svn diff > out.patch</code> then copy the <code>out.patch</code> file to <code>out.patch.add</code> and <code>out.patch.modify</code> </p>\n\n<p><em>Only when you have a working patch file</em> revert the original file using <code>svn revert out.c</code>.</p>\n\n<p>Edit the patch files by hand so that they only contain the <em>hunks</em> for adding or modifying. Apply them to the original file using the <code>patch</code> command, test if the addition worked, then <code>svn commit</code> the addition.</p>\n\n<p>Wash rinse repeat for the <code>out.patch.modify</code> patch.</p>\n\n<p>If the changes are separate in the file as your initial question stated - added a new method, changed an existing method - this will work</p>\n\n<p>This is a very tedious solution - although I'm not convinced you should have any reason to separate your commits.</p>\n\n<p>You also could have checked out multiple working copies of the same source to apply your work against:</p>\n\n<blockquote>\n <p><code>svn co http://location/repository methodAdd</code></p>\n \n <p><code>svn co http://location/repository methodModify</code></p>\n</blockquote>\n\n<p>Be sure to <code>svn up</code> and test to make sure all is well.</p>\n"}, {'answer_id': 76088, 'author': 'jkramer', 'author_id': 12523, 'author_profile': 'https://Stackoverflow.com/users/12523', 'pm_score': 6, 'selected': True, 'text': '<p>With git-svn you can make a local GIT repository of the remote SVN repository, work with it using the full GIT feature set (including partial commits) and then push it all back to the SVN repository.</p>\n\n<p><a href="http://schacon.github.com/git/git-svn.html" rel="noreferrer">git-svn (1)</a></p>\n'}, {'answer_id': 462321, 'author': 'BCS', 'author_id': 1343, 'author_profile': 'https://Stackoverflow.com/users/1343', 'pm_score': 2, 'selected': False, 'text': "<ol>\n<li>Open all the files you want to split in editor-of-choice</li>\n<li>Using a different tool set (on Win, use Spike's suggestion (the old version)) back out the second set</li>\n<li>Commit</li>\n<li>go back to your editor-of-choice and save all the files</li>\n</ol>\n\n<p>It's a little riskier than Spike's full suggestion but can be easier to do. Also make sure you try it on something else first as some editors will refuse to save over a file that has changed out from under them unless you reload that file (losing all your changes)</p>\n"}, {'answer_id': 17538550, 'author': 'Casebash', 'author_id': 165495, 'author_profile': 'https://Stackoverflow.com/users/165495', 'pm_score': 6, 'selected': False, 'text': '<p>Tortoise SVN 1.8 <a href="https://tortoisesvn.net/tsvn_1.8_releasenotes.html#commitparts" rel="noreferrer">now supports</a> this with it\'s "Restore after commit" feature. This allow you to make edits to a file, with all of the edits being undone after the commit</p>\n\n<p><strong>Per the documentation:</strong></p>\n\n<blockquote>\n <p>To commit only the parts of the file that relate to one specific issue:</p>\n \n <ol>\n <li>in the commit dialog, right-click on file, choose "restore after commit"</li>\n <li>edit the file in e.g. TortoiseMerge: undo the changes that you don\'t want to commit yet</li>\n <li>save the file</li>\n <li>commit the file</li>\n </ol>\n</blockquote>\n'}, {'answer_id': 19255703, 'author': 'parvus', 'author_id': 911550, 'author_profile': 'https://Stackoverflow.com/users/911550', 'pm_score': 4, 'selected': False, 'text': '<p>This is possible using TortoiseSvn (Windows) since v1.8.</p>\n<blockquote>\n<p>4.4.1. The Commit Dialog</p>\n<p>If your working copy is up to date and there are no conflicts, you are ready to commit your changes. Select any\nfile and/or folders you want to commit, then TortoiseSVN → Commit....</p>\n<p><snip></p>\n<p>4.4.3. Commit only parts of files</p>\n<p>Sometimes you want to only commit parts of the changes you made to a file. Such a situation usually\nhappens when you\'re working on something but then an urgent fix needs\nto be committed, and that fix happens to be in the same file you\'re\nworking on.</p>\n<p>right click on the file and use Context Menu → Restore after commit.\nThis will create a copy of the file as it is. Then you can edit the\nfile, e.g. in TortoiseMerge and undo all the changes you don\'t want to\ncommit. After saving those changes you can commit the file.</p>\n<p>After the commit is done, the copy of the file is restored\nautomatically, and you have the file with all your modifications that\nwere not committed back.</p>\n</blockquote>\n<p>On Linux, I would give <a href="http://webstaff.itn.liu.se/%7Ekarlu20/div/blog/2013-05-31_SVNPartialCommit.php" rel="noreferrer">http://webstaff.itn.liu.se/~karlu20/div/blog/2013-05-31_SVNPartialCommit.php</a> a try. Haven\'t tried it out myself, though.</p>\n'}, {'answer_id': 35370831, 'author': 'Ian Dunn', 'author_id': 450127, 'author_profile': 'https://Stackoverflow.com/users/450127', 'pm_score': 0, 'selected': False, 'text': "<p>I think an easier option than generating diff files, reverting, etc, would be to have two copies of the repository checked out, and use a visual diff tool like DeltaWalker to copy hunks from one to the other.</p>\n\n<p>The first copy would be the one you actually work off of, and the second would just be for this purpose. Once you've made a ton of changes to the first, you can copy one section over to the second, commit it, copy another section, commit it, etc.</p>\n"}, {'answer_id': 46731868, 'author': 'michaeljt', 'author_id': 213180, 'author_profile': 'https://Stackoverflow.com/users/213180', 'pm_score': 0, 'selected': False, 'text': '<ol>\n<li>Copy all modified files concerned to back-up copies.</li>\n<li>Create a patch of the working state using <code>svn diff</code>.</li>\n<li>Revert the files using <code>svn revert</code>.</li>\n<li>Re-apply the parts of the patch which you wish to commit, either using the <code>patch</code> tool, or by manual editing, or whatever.</li>\n<li>Run <code>diff</code> afterwards to compare your working copy with your back-up to be sure you applied the patch-parts correctly.</li>\n<li>Build and test.</li>\n<li>Commit.</li>\n<li>Copy your back-up copies back to your repository check-out.</li>\n<li>Repeat at 2. (not at 1.!) until done.</li>\n</ol>\n'}, {'answer_id': 49452436, 'author': 'bahrep', 'author_id': 761095, 'author_profile': 'https://Stackoverflow.com/users/761095', 'pm_score': 2, 'selected': False, 'text': '<p>Try <a href="https://www.visualsvn.com/visualsvn/" rel="nofollow noreferrer">VisualSVN for Visual Studio</a>. The <a href="https://www.visualsvn.com/company/news/visualsvn-6.1" rel="nofollow noreferrer">latest 6.1 release</a> introduces the QuickCommit feature. You can partially commit selected changes in a file using the new <strong>Commit this Block</strong> and <strong>Commit Selection</strong> context menu commands in the Visual Studio editor.</p>\n\n<p><a href="https://i.stack.imgur.com/hV92h.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hV92h.gif" alt="enter image description here"></a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4308/'] |
75,819 | <p>I'm having an issue with a query that currently uses </p>
<pre><code>LEFT JOIN weblog_data AS pwd
ON (pwd.field_id_41 != ''
AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%'))
</code></pre>
<p>However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of <code>LIKE</code>, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?</p>
| [{'answer_id': 75861, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 1, 'selected': False, 'text': '<p>you\'re talking about short circuit evaluation.</p>\n\n<p>Take a look at this article it might help you:\n<a href="http://beingmarkcohen.com/?p=62" rel="nofollow noreferrer">http://beingmarkcohen.com/?p=62</a></p>\n'}, {'answer_id': 75884, 'author': 'Chris Ballance', 'author_id': 1551, 'author_profile': 'https://Stackoverflow.com/users/1551', 'pm_score': 1, 'selected': False, 'text': "<p>using TSQL, run an exact match, check for num of rows == 0, if so, run the like, otherwise don't run the like or add the like results below the exact matches.</p>\n"}, {'answer_id': 75899, 'author': 'Mostlyharmless', 'author_id': 12881, 'author_profile': 'https://Stackoverflow.com/users/12881', 'pm_score': 0, 'selected': False, 'text': "<p>I can only think of doing it in code. Look for an exact match, if the result is empty, look for a LIKE. \nOne other option is a WHERE within this query such that WHERE ({count from exact match}=0), in which case, it wont go through the comparison with LIKE if the exact match returns more than 0 results. But its terribly inefficient... not to mention the fact that using it meaningfully in code is rather difficult.</p>\n\n<p>i'd go for a If(count from exact match = 0) then do like query, else just use the result from exact match.</p>\n"}, {'answer_id': 75973, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': True, 'text': "<p>It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now.</p>\n\n<p>Try this:</p>\n\n<pre><code>LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32)\nLEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%'))\n</code></pre>\n\n<p>Then, in your select clause, use something like this:</p>\n\n<pre><code>select\n isnull(pwd1.field, pwd2.field)\n</code></pre>\n\n<p>however, if you are dealing with a field that can be null in pwd, that will cause problems, this should work though:</p>\n\n<pre><code>select\n case pwd1.nonnullfield is null then pwd2.field else pwd1.field end\n</code></pre>\n\n<p>You'll also have to make sure to do a group by, as the join to pwd2 will still add rows to your result set, even if you end up ignoring the data in it.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12073/'] |
75,829 | <p>All the docs for SQLAlchemy give <code>INSERT</code> and <code>UPDATE</code> examples using the local table instance (e.g. <code>tablename.update()</code>... )</p>
<p>Doing this seems difficult with the declarative syntax, I need to reference <code>Base.metadata.tables["tablename"]</code> to get the table reference.</p>
<p>Am I supposed to do this another way? Is there a different syntax for <code>INSERT</code> and <code>UPDATE</code> recommended when using the declarative syntax? Should I just switch to the old way?</p>
| [{'answer_id': 77962, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>via the <code>__table__</code> attribute on your declarative class</p>\n'}, {'answer_id': 156968, 'author': 'GHZ', 'author_id': 18138, 'author_profile': 'https://Stackoverflow.com/users/18138', 'pm_score': 3, 'selected': False, 'text': "<p>well it works for me:</p>\n\n<pre><code>class Users(Base):\n __tablename__ = 'users'\n __table_args__ = {'autoload':True}\n\nusers = Users()\nprint users.__table__.select()\n</code></pre>\n\n<p>...SELECT users.......</p>\n"}, {'answer_id': 315406, 'author': 'Paul Harrington', 'author_id': 40387, 'author_profile': 'https://Stackoverflow.com/users/40387', 'pm_score': 0, 'selected': False, 'text': '<p>There may be some confusion between <strong>table</strong> (the object) and <strong>tablename</strong> (the name of the table, a string). Using the <strong>table</strong> class attribute works fine for me.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
75,848 | <p>I'm trying to insert a <a href="http://en.wikipedia.org/wiki/Spry_framework" rel="nofollow noreferrer">Spry</a> <a href="http://en.wikipedia.org/wiki/Accordion_(GUI)" rel="nofollow noreferrer">accordion</a> into an already existing <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> page using <a href="http://en.wikipedia.org/wiki/Adobe_Dreamweaver" rel="nofollow noreferrer">Dreamweaver</a>. Is this possible? </p>
<p>I've already tried several things, and only the labels show up.</p>
| [{'answer_id': 81534, 'author': 'Dave Smylie', 'author_id': 1505600, 'author_profile': 'https://Stackoverflow.com/users/1505600', 'pm_score': 3, 'selected': True, 'text': '<p>I\'m not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: </p>\n\n<pre><code> <div id="Accordion1" class="Accordion">\n <div class="AccordionPanel">\n <div class="AccordionPanelTab">Panel 1</div>\n <div class="AccordionPanelContent">\n Panel 1 Content<br/>\n Panel 1 Content<br/>\n Panel 1 Content<br/>\n </div>\n </div>\n </div>\n</code></pre>\n\n<p>Provided you have the <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a> library loaded correctly, that should pretty much be all you need to do.</p>\n'}, {'answer_id': 123868, 'author': 'Mike Cornell', 'author_id': 419788, 'author_profile': 'https://Stackoverflow.com/users/419788', 'pm_score': 0, 'selected': False, 'text': "<p>The only other thing you might check is if your ids are getting munged by JSF. Obviously that could impact the ability of Spry to wire itself to your accordion html structure.</p>\n\n<p>+1 to Dave's answer.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1459442/'] |
75,857 | <p>I like InnoDB's safety, consistency, and self-checking.</p>
<p>But I need MyISAM's speed and light weight.</p>
<p>How can I make MyISAM less prone to corruption due to crashes, bad data, etc.? It takes forever to go through a check (either CHECK TABLE or myisamchk). </p>
<p>I'm not asking for transactional security -- that's what InnoDB is for. But I do want a database I can restart quickly rather than hours (or days!) later.</p>
<p><em>UPDATE:</em> I'm not asking how to load data into tables faster. I've beat my head against that already, and determined that using the MyISAM tables for my LOAD DATA is simply much faster. What I'm after now is <em>mitigating the risks</em> of using MyISAM tables. That is, reducing chances of damage, increasing speed of recovery.</p>
| [{'answer_id': 75892, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 0, 'selected': False, 'text': '<p>Are you married to MySQL? <a href="http://www.postgresql.org/" rel="nofollow noreferrer">Postgres</a> is ACID-compliant (like innoDB) and (when well-tuned) nearly as speedy as MyISAM.</p>\n'}, {'answer_id': 75961, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 2, 'selected': False, 'text': '<p>MyISAM\'s supposed speed benefits can actually go away pretty quickly - the fact that it lacks row-level locking means small updates can cause large amounts of data to be locked, and queries to block. Because of that, I\'m skeptical of claimed MyISAM speed benefits: start doing several UPDATEs, and the queries per second will tank.</p>\n\n<p>I think you\'re better off asking "How can applications backed with InnoDB be made faster?" and the answer then deals with caching data, perhaps at the object level, in lightweight caches - there is a cost for ACID, and for, say, web applications, it\'s not really needed.</p>\n\n<p>If UPDATEs are rare (if they aren\'t, MyISAM isn\'t a good choice) then you can even use the MySQL query cache.</p>\n\n<p>memcached (<a href="http://www.danga.com/memcached/" rel="nofollow noreferrer">http://www.danga.com/memcached/</a>) is a very popular option for object caching. Depending on your application you have other options as well (HTTP caches, etc.)</p>\n'}, {'answer_id': 76789, 'author': 'MarkR', 'author_id': 13724, 'author_profile': 'https://Stackoverflow.com/users/13724', 'pm_score': 1, 'selected': False, 'text': '<p>The performance advantages of MyISAM are actually pretty minimal in some cases; you need to benchmark your own application MyISAM vs InnoDB. Using the InnoDB transactional engine exclusively gives other benefits too.</p>\n\n<p>In my testing InnoDB will use up typically about 150% more disc space than MyISAM- this is because of its block structure and lack of index compression.</p>\n\n<p>If you can afford it, just use InnoDB instead.</p>\n\n<p>As far as answering your actual question goes: If you partition your table into multiple MyISAM tables, the amount of repair needed in a crash will be much less; if your data are large, this might be a good idea anyway for other reasons.</p>\n'}, {'answer_id': 82693, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 0, 'selected': False, 'text': "<p>Your comment:</p>\n\n<blockquote>\n <p>No, the major problem is the amazingly\n disk-intensive initial import of data\n into the table. MyISAM time: 12\n minutes. InnoDB time: 3+ hrs. After my\n initial load, UPDATEs are non-existent\n and INSERTs are rare. No known\n solution to InnoDB's disappointing\n load operation.</p>\n</blockquote>\n\n<p>suggests dropping constraints and indexes, then enabling / rebuilding them after the load may significantly speed it up- I assume you tried that? Did that improve things?</p>\n"}, {'answer_id': 82840, 'author': 'Marc Gear', 'author_id': 6563, 'author_profile': 'https://Stackoverflow.com/users/6563', 'pm_score': 0, 'selected': False, 'text': '<p>This really depends a lot on how your use of the tables. If they are write heavy, then you may want to consider removing indexes, which will speed up the recovery time. If they are read heavy, you may want to consider using replication which will serialise all writes to your tables, minimising the recovery time for your read copy after a crash. </p>\n\n<p>Once thing you could do is write to an InnoDB copy of the table, and then replicate to a MyISAM copy. The performance benefits of MyISAM are mostly read-oriented anyway.</p>\n\n<p>Using replication of course, you will have lag time between reads and writes</p>\n'}, {'answer_id': 94613, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 0, 'selected': False, 'text': "<p>Get a good UPS, with decent power conditioning. Run on stable and redundant hardware.</p>\n\n<p>I don't trust MyISAM tables to ever survive a crash during a write, so I think your best bet is on reducing the occurrence of crashes (and writes).</p>\n"}, {'answer_id': 381826, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>in normal practice, you shouldn't get corruption. if you are getting corruption, you need to look at things like bad memory, bad hard drive, bad drive controller, or possibly a mysql bug.</p>\n\n<p>if you want to side-step all that, you could set up a replication slave. when the master dies, stop the replication on the slave and make it your new master. the clear the data off your old master and set it up as a slave. user down-time will be limited to the amount of time it takes to detect that the master died and bring the slave up.</p>\n\n<p>this has the added benefit of being a good way to achieve a zero-downtime backup: shut down the slave process and back up the slave.</p>\n"}, {'answer_id': 382755, 'author': 'Jonathan', 'author_id': 19272, 'author_profile': 'https://Stackoverflow.com/users/19272', 'pm_score': 1, 'selected': False, 'text': '<p>While I agree with the innodb comments, I will give a solution to your MyISAM problem.</p>\n\n<p>A good way to prevent corruption and increasing speed would be to use <a href="http://dev.mysql.com/doc/refman/5.1/en/merge-storage-engine.html" rel="nofollow noreferrer">MERGE tables</a></p>\n\n<p>You can use 2 or more MyISAM files. One is usually for backup\'d old data that isn\'t used that often and the other is newer data. Then you will have 2 FRM (the MyISAM table files) on your harddisk and one will be protected. Usually you <a href="http://dev.mysql.com/doc/refman/5.1/en/myisampack.html" rel="nofollow noreferrer">compress</a> the old MyISAM tables and then they will defiantly not be corrupted, since they become read-only.</p>\n\n<p>This technique is usually used to speed up big MyISAM tables, but you can apply it here as well.</p>\n\n<p>Hope that helped your question. While I realize it didn\'t really help crash-proof MyISAM, it does give quite a bit of protection.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12332/'] |
75,886 | <p>Before I jump headlong into C#...</p>
<p>I've always felt that C, or maybe C++, was best for developing drivers on Windows. I'm not keen on the idea of developing a driver on a .NET machine.</p>
<p>But .NET seems to be the way MS is heading for applications development, and so I'm now wondering:</p>
<ul>
<li>Are people are using C# to develop drivers?</li>
<li>Do you have to do a lot of API hooks, or does C# have the facilities to interface with the kernel without a lot of hackery?</li>
<li>Can anyone speak to the reliability and safety of running a C# program closer to Ring 0 than would normally be the case?</li>
</ul>
<p>I want my devices to be usable in C#, and if driver dev in C# is mature that's obviously the way to go, but I don't want to spend a lot of effort there if it's not recommended.</p>
<ul>
<li>What are some good resources to get started, say, developing a simple virtual serial port driver?</li>
</ul>
<p>-Adam</p>
| [{'answer_id': 75925, 'author': 'Mladen Janković', 'author_id': 6300, 'author_profile': 'https://Stackoverflow.com/users/6300', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s not direct answer to your question but if you\'re interested you might look at <a href="http://research.microsoft.com/os/Singularity/" rel="nofollow noreferrer">Singularity project</a>.</p>\n'}, {'answer_id': 75963, 'author': 'scable', 'author_id': 8942, 'author_profile': 'https://Stackoverflow.com/users/8942', 'pm_score': 2, 'selected': False, 'text': '<p>This shall help you in a way: <a href="http://www.microsoft.com/whdc/devtools/wdk/default.mspx" rel="nofollow noreferrer">Windows Driver Kit</a></p>\n'}, {'answer_id': 75974, 'author': 'Robert Gatliff', 'author_id': 9367, 'author_profile': 'https://Stackoverflow.com/users/9367', 'pm_score': 1, 'selected': False, 'text': '<p>Microsoft has a number of research projects in the area of having a managed-code OS, in other words kill with Win32 API.</p>\n\n<p>See Mary Jo Foley\'s article: <a href="http://reddevnews.com/features/article.aspx?editorialsid=2555" rel="nofollow noreferrer">Rebuilding a Legacy</a></p>\n'}, {'answer_id': 76051, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 6, 'selected': True, 'text': '<p>You can not make kernel-mode device drivers in C# as the runtime can\'t be safely loaded into ring0 and operate as expected.</p>\n\n<p>Additionally, C# doesn\'t create binaries suitable for loading as device drivers, particularly regarding entry points that drivers need to expose. The dependency on the runtime to jump in and analyze and JIT the binary during loading prohibits the direct access the driver subsystem needs to load the binary.</p>\n\n<p>There is work underway, however, to lift some device drivers into user mode, you can see an interview <a href="http://channel9.msdn.com/posts/Charles/Peter-Wieland-User-Mode-Driver-Framework/" rel="noreferrer">here</a> with Peter Wieland of the UDMF (User Mode Driver Framework) team.</p>\n\n<p>User-mode drivers would be much more suited for managed work, but you\'ll have to google a bit to find out if C# and .NET will be directly supported. All I know is that kernel level drivers are not doable in only C#.</p>\n\n<p>You can, however, probably make a C/C++ driver, and a C# service (or similar) and have the driver talk to the managed code, if you absolutely have to write a lot of code in C#.</p>\n'}, {'answer_id': 76091, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n <p>Can anyone speak to the reliability and safety of running a C# program closer to Ring 0 than would normally be the case?</p>\n</blockquote>\n\n<p>C# runs in the .NET Virtual Machine, you can't move it any closer to Ring 0 than the VM is, and the VM runs in userspace.</p>\n"}, {'answer_id': 76308, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 1, 'selected': False, 'text': '<p>Writing device drivers in .net makes no sense for current versions of windows.</p>\n\n<p><speculation><br>\nRumors are that MS is investing a lot of money in bringing Singularity to the next level. Just look for <a href="http://en.wikipedia.org/wiki/Midori_(operating_system)" rel="nofollow noreferrer">Midori</a>. But that\'s 2015+<br>\n</speculation></p>\n'}, {'answer_id': 1753457, 'author': 'Jeffrey Hantin', 'author_id': 55637, 'author_profile': 'https://Stackoverflow.com/users/55637', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re willing to have a go at a proprietary framework, <a href="http://www.jungo.com/st/windriver_usb_pci_driver_development_software.html" rel="nofollow noreferrer">Jungo\'s WinDriver toolkit</a> supports user-mode driver development (even in managed code) for USB, PCI, and PCI-E devices.</p>\n'}, {'answer_id': 50309676, 'author': 'unknown6656', 'author_id': 3902603, 'author_profile': 'https://Stackoverflow.com/users/3902603', 'pm_score': 1, 'selected': False, 'text': '<p>If I remember it correctly, the <a href="https://dokan-dev.github.io/" rel="nofollow noreferrer">Dokan Project</a> is a user-mode file system driver, which also allows .NET code to be executed by a system driver: <a href="https://github.com/dokan-dev/dokan-dotnet" rel="nofollow noreferrer">https://github.com/dokan-dev/dokan-dotnet</a>.</p>\n\n<p>So, you could develop a C# "driver" (user-mode application really), which is then called/invoked by a C++ kernel-mode driver. The kernel-driver could simply pass everything along without manipulating the data and act as a simple wrapper.\n<br/>\nNeedless to mention, that it is very unsafe and you would most likely end with a BSOD (I tried it).</p>\n\n<hr/>\n\n<p><em>Mildly related:</em></p>\n\n<p>The <a href="http://gocosmos.org" rel="nofollow noreferrer">Cosmos Project</a> is an open-source Operating system, which is developed in C# and runs<br/>\n"(kernel) drivers" and user-level applications written completely in C#/F#/VB.NET/...</p>\n\n<p>Though these are technically kernel-level drivers, the OS is no longer Windows but your own, so I guess that this is not a correct answer ......</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2915/'] |
75,891 | <p>I need an algorithm that can determine whether two images are 'similar' and recognizes similar patterns of color, brightness, shape etc.. I might need some pointers as to what parameters the human brain uses to 'categorize' images. .. </p>
<p>I have looked at hausdorff based matching but that seems mainly for matching transformed objects and patterns of shape.</p>
| [{'answer_id': 75902, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 1, 'selected': False, 'text': '<p>You could perform some sort of block-matching motion estimation between the two images and measure the overall sum of residuals and motion vector costs (much like one would do in a video encoder). This would compensate for motion; for bonus points, do affine-transformation motion estimation (compensates for zooms and stretching and similar). You could also do overlapped blocks or optical flow.</p>\n'}, {'answer_id': 75929, 'author': 'Alejandro Bologna', 'author_id': 9263, 'author_profile': 'https://Stackoverflow.com/users/9263', 'pm_score': 3, 'selected': False, 'text': '<p>You could use <a href="http://pdiff.sourceforge.net/" rel="noreferrer">Perceptual Image Diff</a></p>\n\n<p>It\'s a command line utility that compares two images using a perceptual metric. That is, it uses a computational model of the human visual system to determine if two images are visually different, so minor changes in pixels are ignored. Plus, it drastically reduces the number of false positives caused by differences in random number generation, OS or machine architecture differences.</p>\n'}, {'answer_id': 75931, 'author': 'Dima', 'author_id': 13313, 'author_profile': 'https://Stackoverflow.com/users/13313', 'pm_score': 1, 'selected': False, 'text': '<p>As a first pass, you can try using color histograms. However, you really need to narrow down your problem domain. Generic image matching is a very hard problem. </p>\n'}, {'answer_id': 75940, 'author': 'Ben', 'author_id': 11522, 'author_profile': 'https://Stackoverflow.com/users/11522', 'pm_score': 2, 'selected': False, 'text': "<p>It's a difficult problem! It depends on how accurate you need to be, and it depends on what kind of images you are working with. You can use histograms to compare colours, but that obviously doesn't take into account the spatial distribution of those colours within the images (i.e. the shapes). Edge detection followed by some kind of segmentation (i.e. picking out the shapes) can provide a pattern for matching against another image. You can use coocurence matrices to compare textures, by considering the images as matrices of pixel values, and comparing those matrices. There are some good books out there on image matching and machine vision -- A search on Amazon will find some.</p>\n\n<p>Hope this helps!</p>\n"}, {'answer_id': 75990, 'author': 'neuroguy123', 'author_id': 12529, 'author_profile': 'https://Stackoverflow.com/users/12529', 'pm_score': 0, 'selected': False, 'text': '<p>There are some good answers in the other thread on this, but I wonder if something involving a spectral analysis would work? I.e., break the image down to it\'s phase and amplitude information and compare those. This may avoid some of the issues with cropping, transformation and intensity differences. Anyway, that\'s just me speculating since this seems like an interesting problem. If you searched <a href="http://scholar.google.com" rel="nofollow noreferrer">http://scholar.google.com</a> I\'m sure you could come up with several papers on this.</p>\n'}, {'answer_id': 76036, 'author': 'willasaywhat', 'author_id': 12234, 'author_profile': 'https://Stackoverflow.com/users/12234', 'pm_score': 2, 'selected': False, 'text': "<p>This sounds like a vision problem. You might want to look into Adaptive Boosting as well as the Burns Line Extraction algorithm. The concepts in these two should help with approaching this problem. Edge detection is an even simpler place to start if you're new to vision algorithms, as it explains the basics. </p>\n\n<p>As far as parameters for categorization:</p>\n\n<ul>\n<li>Color Palette & Location (Gradient calculation, histogram of colors)</li>\n<li>Contained Shapes (Ada. Boosting/Training to detect shapes)</li>\n</ul>\n"}, {'answer_id': 83406, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Depending on how much accurate results you need, you can simply break the images in n x n pixels blocks and analyze them. If you get different results in the first block you can't stop processing, resulting in some performance improvements.</p>\n\n<p>For analyzing the squares you can for example get the sum of the color values.</p>\n"}, {'answer_id': 83463, 'author': 'petr k.', 'author_id': 15497, 'author_profile': 'https://Stackoverflow.com/users/15497', 'pm_score': 2, 'selected': False, 'text': '<p>Some image recognition software solutions are actually not purely algorithm-based, but make use of the <strong>neural network</strong> concept instead. Check out <a href="http://en.wikipedia.org/wiki/Artificial_neural_network" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Artificial_neural_network</a> and namely NeuronDotNet which also includes interesting samples: <a href="http://neurondotnet.freehostia.com/index.html" rel="nofollow noreferrer">http://neurondotnet.freehostia.com/index.html</a></p>\n'}, {'answer_id': 83486, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 7, 'selected': True, 'text': '<p>I have done something similar, by decomposing images into signatures using <a href="http://en.wikipedia.org/wiki/Wavelet" rel="nofollow noreferrer">wavelet transform</a>.</p>\n<p>My approach was to pick the most significant <em>n</em> coefficients from each transformed channel, and recording their location. This was done by sorting the list of (power,location) tuples according to abs(power). Similar images will share similarities in that they will have significant coefficients in the same places.</p>\n<p>I found it was best to transform in the image into YUV format, which effectively allows you weight similarity in shape (Y channel) and colour (UV channels).</p>\n<p>You can in find my implementation of the above in <a href="https://github.com/freespace/mactorii" rel="nofollow noreferrer">mactorii</a>, which unfortunately I haven\'t been working on as much as I should have :-)</p>\n<p>Another method, which some friends of mine have used with surprisingly good results, is to simply resize your image down to say, a 4x4 pixel and store that as your signature. How similar 2 images are can be scored by say, computing the <a href="http://en.wikipedia.org/wiki/Manhattan_distance" rel="nofollow noreferrer">Manhattan distance</a> between the 2 images, using corresponding pixels. I don\'t have the details of how they performed the resizing, so you may have to play with the various algorithms available for that task to find one which is suitable.</p>\n'}, {'answer_id': 85842, 'author': 'EPa', 'author_id': 15281, 'author_profile': 'https://Stackoverflow.com/users/15281', 'pm_score': 2, 'selected': False, 'text': '<p>There is related research using Kohonen neural networks/self organizing maps </p>\n\n<p>Both more academic systems (Google for PicSOM ) or less academic<br>\n( <a href="http://www.generation5.org/content/2004/aiSomPic.asp" rel="nofollow noreferrer">http://www.generation5.org/content/2004/aiSomPic.asp</a> , (possibly not suitable\nfor all work enviroments)) presentations exist.</p>\n'}, {'answer_id': 88429, 'author': 'jilles de wit', 'author_id': 7531, 'author_profile': 'https://Stackoverflow.com/users/7531', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve used <a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">SIFT</a> to re-detect te same object in different images. It is really powerfull but rather complex, and might be overkill. If the images are supposed to be pretty similar some simple parameters based on the difference between the two images can tell you quite a bit. Some pointers:</p>\n\n<ul>\n<li>Normalize the images i.e. make the average brightness of both images the same by calculating the average brightness of both and scaling the brightest down according to the ration (to avoid clipping at the highest level)) especially if you\'re more interested in shape than in colour.</li>\n<li>Sum of colour difference over normalized image per channel.</li>\n<li>find edges in the images and measure the distance betwee edge pixels in both images. (for shape)</li>\n<li>Divide the images in a set of discrete regions and compare the average colour of each region.</li>\n<li>Threshold the images at one (or a set of) level(s) and count the number of pixels where the resulting black/white images differ. </li>\n</ul>\n'}, {'answer_id': 774916, 'author': 'Alvis', 'author_id': 37500, 'author_profile': 'https://Stackoverflow.com/users/37500', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://www.phash.org/" rel="noreferrer">pHash</a> might interest you.</p>\n\n<blockquote>\n <p>perceptual hash n. a fingerprint of an audio, video or image file that is mathematically based on the audio or visual content contained within. Unlike cryptographic hash functions which rely on the avalanche effect of small changes in input leading to drastic changes in the output, perceptual hashes are "close" to one another if the inputs are visually or auditorily similar.</p>\n</blockquote>\n'}, {'answer_id': 6226040, 'author': 'andi', 'author_id': 2250, 'author_profile': 'https://Stackoverflow.com/users/2250', 'pm_score': 2, 'selected': False, 'text': '<p>I found this article very helpful explaining how it works:</p>\n\n<p><a href="http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html" rel="nofollow">http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html</a></p>\n'}, {'answer_id': 7770104, 'author': 'chris', 'author_id': 995701, 'author_profile': 'https://Stackoverflow.com/users/995701', 'pm_score': 2, 'selected': False, 'text': '<p>Calculating the sum of the squares of the differences of the pixel colour values of a drastically scaled-down version (eg: 6x6 pixels) works nicely. Identical images yield 0, similar images yield small numbers, different images yield big ones. </p>\n\n<p>The other guys above\'s idea to break into YUV first sounds intriguing - while my idea works great, I want my images to be calculated as "different" so that it yields a correct result - even from the perspective of a colourblind observer.</p>\n'}, {'answer_id': 40079158, 'author': 'Vivek Srinivasan', 'author_id': 2625282, 'author_profile': 'https://Stackoverflow.com/users/2625282', 'pm_score': 1, 'selected': False, 'text': '<p>Apologies for joining late in the discussion.</p>\n\n<p>We can even use ORB methodology to detect similar features points between two images.\nFollowing link gives direct implementation of ORB in python</p>\n\n<p><a href="http://scikit-image.org/docs/dev/auto_examples/plot_orb.html" rel="nofollow">http://scikit-image.org/docs/dev/auto_examples/plot_orb.html</a></p>\n\n<p>Even openCV has got direct implementation of ORB. If you more info follow the research article given below.</p>\n\n<p><a href="https://www.researchgate.net/publication/292157133_Image_Matching_Using_SIFT_SURF_BRIEF_and_ORB_Performance_Comparison_for_Distorted_Images" rel="nofollow">https://www.researchgate.net/publication/292157133_Image_Matching_Using_SIFT_SURF_BRIEF_and_ORB_Performance_Comparison_for_Distorted_Images</a></p>\n'}, {'answer_id': 49534462, 'author': 'duhaime', 'author_id': 1727392, 'author_profile': 'https://Stackoverflow.com/users/1727392', 'pm_score': 3, 'selected': False, 'text': '<p>My lab needed to solve this problem as well, and we used Tensorflow. Here\'s a <a href="https://github.com/YaleDHLab/pix-plot" rel="noreferrer">full app</a> implementation for visualizing image similarity.</p>\n\n<p>For a tutorial on vectorizing images for similarity computation, check out <a href="http://douglasduhaime.com/posts/identifying-similar-images-with-tensorflow.html" rel="noreferrer">this page</a>. Here\'s the Python (again, see the post for full workflow):</p>\n\n<pre><code>from __future__ import absolute_import, division, print_function\n\n"""\n\nThis is a modification of the classify_images.py\nscript in Tensorflow. The original script produces\nstring labels for input images (e.g. you input a picture\nof a cat and the script returns the string "cat"); this\nmodification reads in a directory of images and \ngenerates a vector representation of the image using\nthe penultimate layer of neural network weights.\n\nUsage: python classify_images.py "../image_dir/*.jpg"\n\n"""\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n"""Simple image classification with Inception.\n\nRun image classification with Inception trained on ImageNet 2012 Challenge data\nset.\n\nThis program creates a graph from a saved GraphDef protocol buffer,\nand runs inference on an input JPEG image. It outputs human readable\nstrings of the top 5 predictions along with their probabilities.\n\nChange the --image_file argument to any jpg image to compute a\nclassification of that image.\n\nPlease see the tutorial and website for a detailed description of how\nto use this script to perform image recognition.\n\nhttps://tensorflow.org/tutorials/image_recognition/\n"""\n\nimport os.path\nimport re\nimport sys\nimport tarfile\nimport glob\nimport json\nimport psutil\nfrom collections import defaultdict\nimport numpy as np\nfrom six.moves import urllib\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\n# classify_image_graph_def.pb:\n# Binary representation of the GraphDef protocol buffer.\n# imagenet_synset_to_human_label_map.txt:\n# Map from synset ID to a human readable string.\n# imagenet_2012_challenge_label_map_proto.pbtxt:\n# Text representation of a protocol buffer mapping a label to synset ID.\ntf.app.flags.DEFINE_string(\n \'model_dir\', \'/tmp/imagenet\',\n """Path to classify_image_graph_def.pb, """\n """imagenet_synset_to_human_label_map.txt, and """\n """imagenet_2012_challenge_label_map_proto.pbtxt.""")\ntf.app.flags.DEFINE_string(\'image_file\', \'\',\n """Absolute path to image file.""")\ntf.app.flags.DEFINE_integer(\'num_top_predictions\', 5,\n """Display this many predictions.""")\n\n# pylint: disable=line-too-long\nDATA_URL = \'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz\'\n# pylint: enable=line-too-long\n\n\nclass NodeLookup(object):\n """Converts integer node ID\'s to human readable labels."""\n\n def __init__(self,\n label_lookup_path=None,\n uid_lookup_path=None):\n if not label_lookup_path:\n label_lookup_path = os.path.join(\n FLAGS.model_dir, \'imagenet_2012_challenge_label_map_proto.pbtxt\')\n if not uid_lookup_path:\n uid_lookup_path = os.path.join(\n FLAGS.model_dir, \'imagenet_synset_to_human_label_map.txt\')\n self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\n\n def load(self, label_lookup_path, uid_lookup_path):\n """Loads a human readable English name for each softmax node.\n\n Args:\n label_lookup_path: string UID to integer node ID.\n uid_lookup_path: string UID to human-readable string.\n\n Returns:\n dict from integer node ID to human-readable string.\n """\n if not tf.gfile.Exists(uid_lookup_path):\n tf.logging.fatal(\'File does not exist %s\', uid_lookup_path)\n if not tf.gfile.Exists(label_lookup_path):\n tf.logging.fatal(\'File does not exist %s\', label_lookup_path)\n\n # Loads mapping from string UID to human-readable string\n proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\n uid_to_human = {}\n p = re.compile(r\'[n\\d]*[ \\S,]*\')\n for line in proto_as_ascii_lines:\n parsed_items = p.findall(line)\n uid = parsed_items[0]\n human_string = parsed_items[2]\n uid_to_human[uid] = human_string\n\n # Loads mapping from string UID to integer node ID.\n node_id_to_uid = {}\n proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\n for line in proto_as_ascii:\n if line.startswith(\' target_class:\'):\n target_class = int(line.split(\': \')[1])\n if line.startswith(\' target_class_string:\'):\n target_class_string = line.split(\': \')[1]\n node_id_to_uid[target_class] = target_class_string[1:-2]\n\n # Loads the final mapping of integer node ID to human-readable string\n node_id_to_name = {}\n for key, val in node_id_to_uid.items():\n if val not in uid_to_human:\n tf.logging.fatal(\'Failed to locate: %s\', val)\n name = uid_to_human[val]\n node_id_to_name[key] = name\n\n return node_id_to_name\n\n def id_to_string(self, node_id):\n if node_id not in self.node_lookup:\n return \'\'\n return self.node_lookup[node_id]\n\n\ndef create_graph():\n """Creates a graph from saved GraphDef file and returns a saver."""\n # Creates graph from saved graph_def.pb.\n with tf.gfile.FastGFile(os.path.join(\n FLAGS.model_dir, \'classify_image_graph_def.pb\'), \'rb\') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(graph_def, name=\'\')\n\n\ndef run_inference_on_images(image_list, output_dir):\n """Runs inference on an image list.\n\n Args:\n image_list: a list of images.\n output_dir: the directory in which image vectors will be saved\n\n Returns:\n image_to_labels: a dictionary with image file keys and predicted\n text label values\n """\n image_to_labels = defaultdict(list)\n\n create_graph()\n\n with tf.Session() as sess:\n # Some useful tensors:\n # \'softmax:0\': A tensor containing the normalized prediction across\n # 1000 labels.\n # \'pool_3:0\': A tensor containing the next-to-last layer containing 2048\n # float description of the image.\n # \'DecodeJpeg/contents:0\': A tensor containing a string providing JPEG\n # encoding of the image.\n # Runs the softmax tensor by feeding the image_data as input to the graph.\n softmax_tensor = sess.graph.get_tensor_by_name(\'softmax:0\')\n\n for image_index, image in enumerate(image_list):\n try:\n print("parsing", image_index, image, "\\n")\n if not tf.gfile.Exists(image):\n tf.logging.fatal(\'File does not exist %s\', image)\n\n with tf.gfile.FastGFile(image, \'rb\') as f:\n image_data = f.read()\n\n predictions = sess.run(softmax_tensor,\n {\'DecodeJpeg/contents:0\': image_data})\n\n predictions = np.squeeze(predictions)\n\n ###\n # Get penultimate layer weights\n ###\n\n feature_tensor = sess.graph.get_tensor_by_name(\'pool_3:0\')\n feature_set = sess.run(feature_tensor,\n {\'DecodeJpeg/contents:0\': image_data})\n feature_vector = np.squeeze(feature_set) \n outfile_name = os.path.basename(image) + ".npz"\n out_path = os.path.join(output_dir, outfile_name)\n np.savetxt(out_path, feature_vector, delimiter=\',\')\n\n # Creates node ID --> English string lookup.\n node_lookup = NodeLookup()\n\n top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]\n for node_id in top_k:\n human_string = node_lookup.id_to_string(node_id)\n score = predictions[node_id]\n print("results for", image)\n print(\'%s (score = %.5f)\' % (human_string, score))\n print("\\n")\n\n image_to_labels[image].append(\n {\n "labels": human_string,\n "score": str(score)\n }\n )\n\n # close the open file handlers\n proc = psutil.Process()\n open_files = proc.open_files()\n\n for open_file in open_files:\n file_handler = getattr(open_file, "fd")\n os.close(file_handler)\n except:\n print(\'could not process image index\',image_index,\'image\', image)\n\n return image_to_labels\n\n\ndef maybe_download_and_extract():\n """Download and extract model tar file."""\n dest_directory = FLAGS.model_dir\n if not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\n filename = DATA_URL.split(\'/\')[-1]\n filepath = os.path.join(dest_directory, filename)\n if not os.path.exists(filepath):\n def _progress(count, block_size, total_size):\n sys.stdout.write(\'\\r>> Downloading %s %.1f%%\' % (\n filename, float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print(\'Succesfully downloaded\', filename, statinfo.st_size, \'bytes.\')\n tarfile.open(filepath, \'r:gz\').extractall(dest_directory)\n\n\ndef main(_):\n maybe_download_and_extract()\n if len(sys.argv) < 2:\n print("please provide a glob path to one or more images, e.g.")\n print("python classify_image_modified.py \'../cats/*.jpg\'")\n sys.exit()\n\n else:\n output_dir = "image_vectors"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n images = glob.glob(sys.argv[1])\n image_to_labels = run_inference_on_images(images, output_dir)\n\n with open("image_to_labels.json", "w") as img_to_labels_out:\n json.dump(image_to_labels, img_to_labels_out)\n\n print("all done")\nif __name__ == \'__main__\':\n tf.app.run()\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13466/'] |
75,919 | <p>As a part of database maintenance we are thinking of taking daily backups onto an external/firewire drives. Are there any specific recommended drives for the frequent read/write operations from sql server 2000 to take backups?</p>
| [{'answer_id': 75938, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 1, 'selected': False, 'text': "<p>Whatever you do, just don't use USB 1.1.</p>\n"}, {'answer_id': 75996, 'author': 'betelgeuce', 'author_id': 366182, 'author_profile': 'https://Stackoverflow.com/users/366182', 'pm_score': 0, 'selected': False, 'text': '<p>The simple fact is that harddrives over a period of time will fail. The best two solutions\nI can recommend unfortunately do not avail of using harddrives.</p>\n\n<p>Using a tape backup, granted is slower but you get the flexibility of having the option of offsite backups. It is easy to put a tape in the boot of a car. Rotating the tapes means that you can have pretty recent protection against any unforseen situations. </p>\n\n<p>Another option is an online backup solution where the backups are encrypted and copied offsite. My reccommendation is definitly at least having some sort of offsite backup external to the building that you keep the SQL servers. After all it is "disaster" recovery.</p>\n'}, {'answer_id': 76037, 'author': 'Christopher Cashell', 'author_id': 13091, 'author_profile': 'https://Stackoverflow.com/users/13091', 'pm_score': 0, 'selected': False, 'text': "<p>Pretty much any external drive can be used here, provided it has the space to hold your backups and enough performance to get the backups there. The specifics depend on your exact requirements.</p>\n\n<p>In my experience, FireWire tends to outperform USB for disk activity, regardless of their theoretical maximum transfer rates. And FireWire 800 will perform even better yet. I have found poor performance from FireWire and USB drives when you have multiple concurrent reads/writes going on, but with backups, it's generally more large sequential reads and writes.</p>\n\n<p>Another option that is a little bit more complex to setup and manage, but can provide you with greater flexibility and performance is external SATA (eSATA). You can even get Hot Swappable external SATA enclosures for even greater convenience, and ease of taking your backups offsite.</p>\n\n<p>However, another related option that I've had excellent success with is to setup a separate server to act as your backup server. You can use whatever disk options you choose (FireWire, SATA, eSATA, SCSI, FiberChannel, iSCSI, etc), and share out that disk storage as a network share (I use NFS and Samba on a Linux box, but for a Windows oriented network, a Windows share will work fine). You can then access the shares across the network and backup multiple machines to it. Also, the separation of backup server from your production machines will give you greater flexibility if you need to take it offline for maintenance, adding/removing storage, etc.</p>\n"}, {'answer_id': 76157, 'author': 'Chris', 'author_id': 13488, 'author_profile': 'https://Stackoverflow.com/users/13488', 'pm_score': 0, 'selected': False, 'text': '<p>Drobo!</p>\n\n<p>A USB hard drive RAID array that uses normal - off the shelf hard drives. 4 bays, when you need more space, buy another hard drive. Out of bays? Buy bigger hard drives and replace your smallest in the array.</p>\n\n<p><a href="http://www.drobo.com/" rel="nofollow noreferrer">http://www.drobo.com/</a></p>\n'}, {'answer_id': 76758, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Depending on the size of the databases speed of the drive can be a real factor. I would look into something like Drobo but with an eSata or SAS interface. There is nothing more entertaining than watching a terabyte go through USB 2.0. Also, you might consider something like hyperbac or RedGate SQL Backup to compress the backup and make it easier to fit on the drive as well.</p>\n'}, {'answer_id': 77199, 'author': 'Michael K. Campbell', 'author_id': 11191, 'author_profile': 'https://Stackoverflow.com/users/11191', 'pm_score': 0, 'selected': False, 'text': '<p>For the most part, external drives aren\'t a good option - unless your database is really small. </p>\n\n<p>Other than some of the options others have listed, you can also use UNC/Network shares as a great \'off-box\' option. </p>\n\n<p>Check out the following video for some other options:<br>\n<a href="http://www.sqlservervideos.com/sqlserver-backups/backup-options" rel="nofollow noreferrer">SQL Server Backup Options (Free Video)</a></p>\n\n<p>And the videos on configuring backups on the site will show you how to specify a network path for backup purposes. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
75,924 | <p>This may be a no-brainer for the WPF cognoscenti, but I'd like to know if there's a simple way to put text on the WPF ProgressBar. To me, an empty progress bar looks naked. That's screen real estate that could carry a message about <strong>what</strong> is in progress, or even just add numbers to the representation. Now, WPF is all about containers and extensions and I'm slowly wrapping my mind around that, but since I don't see a "Text" or "Content" property, I'm thinking I'm going to have to add something to the container that is my progress bar. Is there a technique or two out there that is more natural than my original WinForms impulses will be? What's the best, most WPF-natural way to add text to that progress bar?</p>
| [{'answer_id': 75969, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 6, 'selected': True, 'text': "<p>If you are needing to have a reusable method for adding text, you can create a new Style/ControlTemplate that has an additional TextBlock to display the text. You can hijack the TextSearch.Text attached property to set the text on a progress bar. </p>\n\n<p>If it doesn't need to be reusable, simply put the progress bar in a Grid and add a TextBlock to the grid. Since WPF can compose elements together, this will work nicely.</p>\n\n<p>If you want, you can create a UserControl that exposes the ProgressBar and TextBlock as public properties, so it would be less work than creating a custom ControlTemplate.</p>\n"}, {'answer_id': 76035, 'author': 'Bob Wintemberg', 'author_id': 12999, 'author_profile': 'https://Stackoverflow.com/users/12999', 'pm_score': 3, 'selected': False, 'text': '<p>You could use an Adorner to display text over top of it.</p>\n\n<p>See <a href="http://msdn.microsoft.com/en-us/library/ms743737(VS.85).aspx#adorn_single_element" rel="noreferrer">MSDN article on Adorners</a></p>\n\n<p>You would create a class that inherits from the Adorner class. Override the OnRender method to draw the text that you want. If you want you could create a dependency property for your custom Adorner that contains the text that you want to display. Then use the example in the link I mentioned to add this Adorner to your progress bar\'s adorner layer.</p>\n'}, {'answer_id': 99245, 'author': 'SmartyP', 'author_id': 18005, 'author_profile': 'https://Stackoverflow.com/users/18005', 'pm_score': 6, 'selected': False, 'text': '<p>Both of the prior responses (creating a new <code>CustomControl</code> or an <code>Adorner</code>) are better practices, but if you just want quick and dirty (or to understand visually how to do it) then this code would work:</p>\n\n<pre><code><Grid Width="300" Height="50"> \n <ProgressBar Value="50" />\n <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">\n My Text\n </TextBlock>\n</Grid>\n</code></pre>\n\n<p>Just keep in mind that the z-index is such that the last item listed will be on top.</p>\n\n<p>Also, if you don\'t have <a href="http://www.kaxaml.com/" rel="noreferrer">Kaxaml</a> yet, be sure to pick it up - it is great for playing with XAML when you\'re trying to figure things out.</p>\n'}, {'answer_id': 30941868, 'author': 'Felix D.', 'author_id': 4610605, 'author_profile': 'https://Stackoverflow.com/users/4610605', 'pm_score': 5, 'selected': False, 'text': '<p><strong>This can be very simple</strong> (unless there are alot of ways getting this to work).</p>\n\n<p>You could use <code>Style</code> to get this done or you just overlay a <code>TextBlock</code> and a <code>ProgressBar</code>. </p>\n\n<p>I personally use this to show the percentage of the progress when waiting for completion.</p>\n\n<blockquote>\n <p>To keep it very simple I only wanted to have <strong>one</strong> <code>Binding</code> only,\n so I attached the <code>TextBock.Text</code> to the <code>ProgressBar.Value</code>.</p>\n</blockquote>\n\n<p> <strong>Then just copy the Code to get it done.</strong></p>\n\n<pre><code><Grid>\n <ProgressBar Minimum="0" \n Maximum="100" \n Value="{Binding InsertBindingHere}" \n Name="pbStatus" />\n <TextBlock Text="{Binding ElementName=pbStatus, Path=Value, StringFormat={}{0:0}%}" \n HorizontalAlignment="Center" \n VerticalAlignment="Center" />\n</Grid>\n</code></pre>\n\n<p> <strong>Here is how this could look like:</strong></p>\n\n<p> \n<a href="https://i.stack.imgur.com/OvaW7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OvaW7.png" alt="enter image description here"></a></p>\n\n<p>Check out <a href="http://www.wpf-tutorial.com/misc-controls/the-progressbar-control/" rel="noreferrer">WPF Tutorial</a> for the full post. </p>\n'}, {'answer_id': 35081337, 'author': 'AnjumSKhan', 'author_id': 3667257, 'author_profile': 'https://Stackoverflow.com/users/3667257', 'pm_score': 1, 'selected': False, 'text': '<p>Right click <code>ProgressBar</code>, and click Edit Template > Edit a Copy.</p>\n\n<p>Then put the <code>TextBlock</code> as shown below just above the closing tag of <code>Grid</code> in the Style generated by VS.</p>\n\n<pre><code> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/>\n <TextBlock Background="Transparent" Text="work in progress" Foreground="Black" TextAlignment="Center"/>\n </Grid>\n <ControlTemplate.Triggers>\n</code></pre>\n'}, {'answer_id': 54175304, 'author': 'Andrew___Pls_Support_UA', 'author_id': 4423545, 'author_profile': 'https://Stackoverflow.com/users/4423545', 'pm_score': 2, 'selected': False, 'text': '<p>ProgressBar with Text and Binding from 2 Properties ( <strong>Value/Maximum value</strong> ):</p>\n\n<pre><code><Grid>\n <ProgressBar Name="pbUsrLvl"\n Minimum="1" \n Maximum="99" \n Value="59" \n Margin="5" \n Height="24" Foreground="#FF62FF7F"/>\n <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">\n <TextBlock.Text>\n <MultiBinding StringFormat="{}UserLvl:{0}/{1}">\n <Binding Path="Value" ElementName="pbUsrLvl" />\n <Binding Path="Maximum" ElementName="pbUsrLvl" />\n </MultiBinding>\n </TextBlock.Text>\n </TextBlock>\n</Grid>\n</code></pre>\n\n<p>Rezult:</p>\n\n<p><a href="https://i.stack.imgur.com/cKsaG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cKsaG.png" alt="enter image description here"></a></p>\n\n<hr>\n\n<p>The same but <strong>with % of progress</strong> :</p>\n\n<pre><code><Grid>\n <ProgressBar Name="pbLifePassed"\n Minimum="0" \n Value="59" \n Maximum="100"\n Margin="5" Height="24" Foreground="#FF62FF7F"/>\n <TextBlock Text="{Binding ElementName=pbLifePassed, Path=Value, StringFormat={}{0:0}%}" \n HorizontalAlignment="Center" VerticalAlignment="Center" />\n</Grid>\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/2irXR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2irXR.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 58972019, 'author': 'Julian', 'author_id': 9479890, 'author_profile': 'https://Stackoverflow.com/users/9479890', 'pm_score': 1, 'selected': False, 'text': '<p>This is based on the given answers.\nSince I´m using MahApps Metro, I ended up with this:</p>\n\n<pre><code><Grid>\n <metro:MetroProgressBar x:Name="pbar" Value="50" Height="20"></metro:MetroProgressBar>\n <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}"></TextBlock>\n</Grid>\n</code></pre>\n\n<p>If you want to use the normal bar with Metro Style:</p>\n\n<pre><code><Grid>\n <ProgressBar x:Name="pbar" Value="50" Height="20" Style="{StaticResource MetroProgressBar}"></ProgressBar>\n <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}"></TextBlock>\n</Grid>\n</code></pre>\n\n<p>Same without Style:</p>\n\n<pre><code><Grid>\n <ProgressBar x:Name="pbar" Value="60" Height="20" Style="{x:Null}"></ProgressBar>\n <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ElementName=pbar, Path=Value, StringFormat={}{0:0}%}"></TextBlock>\n</Grid>\n</code></pre>\n\n<p>What is Happening?</p>\n\n<p>You have your progressbar and simply just lay text over it.\nSo you just use your progressbar as you would.\nPut the progressbar in a grid and lay an textblock in it.\nThen you can text as you wish or grab the current percenteage wich is the value from the progressbar.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336/'] |
75,935 | <p>I'm working in a .net application where we need to generate XML files on the fly based on the dataset retrieved from the db. XML schema should be based on a xsd provided. I would like to know is there any way to bind or associate a dataset or each datarow with the xsd. I dont know whether it can be done at all or i may be thinking usage of XSDs at a wrong perspective. If i'm wrong please correct me and let me know of the best way to associate a data retrieved from db to a predefined schema.Thanks.</p>
<p>Update: If my perspective on xsd is wrong please shed some light on how xsds are used(or perhaps point me to some useful links).</p>
| [{'answer_id': 76041, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 2, 'selected': False, 'text': "<p>Use the schema document as a parameter to the command line xsd.exe program included with visual studio to generate class files or typed datasets that you can include in your project/solution. These classes or datasets can be serialized to xml and will conform to the schema document you used to create them.</p>\n\n<p>The only problem with this is that it's not dynamic: you can't wait until runtime to get the schema files. But there's nothing built in that supports this otherwise.</p>\n"}, {'answer_id': 76368, 'author': 'GregK', 'author_id': 8653, 'author_profile': 'https://Stackoverflow.com/users/8653', 'pm_score': 2, 'selected': True, 'text': "<p>In addition to the solution suggested by Joel Coehoorn -- generate typed datasets or business entities from XSD -- let me add a couple of other approaches:</p>\n\n<ol>\n<li>If you use a database that supports XML type like Oracle or MS SQL Server, you can construct XML right in your SQL queries and retrieve XML directly from the database bypassing population of dataset.</li>\n<li>In case your database schema is not directly mapped to the given XSD, i.e. you already have a typed dataset or a set of XML-serializable business objects and those objects are serialized into XML that doesn't conform to XSD you're provided with, then you can use XSLT to transform your XML to another XML document which will be compliant with the given XSD.</li>\n</ol>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3113/'] |
75,937 | <p>I am using <strong>gcc</strong> for <strong>windows</strong>. The OS is <strong>windows XP</strong>.
How do I import the homepath variable into my c program so I can write to c:\%homepath%\desktop? I would like to use something similar to:</p>
<p><code>fd = fopen("C:\\%%homepath%%\\desktop\\helloworld.txt","w")</code>;</p>
| [{'answer_id': 76010, 'author': 'Lou Franco', 'author_id': 3937, 'author_profile': 'https://Stackoverflow.com/users/3937', 'pm_score': 2, 'selected': True, 'text': '<p>Use getenv() to get the value of an environment variable, then use sprintf or strcat to compose the path.</p>\n'}, {'answer_id': 76146, 'author': 'ljorquera', 'author_id': 9132, 'author_profile': 'https://Stackoverflow.com/users/9132', 'pm_score': 1, 'selected': False, 'text': '<p>Use <code>getenv("homepath")</code> to get the value of environment variable. You should handle the case in which the variable has not been defined (<code>getenv</code> returns <code>NULL</code> in that case).</p>\n\n<p>To compose the path use <code>sprintf</code></p>\n\n<pre><code>char * homepath = getenv("homepath");\n\nif(homepath == null) {\n /* variable HOMEPATH has not been defined */ \n}\n\nsprintf(path,"%s\\\\desktop\\\\helloworld.txt",homepath);\n</code></pre>\n\n<p>You should make path big enough to accomodate the value <code>homepath</code> and <code>\\\\desktop\\\\helloworld.txt</code>.</p>\n\n<p>Also note the use of <code>\\\\</code> in the string. You can\'t use single <code>\\</code>.</p>\n'}, {'answer_id': 97936, 'author': 'florin', 'author_id': 18308, 'author_profile': 'https://Stackoverflow.com/users/18308', 'pm_score': 0, 'selected': False, 'text': '<p>Note: you actually need to get the value of HOMEDRIVE as well, and prepend that to HOMEPATH. In many corporate environments, the home directories are kept on large network appliances or servers.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13461/'] |
75,943 | <p>I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: </p>
<pre><code><div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
</code></pre>
<p>I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? </p>
<p>Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?</p>
| [{'answer_id': 76003, 'author': 'Scott Nichols', 'author_id': 4299, 'author_profile': 'https://Stackoverflow.com/users/4299', 'pm_score': 4, 'selected': False, 'text': "<p>You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName. </p>\n\n<pre><code>div.innerHTML = response;\nvar scripts = div.getElementsByTagName('script');\nfor (var ix = 0; ix < scripts.length; ix++) {\n eval(scripts[ix].text);\n}\n</code></pre>\n"}, {'answer_id': 76054, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': 1, 'selected': False, 'text': '<p>The best method would probably be to identify and eval the contents of the script block directly via the DOM.</p>\n\n<p>I would be careful though.. if you are implementing this to overcome a limitation of some off site call you are opening up a security hole.</p>\n\n<p>Whatever you implement could be exploited for XSS.</p>\n'}, {'answer_id': 76068, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative is to not just dump the return from the Ajax call into the DOM using InnerHTML.</p>\n\n<p>You can insert each node dynamically, and then the script will run.</p>\n\n<p>Otherwise, the browser just assumes you are inserting a text node, and ignores the scripts.</p>\n\n<p>Using Eval is rather evil, because it requires another instance of the Javascript VM to be fired up and JIT the passed string.</p>\n'}, {'answer_id': 76100, 'author': 'Ed.', 'author_id': 12257, 'author_profile': 'https://Stackoverflow.com/users/12257', 'pm_score': 5, 'selected': True, 'text': "<p>Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:</p>\n\n<pre>\n<html>\n<head>\n<script type='text/javascript'>\nfunction addScript()\n{\n var str = "<script>alert('i am here');<\\/script>";\n var newdiv = document.createElement('div');\n newdiv.innerHTML = str;\n document.getElementById('target').appendChild(newdiv);\n}\n</script>\n</head>\n<body>\n<input type="button" value="add script" onclick="addScript()"/>\n<div>hello world</div>\n<div id="target"></div>\n</body>\n</html>\n</pre>\n"}, {'answer_id': 76387, 'author': 'Diodeus - James MacFarlane', 'author_id': 12579, 'author_profile': 'https://Stackoverflow.com/users/12579', 'pm_score': 0, 'selected': False, 'text': '<p>You can use one of the popular Ajax libraries that do this for you natively. I like <a href="http://www.prototypejs.org/" rel="nofollow noreferrer">Prototype</a>. You can just add evalScripts:true as part of your Ajax call and it happens automagically.</p>\n'}, {'answer_id': 35462561, 'author': 'Roman Vottner', 'author_id': 1377895, 'author_profile': 'https://Stackoverflow.com/users/1377895', 'pm_score': 3, 'selected': False, 'text': '<p>While the accepted answer from @Ed. does not work on current versions of Firefox, Google Chrome or Safari browsers I managed to adept his example in order to invoke dynamically added scripts.</p>\n\n<p>The necessary changes are only in the way scripts are added to DOM. Instead of adding it as <code>innerHTML</code> the trick was to create a new script element and add the actual script content as <code>innerHTML</code> to the created element and then append the script element to the actual target.</p>\n\n<pre><code><html>\n<head>\n<script type=\'text/javascript\'>\nfunction addScript()\n{\n var newdiv = document.createElement(\'div\');\n\n var p = document.createElement(\'p\');\n p.innerHTML = "Dynamically added text";\n newdiv.appendChild(p);\n\n var script = document.createElement(\'script\');\n script.innerHTML = "alert(\'i am here\');";\n newdiv.appendChild(script);\n\n document.getElementById(\'target\').appendChild(newdiv);\n}\n</script>\n</head>\n<body>\n<input type="button" value="add script" onclick="addScript()"/>\n<div>hello world</div>\n<div id="target"></div>\n</body>\n</html>\n</code></pre>\n\n<p>This works for me on Firefox 42, Google Chrome 48 and Safari 9.0.3</p>\n'}, {'answer_id': 63677480, 'author': 'Matthew Beck', 'author_id': 2413712, 'author_profile': 'https://Stackoverflow.com/users/2413712', 'pm_score': 0, 'selected': False, 'text': '<p>For those who like to live dangerously:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>// This is the HTML with script element(s) we want to inject\nvar newHtml = \'<b>After!</b>\\r\\n<\' +\n \'script>\\r\\nchangeColorEverySecond();\\r\\n</\' +\n \'script>\';\n \n// Here, we separate the script tags from the non-script HTML\nvar parts = separateScriptElementsFromHtml(newHtml);\n\nfunction separateScriptElementsFromHtml(fullHtmlString) {\n var inner = [], outer = [], m;\n while (m = /<script>([^<]*)<\\/script>/gi.exec(fullHtmlString)) {\n outer.push(fullHtmlString.substr(0, m.index));\n inner.push(m[1]);\n fullHtmlString = fullHtmlString.substr(m.index + m[0].length);\n }\n outer.push(fullHtmlString);\n return {\n html: outer.join(\'\\r\\n\'),\n js: inner.join(\'\\r\\n\')\n };\n}\n\n// In 2 seconds, inject the new HTML, and run the JS\nsetTimeout(function(){\n document.getElementsByTagName(\'P\')[0].innerHTML = parts.html;\n eval(parts.js);\n}, 2000);\n\n\n// This is the function inside the script tag\nfunction changeColorEverySecond() {\n document.getElementsByTagName(\'p\')[0].style.color = getRandomColor();\n setTimeout(changeColorEverySecond, 1000);\n}\n\n// Here is a fun fun function copied from:\n// https://stackoverflow.com/a/1484514/2413712\nfunction getRandomColor() {\n var letters = \'0123456789ABCDEF\';\n var color = \'#\';\n for (var i = 0; i < 6; i++) {\n color += letters[Math.floor(Math.random() * 16)];\n }\n return color;\n}</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Before</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4243/'] |
75,947 | <p>When using PNG files (made with Paint.NET) as background images on my web site, IE7 is changing the colors and actually displaying a darker version of my images, as seen <a href="http://twitpic.com/bud1" rel="noreferrer" title="IE7 dithering">here</a>. In this image, the dark background and background image should be both #001122, and the medium background and background image #004466. But IE7 changes the images to #000C1A and #003A5B respectively. No problem with FF3.</p>
| [{'answer_id': 75972, 'author': 'Lou Franco', 'author_id': 3937, 'author_profile': 'https://Stackoverflow.com/users/3937', 'pm_score': 2, 'selected': False, 'text': '<p>I think this has to do with Gamma correction. Take a look at this</p>\n\n<p><a href="http://www.hanselman.com/blog/GammaCorrectionAndColorCorrectionPNGIsStillTooHard.aspx" rel="nofollow noreferrer">http://www.hanselman.com/blog/GammaCorrectionAndColorCorrectionPNGIsStillTooHard.aspx</a></p>\n'}, {'answer_id': 76009, 'author': 'Álvaro González', 'author_id': 13508, 'author_profile': 'https://Stackoverflow.com/users/13508', 'pm_score': 4, 'selected': True, 'text': '<p>IE has a known bug with PNG gamma info, though I thought they had fixed it in version 7 :-?</p>\n\n<p>I remove the gamma info from PNG files using "PNG Crush". I\'ve created a right-click shortcut in Windows explorer. Further info: <a href="http://www.weirdlooking.com/blog/64" rel="nofollow noreferrer">using pngcrush in windows</a></p>\n'}, {'answer_id': 76539, 'author': 'yoavf', 'author_id': 1011, 'author_profile': 'https://Stackoverflow.com/users/1011', 'pm_score': 1, 'selected': False, 'text': '<p>Additional resource on this issue: <a href="http://www.modernblue.com/web-design-blog/tweak-that-gamma/" rel="nofollow noreferrer">http://www.modernblue.com/web-design-blog/tweak-that-gamma/</a></p>\n'}, {'answer_id': 1259253, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative to PNGOUT is TweakPNG. Comes with a GUI and no installer, very easy to remove the gAMA (just right click and delete it!)</p>\n\n<p><a href="http://entropymine.com/jason/tweakpng/" rel="nofollow noreferrer">http://entropymine.com/jason/tweakpng/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4898/'] |
75,959 | <p>I have used the Entity Framework to start a fairly simple sample project. In the project, I have created a new Entity Data Model from a SQL Server 2000 database. I am able to query the data using LINQ to Entities and display values on the screen.</p>
<p>I have an Oracle database with an extremely similar schema (I am trying to be exact but I do not know all the details of Oracle). I would like my project to be able to run on both the SQL Server and Oracle data stores with minimal effort. I was hoping that I could simply change the configuration string of my Entity Data Model and the Entity Framework would take care of the rest. However, it appears that will not work at seamlessly as I thought.</p>
<p>Has anyone done what I am trying to do? Again, I am trying to write an application that can query (and update) data from a SQL Server or Oracle database with minimal effort using the Entity Framework. The secondary goal is to not have to re-compile the application when switching back and forth between data stores. If I have to "Update Model from Database" that might be ok because I wouldn't have to recompile, but I'd prefer not to have to go this route. Does anyone know of any steps that might be necessary?</p>
| [{'answer_id': 78722, 'author': 'Min', 'author_id': 14461, 'author_profile': 'https://Stackoverflow.com/users/14461', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://blogs.msdn.com/jkowalski/archive/2008/09/09/persistence-ignorance-poco-adapter-for-entity-framework-v1.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jkowalski/archive/2008/09/09/persistence-ignorance-poco-adapter-for-entity-framework-v1.aspx</a></p>\n\n<p>The main problem is that the entity framework was not designed with persistence ignorance in mind. I would honestly look at using something other than entity framework.</p>\n'}, {'answer_id': 82947, 'author': 'Arno', 'author_id': 13685, 'author_profile': 'https://Stackoverflow.com/users/13685', 'pm_score': 3, 'selected': True, 'text': '<p>What is generally understood under the term "Persistence Ignorance" is that your entity classes are not being flooded with framework dependencies (important for N-tier scenarios). This is not the case right now, as entity classes must implement certain EF interfaces ("IPOCO"), as opposed to plain old CLR objects. As another poster has mentioned, there is a solution called <a href="http://blogs.msdn.com/jkowalski/archive/2008/09/09/persistence-ignorance-poco-adapter-for-entity-framework-v1.aspx" rel="nofollow noreferrer">Persistence Ignorance (POCO) Adapter for Entity Framework V1</a> for that, and EF V2 will support POCO out of the box.</p>\n\n<p>But I think what you really had in mind was database independence. With one big configuration XML that includes storage model, conceptual model and the mapping between those two from which a typed ObjectContext will be generated at designtime, I also find it hard to image how to transparently support two databases.</p>\n\n<p>What probably looks more promising is applying a database-independent ADO.NET provider like the one from <a href="http://www.datadirect.com" rel="nofollow noreferrer">DataDirect</a>. DataDirect has also announced EF support for Q3/2008.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1300/'] |
75,976 | <p>I've always been told that adding an element to an array happens like this:</p>
<blockquote>
<p>An empty copy of the array+1element is
created and then the data from the
original array is copied into it then
the new data for the new element is
then loaded</p>
</blockquote>
<p>If this is true, then using an array within a scenario that requires a lot of element activity is contra-indicated due to memory and CPU utilization, correct?</p>
<p>If that is the case, shouldn't you try to avoid using an array as much as possible when you will be adding a lot of elements? Should you use iStringMap instead? If so, what happens if you need more than two dimensions AND need to add a lot of element additions. Do you just take the performance hit or is there something else that should be used?</p>
| [{'answer_id': 75995, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 2, 'selected': False, 'text': "<p>When the array is resized, a new array must be allocated, and the contents copied. If you are only modifying the contents of the array, it is just a memory assignment. </p>\n\n<p>So, you should not use arrays when you don't know the size of the array, or the size is likely to change. However, if you have a fixed length array, they are an easy way of retrieving elements by index.</p>\n"}, {'answer_id': 76001, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 6, 'selected': True, 'text': '<p>Look at the generic <code>List<T></code> as a replacement for arrays. They support most of the same things arrays do, including allocating an initial storage size if you want. </p>\n'}, {'answer_id': 76004, 'author': 'Jon', 'author_id': 12261, 'author_profile': 'https://Stackoverflow.com/users/12261', 'pm_score': 1, 'selected': False, 'text': '<p>The best thing you can do is to allocate as much memory as you need upfront if possible. This will prevent <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> from having to make additional calls to get memory on the heap. Failing that then it makes sense to allocate in chunks of five or whatever number makes sense for your application.</p>\n\n<p>This is a rule you can apply to anything really.</p>\n'}, {'answer_id': 76008, 'author': 'user13288', 'author_id': 13288, 'author_profile': 'https://Stackoverflow.com/users/13288', 'pm_score': 1, 'selected': False, 'text': '<p>A standard array should be defined with a length, which reserves all of the memory that it needs in a contiguous block. Adding an item to the array would put it inside of the block of already reserved memory.</p>\n'}, {'answer_id': 76021, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': False, 'text': "<p>In general, I prefer to avoid array usage. Just use List<T>. It uses a dynamically-sized array internally, and is fast enough for most usage. If you're using multi-dimentional arrays, use List<List<List<T>>> if you have to. It's not that much worse in terms of memory, and is much simpler to add items to.</p>\n\n<p>If you're in the 0.1% of usage that requires extreme speed, make sure it's your list accesses that are really the problem before you try to optimize it.</p>\n"}, {'answer_id': 76022, 'author': 'Tom Ritter', 'author_id': 8435, 'author_profile': 'https://Stackoverflow.com/users/8435', 'pm_score': 2, 'selected': False, 'text': "<p>ArrayList and List grow the array by more than one when needed (I think it's by doubling the size, but I haven't checked the source). They are generally the best choice when you are building a dynamically sized array.</p>\n\n<p>When your benchmarks indicate that array resize is seriously slowing down your application (remember - premature optimization is the root of all evil), you can evaluate writing a custom array class with tweaked resizing behavior.</p>\n"}, {'answer_id': 76023, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 1, 'selected': False, 'text': '<p>Arrays are great for few writes and many reads, particularly those of an iterative nature - for anything else, use one of the many other data structures.</p>\n'}, {'answer_id': 76034, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re going to be adding/removing elements a lot, just use a List. If it\'s multidimensional, you can always use a List<List<int>> or something.</p>\n\n<p>On the other hand, lists are less efficient than arrays if what you\'re mostly doing is <em>traversing</em> the list, because arrays are all in one place in your CPU cache, where objects in a list are scattered all over the place.</p>\n\n<p>If you want to use an array for efficient reading but you\'re going to be "adding" elements frequently, you have two main options:</p>\n\n<p>1) Generate it as a List (or List of Lists) and then use ToArray() to turn it into an efficient array structure.</p>\n\n<p>2) Allocate the array to be larger than you need, then put the objects into the pre-allocated cells. If you end up needing even more elements than you pre-allocated, you can just reallocate the array when it fills, doubling the size each time. This gives O(log n) resizing performance instead of O(n) like it would be with a reallocate-once-per-add array. Note that this is pretty much how StringBuilder works, giving you a faster way to continually append to a string.</p>\n'}, {'answer_id': 76056, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 1, 'selected': False, 'text': "<p>You are correct an array is great for look ups. However modifications to the size of the array are costly.</p>\n\n<p>You should use a container that supports incremental size adjustments in the scenario where you're modifying the size of the array. You could use an ArrayList which allows you to set the initial size, and you could continually check the size versus the capacity and then increment the capacity by a large chunk to limit the number of resizes.</p>\n\n<p>Or you could just use a linked list. Then however look ups are slow...</p>\n"}, {'answer_id': 76059, 'author': 'Alex Lyman', 'author_id': 5897, 'author_profile': 'https://Stackoverflow.com/users/5897', 'pm_score': 4, 'selected': False, 'text': '<p>This really depends on what you mean by "add."</p>\n\n<p>If you mean:</p>\n\n<pre><code>T[] array;\nint i;\nT value;\n...\nif (i >= 0 && i <= array.Length)\n array[i] = value;\n</code></pre>\n\n<p>Then, no, this does not create a new array, and is in-fact the fastest way to alter any kind of IList in .NET.</p>\n\n<p>If, however, you\'re using something like ArrayList, List, Collection, etc. then calling the "Add" method <em>may</em> create a new array -- but they are smart about it, they don\'t just resize by 1 element, they grow geometrically, so if you\'re adding lots of values only every once in a while will it have to allocate a new array. Even then, you can use the "Capacity" property to force it to grow before hand, if you know how many elements you\'re adding (<code>list.Capacity += numberOfAddedElements</code>)</p>\n'}, {'answer_id': 76361, 'author': 'John Christensen', 'author_id': 1194, 'author_profile': 'https://Stackoverflow.com/users/1194', 'pm_score': 1, 'selected': False, 'text': "<p>If I think I'm going to be adding items to the collection a lot over its lifetime, than I'll use a List. If I know for sure what the size of the collection will be when its declared, then I'll use an array.</p>\n\n<p>Another time I generally use an array over a List is when I need to return a collection as a property of an object - I don't want callers adding items that collection via List's Add methods, but instead want them to add items to the collection via my object's interface. In that case, I'll take the internal List and call ToArray and return an array.</p>\n"}, {'answer_id': 76458, 'author': 'Rick Minerich', 'author_id': 9251, 'author_profile': 'https://Stackoverflow.com/users/9251', 'pm_score': 2, 'selected': False, 'text': '<p>Generally, if you must have the BEST indexed lookup performance it\'s best to build a List first and then turn it into a array thus paying a small penalty at first but avoiding any later. If the issue is that you will be continually adding new data and removing old data then you may want to use a ArrayList or List for convenience but keep in mind that they are just special case Arrays. When they "grow" they allocate a completely new array and copy everything into it which is extremely slow.</p>\n\n<p><a href="http://blogs.msdn.com/bclteam/articles/273454.aspx" rel="nofollow noreferrer">ArrayList</a> is just an Array which grows when needed. \nAdd is amortized O(1), just be careful to make sure the resize won\'t happen at a bad time.\nInsert is O(n) all items to the right must be moved over.\nRemove is O(n) all items to the right must be moved over.</p>\n\n<p>Also important to keep in mind that List is not a linked list. It\'s just a typed ArrayList. The List <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="nofollow noreferrer">documentation</a> does note that it performs better in most cases but does not say why.</p>\n\n<p>The best thing to do is to pick a data structure which is appropriate to your problem. This depends one a LOT of things and so you may want to browse the <a href="http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx" rel="nofollow noreferrer">System.Collections.Generic</a> Namespace. </p>\n\n<p>In this particular case I would say that if you can come up with a good key value <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="nofollow noreferrer">Dictionary</a> would be your best bet. It has insert and remove that approaches O(1). However, even with a Dictionary you have to be careful not to let it resize it\'s internal array (an O(n) operation). It\'s best to give them a lot of room by specifying a larger-then-you-expect-to-use initial capacity in the constructor. </p>\n\n<p>-Rick</p>\n'}, {'answer_id': 76520, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 1, 'selected': False, 'text': '<p>If you are going to be doing a lot of adding, <em>and</em> you will not be doing random access (such as <code>myArray[i]</code>). You could consider using a linked list (<code>LinkedList<T></code>), because it will never have to "grow" like the <code>List<T></code> implementation. Keep in mind, though, that you can only really access items in a <code>LinkedList<T></code> implementation using the <code>IEnumerable<T></code> interface.</p>\n'}, {'answer_id': 19907490, 'author': 'nawfal', 'author_id': 661933, 'author_profile': 'https://Stackoverflow.com/users/661933', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n<p>When to abandon the use of arrays</p>\n</blockquote>\n<ol>\n<li><p>First and foremost, <em>when semantics of arrays <strong>dont</strong> match with your intent</em> - Need a dynamically growing collection? A set which doesn\'t allow duplicates? A collection that has to remain immutable? Avoid arrays in all that cases. That\'s 99% of the cases. Just stating the obvious basic point.</p>\n</li>\n<li><p>Secondly, <em>when you are <strong>not</strong> coding for absolute performance criticalness</em> - That\'s about 95% of the cases. <a href="https://stackoverflow.com/questions/1168915/which-one-is-more-efficient-listint-or-int">Arrays perform better <em>marginally</em></a>, <a href="https://stackoverflow.com/questions/454916/performance-of-arrays-vs-lists">especially in iteration</a>. It almost always never matter.</p>\n</li>\n<li><p><em>When you\'re <strong>not</strong> forced by an argument with <code>params</code> keyword</em> - I just wished <code>params</code> accepted any <code>IEnumerable<T></code> or even better a language construct itself to denote a <em>sequence</em> (and not a framework type).</p>\n</li>\n<li><p><em>When you are <strong>not</strong> writing legacy code, or dealing with interop</em></p>\n</li>\n</ol>\n<p>In short, its very rare that you would actually need an array. I will add as to why may one avoid it?</p>\n<ol>\n<li><p>The biggest reason to avoid arrays imo is conceptual. Arrays are closer to implementation and farther from abstraction. Arrays conveys more <em>how it is done</em> than <em>what is done</em> which is against the spirit of high level languages. That\'s not surprising, considering arrays are closer to the metal, they are straight out of a special type (though internally array is a class). Not to be pedagogical, but arrays really do translate to a semantic meaning very very rarely required. The most useful and frequent semantics are that of a collections with any entries, sets with distinct items, key value maps etc with any combination of addable, readonly, immutable, order-respecting variants. Think about this, you might want an addable collection, or readonly collection with predefined items with no further modification, but how often does your logic look like "I want a dynamically addable collection but only a fixed number of them and they should be modifiable too"? Very rare I would say.</p>\n</li>\n<li><p>Array was designed during pre-generics era and it mimics genericity with lot of run time hacks and it will show its oddities here and there. Some of the catches I found:</p>\n<ol>\n<li><p><a href="https://stackoverflow.com/questions/4317459/why-is-array-co-variance-considered-so-horrible">Broken covariance.</a></p>\n<pre><code> string[] strings = ...\n object[] objects = strings;\n objects[0] = 1; //compiles, but gives a runtime exception.\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/6705583/indexers-in-list-vs-array">Arrays can give you reference to a struct!</a>. That\'s unlike anywhere else. A sample:</p>\n<pre><code> struct Value { public int mutable; }\n\n var array = new[] { new Value() }; \n array[0].mutable = 1; //<-- compiles !\n //a List<Value>[0].mutable = 1; doesnt compile since editing a copy makes no sense\n print array[0].mutable // 1, expected or unexpected? confusing surely\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/19888123/t-contains-for-struct-and-class-behaving-differently">Run time implemented methods like <code>ICollection<T>.Contains</code> can be different for structs and classes</a>. It\'s not a big deal, but if you forget to override <em>non generic <code>Equals</code></em> correctly for reference types expecting generic collection to look for <em>generic <code>Equals</code></em>, you will get incorrect results.</p>\n<pre><code> public class Class : IEquatable<Class>\n {\n public bool Equals(Class other)\n {\n Console.WriteLine("generic");\n return true;\n }\n public override bool Equals(object obj)\n {\n Console.WriteLine("non generic");\n return true;\n } \n }\n\n public struct Struct : IEquatable<Struct>\n {\n public bool Equals(Struct other)\n {\n Console.WriteLine("generic");\n return true;\n }\n public override bool Equals(object obj)\n {\n Console.WriteLine("non generic");\n return true;\n } \n }\n\n class[].Contains(test); //prints "non generic"\n struct[].Contains(test); //prints "generic"\n</code></pre>\n</li>\n<li><p>The <code>Length</code> property and <code>[]</code> indexer on <code>T[]</code> seem to be regular properties that you can access through reflection (which should involve some magic), but when it comes to expression trees you have to spit out the exact same code the compiler does. There are <code>ArrayLength</code> and <code>ArrayIndex</code> methods to do that separately. One such <a href="https://stackoverflow.com/questions/19336342/how-to-get-memberinfo-of-arraylength-type-expressions">question here</a>. Another example:</p>\n<pre><code> Expression<Func<string>> e = () => new[] { "a" }[0];\n //e.Body.NodeType == ExpressionType.ArrayIndex\n\n Expression<Func<string>> e = () => new List<string>() { "a" }[0];\n //e.Body.NodeType == ExpressionType.Call;\n</code></pre>\n</li>\n<li><p><a href="https://stackoverflow.com/questions/26475362/why-does-ilisttarray-readonly-true-but-ilistarray-readonly-false">Yet another one</a>. <code>string[].IsReadOnly</code> returns <code>false</code>, but if you are casting, <code>IList<string>.IsReadOnly</code> returns <code>true</code>.</p>\n</li>\n<li><p>Type checking gone wrong: <code>(object)new ConsoleColor[0] is int[]</code> returns <code>true</code>, whereas <code>new ConsoleColor[0] is int[]</code> returns <code>false</code>. Same is true for <code>uint[]</code> and <code>int[]</code> comparisons. No such problems if you use any other collection types.</p>\n</li>\n</ol>\n</li>\n</ol>\n<blockquote>\n<p>How to abandon the use of arrays.</p>\n</blockquote>\n<p>The most commonly used substitute is <code>List<T></code> which has a cleaner API. But it is a dynamically growing structure which means you can add to a <code>List<T></code> at the end or insert anywhere to any capacity. There is no substitute for the exact behaviour of an array, but people mostly use arrays as readonly collection where you can\'t add anything to its end. A substitute is <code>ReadOnlyCollection<T></code>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/730/'] |
75,978 | <p>In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>
| [{'answer_id': 76067, 'author': 'Santiago Palladino', 'author_id': 12791, 'author_profile': 'https://Stackoverflow.com/users/12791', 'pm_score': 3, 'selected': False, 'text': '<p>Use the following (remember to include System.Configuration assembly)</p>\n\n<pre><code>ConfigurationManager.OpenExeConfiguration(exePath)\n</code></pre>\n'}, {'answer_id': 76071, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 2, 'selected': False, 'text': '<p>You can set it by creating a new app domain:</p>\n\n<pre><code>AppDomainSetup domainSetup = new AppDomainSetup();\ndomainSetup.ConfigurationFile = fileLocation;\nAppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup);\n</code></pre>\n'}, {'answer_id': 76085, 'author': 'jeff.willis', 'author_id': 9829, 'author_profile': 'https://Stackoverflow.com/users/9829', 'pm_score': 5, 'selected': True, 'text': '<pre><code>using System.Configuration; \n\nConfiguration config =\nConfigurationManager.OpenExeConfiguration("C:\\Test.exe");\n</code></pre>\n\n<p>You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is <strong><em>not</em></strong> "C:\\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\\Test.exe.config" it will look for "C:\\Test.exe.config.config" Kinda lame, but understandable, I guess.</p>\n\n<p>Reference here: <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx</a></p>\n'}, {'answer_id': 18218068, 'author': 'CodeNaked', 'author_id': 142794, 'author_profile': 'https://Stackoverflow.com/users/142794', 'pm_score': 3, 'selected': False, 'text': '<p>It appears that you can use the <a href="http://msdn.microsoft.com/en-us/library/37z40s1c.aspx" rel="nofollow noreferrer"><code>AppDomain.SetData</code></a> method to achieve this. The documentation states:</p>\n\n<blockquote>\n <p>You cannot insert or modify system entries with this method.</p>\n</blockquote>\n\n<p>Regardless, doing so does appear to work. The documentation for the <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx" rel="nofollow noreferrer"><code>AppDomain.GetData</code></a> method lists the system entries available, of interest is the <code>"APP_CONFIG_FILE"</code> entry.</p>\n\n<p>If we set the <code>"APP_CONFIG_FILE"</code> before any application settings are used, we can modify where the <code>app.config</code> is loaded from. For example:</p>\n\n<pre><code>public class Program\n{\n public static void Main()\n {\n AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\\Temp\\test.config");\n //...\n }\n}\n</code></pre>\n\n<p>I found this solution documented in <a href="http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx" rel="nofollow noreferrer">this blog</a> and a more complete answer (to a related question) can be found <a href="https://stackoverflow.com/a/6151688/142794">here</a>.</p>\n'}, {'answer_id': 62144686, 'author': 'Balaji Dinakaran', 'author_id': 4890791, 'author_profile': 'https://Stackoverflow.com/users/4890791', 'pm_score': 0, 'selected': False, 'text': '<pre><code>AppDomainSetup domainSetup = new AppDomainSetup();\n domainSetup.ConfigurationFile = @"D:\\Mine\\Company\\";\n string browserName = ConfigurationManager.AppSettings["browser"];\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2748/'] |
75,980 | <p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p>
<p>Use escape:</p>
<pre><code>escape("% +&=");
</code></pre>
<p>OR</p>
<p>use encodeURI() / encodeURIComponent()</p>
<pre><code>encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
</code></pre>
| [{'answer_id': 75989, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 5, 'selected': False, 'text': '<p>encodeURI() - the escape() function is for javascript escaping, not HTTP.</p>\n'}, {'answer_id': 76119, 'author': 'Pseudo Masochist', 'author_id': 8529, 'author_profile': 'https://Stackoverflow.com/users/8529', 'pm_score': 3, 'selected': False, 'text': "<p>Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().</p>\n"}, {'answer_id': 3608791, 'author': 'Arne Evertsson', 'author_id': 16686, 'author_profile': 'https://Stackoverflow.com/users/16686', 'pm_score': 12, 'selected': True, 'text': '<h1>escape()</h1>\n<p>Don\'t use it!\n<code>escape()</code> is defined in section <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string" rel="noreferrer">B.2.1.2 escape</a> and the <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers" rel="noreferrer">introduction text of Annex B</a> says:</p>\n<blockquote>\n<p>... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...<br />\n... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....</p>\n</blockquote>\n<p>Behaviour:</p>\n<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape</a></p>\n<p>Special characters are encoded with the exception of: @*_+-./</p>\n<p>The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: <code>%xx</code>.</p>\n<p>For characters with a greater code unit, the four-digit format <code>%uxxxx</code> is used. This is not allowed within a query string (as defined in <a href="https://www.rfc-editor.org/rfc/rfc3986#section-3.4" rel="noreferrer">RFC3986</a>):</p>\n<pre><code>query = *( pchar / "/" / "?" )\npchar = unreserved / pct-encoded / sub-delims / ":" / "@"\nunreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"\npct-encoded = "%" HEXDIG HEXDIG\nsub-delims = "!" / "$" / "&" / "\'" / "(" / ")"\n / "*" / "+" / "," / ";" / "="\n</code></pre>\n<p>A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by <code>u</code> is not allowed.</p>\n<h1>encodeURI()</h1>\n<p>Use encodeURI when you want a working URL. Make this call:</p>\n<pre><code>encodeURI("http://www.example.org/a file with spaces.html")\n</code></pre>\n<p>to get:</p>\n<pre><code>http://www.example.org/a%20file%20with%20spaces.html\n</code></pre>\n<p>Don\'t call encodeURIComponent since it would destroy the URL and return</p>\n<pre><code>http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html\n</code></pre>\n<p>Note that encodeURI, like encodeURIComponent, does not escape the \' character.</p>\n<h1>encodeURIComponent()</h1>\n<p>Use encodeURIComponent when you want to encode the value of a URL parameter.</p>\n<pre><code>var p1 = encodeURIComponent("http://example.org/?a=12&b=55")\n</code></pre>\n<p>Then you may create the URL you need:</p>\n<pre><code>var url = "http://example.net/?param1=" + p1 + "&param2=99";\n</code></pre>\n<p>And you will get this complete URL:</p>\n<p><code>http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99</code></p>\n<p>Note that encodeURIComponent does not escape the <code>\'</code> character. A common bug is to use it to create html attributes such as <code>href=\'MyUrl\'</code>, which could suffer an injection bug. If you are constructing html from strings, either use <code>"</code> instead of <code>\'</code> for attribute quotes, or add an extra layer of encoding (<code>\'</code> can be encoded as %27).</p>\n<p>For more information on this type of encoding you can check: <a href="http://en.wikipedia.org/wiki/Percent-encoding" rel="noreferrer">http://en.wikipedia.org/wiki/Percent-encoding</a></p>\n'}, {'answer_id': 12796866, 'author': 'Damien', 'author_id': 438970, 'author_profile': 'https://Stackoverflow.com/users/438970', 'pm_score': 6, 'selected': False, 'text': '<p>I found this article enlightening :\n<a href="http://unixpapa.com/js/querystring.html" rel="noreferrer">Javascript Madness: Query String Parsing</a></p>\n\n<p>I found it when I was trying to undersand why decodeURIComponent was not decoding \'+\' correctly. Here is an extract:</p>\n\n<pre><code>String: "A + B"\nExpected Query String Encoding: "A+%2B+B"\nescape("A + B") = "A%20+%20B" Wrong!\nencodeURI("A + B") = "A%20+%20B" Wrong!\nencodeURIComponent("A + B") = "A%20%2B%20B" Acceptable, but strange\n\nEncoded String: "A+%2B+B"\nExpected Decoding: "A + B"\nunescape("A+%2B+B") = "A+++B" Wrong!\ndecodeURI("A+%2B+B") = "A+++B" Wrong!\ndecodeURIComponent("A+%2B+B") = "A+++B" Wrong!\n</code></pre>\n'}, {'answer_id': 16435373, 'author': 'Kirankumar Sripati', 'author_id': 2191887, 'author_profile': 'https://Stackoverflow.com/users/2191887', 'pm_score': 5, 'selected': False, 'text': '<p>encodeURIComponent doesn\'t encode <code>-_.!~*\'()</code>, causing problem in posting data to php in xml string.</p>\n\n<p>For example:<br/>\n<code><xml><text x="100" y="150" value="It\'s a value with single quote" />\n</xml></code></p>\n\n<p>General escape with <code>encodeURI</code><br/>\n<code>%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It\'s%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E</code></p>\n\n<p>You can see, single quote is not encoded.\nTo resolve issue I created two functions to solve issue in my project, for Encoding URL:</p>\n\n<pre><code>function encodeData(s:String):String{\n return encodeURIComponent(s).replace(/\\-/g, "%2D").replace(/\\_/g, "%5F").replace(/\\./g, "%2E").replace(/\\!/g, "%21").replace(/\\~/g, "%7E").replace(/\\*/g, "%2A").replace(/\\\'/g, "%27").replace(/\\(/g, "%28").replace(/\\)/g, "%29");\n}\n</code></pre>\n\n<p>For Decoding URL:</p>\n\n<pre><code>function decodeData(s:String):String{\n try{\n return decodeURIComponent(s.replace(/\\%2D/g, "-").replace(/\\%5F/g, "_").replace(/\\%2E/g, ".").replace(/\\%21/g, "!").replace(/\\%7E/g, "~").replace(/\\%2A/g, "*").replace(/\\%27/g, "\'").replace(/\\%28/g, "(").replace(/\\%29/g, ")"));\n }catch (e:Error) {\n }\n return "";\n}\n</code></pre>\n'}, {'answer_id': 17235463, 'author': 'molokoloco', 'author_id': 174449, 'author_profile': 'https://Stackoverflow.com/users/174449', 'pm_score': 1, 'selected': False, 'text': '<p>I have this function...</p>\n\n<pre><code>var escapeURIparam = function(url) {\n if (encodeURIComponent) url = encodeURIComponent(url);\n else if (encodeURI) url = encodeURI(url);\n else url = escape(url);\n url = url.replace(/\\+/g, \'%2B\'); // Force the replacement of "+"\n return url;\n};\n</code></pre>\n'}, {'answer_id': 18126158, 'author': 'veeTrain', 'author_id': 469643, 'author_profile': 'https://Stackoverflow.com/users/469643', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve found that experimenting with the various methods is a good sanity check even after having a good handle of what their various uses and capabilities are.</p>\n\n<p>Towards that end I have found <a href="http://www.the-art-of-web.com/javascript/escape/" rel="nofollow">this website</a> extremely useful to confirm my suspicions that I am doing something appropriately. It has also proven useful for decoding an encodeURIComponent\'ed string which can be rather challenging to interpret. A great bookmark to have:</p>\n\n<p><a href="http://www.the-art-of-web.com/javascript/escape/" rel="nofollow">http://www.the-art-of-web.com/javascript/escape/</a></p>\n'}, {'answer_id': 23250699, 'author': 'Jerry Joseph', 'author_id': 1001217, 'author_profile': 'https://Stackoverflow.com/users/1001217', 'pm_score': 4, 'selected': False, 'text': '<p>I recommend not to use one of those methods as is. Write your own function which does the right thing.</p>\n\n<p>MDN has given a good example on url encoding shown below.</p>\n\n<pre><code>var fileName = \'my file(2).txt\';\nvar header = "Content-Disposition: attachment; filename*=UTF-8\'\'" + encodeRFC5987ValueChars(fileName);\n\nconsole.log(header); \n// logs "Content-Disposition: attachment; filename*=UTF-8\'\'my%20file%282%29.txt"\n\n\nfunction encodeRFC5987ValueChars (str) {\n return encodeURIComponent(str).\n // Note that although RFC3986 reserves "!", RFC5987 does not,\n // so we do not need to escape it\n replace(/[\'()]/g, escape). // i.e., %27 %28 %29\n replace(/\\*/g, \'%2A\').\n // The following are not required for percent-encoding per RFC5987, \n // so we can allow for a little better readability over the wire: |`^\n replace(/%(?:7C|60|5E)/g, unescape);\n}\n</code></pre>\n\n<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent</a></p>\n'}, {'answer_id': 23842171, 'author': 'Johann Echavarria', 'author_id': 2391782, 'author_profile': 'https://Stackoverflow.com/users/2391782', 'pm_score': 9, 'selected': False, 'text': '<p>The difference between <code>encodeURI()</code> and <code>encodeURIComponent()</code> are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:</p>\n\n<p><img src="https://i.imgur.com/rHWC1r1.png" alt="Table with the ten differences between encodeURI and encodeURIComponent"></p>\n\n<p>I generated this table easily with <strong>console.table</strong> in Google Chrome with this code:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [];\r\nfor(var i=0;i<256;i++) {\r\n var char=String.fromCharCode(i);\r\n if(encodeURI(char)!==encodeURIComponent(char)) {\r\n arr.push({\r\n character:char,\r\n encodeURI:encodeURI(char),\r\n encodeURIComponent:encodeURIComponent(char)\r\n });\r\n }\r\n}\r\nconsole.table(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 33019871, 'author': '30thh', 'author_id': 608164, 'author_profile': 'https://Stackoverflow.com/users/608164', 'pm_score': 4, 'selected': False, 'text': "<p>Small comparison table Java vs. JavaScript vs. PHP.</p>\n\n<pre><code>1. Java URLEncoder.encode (using UTF8 charset)\n2. JavaScript encodeURIComponent\n3. JavaScript escape\n4. PHP urlencode\n5. PHP rawurlencode\n\nchar JAVA JavaScript --PHP---\n[ ] + %20 %20 + %20\n[!] %21 ! %21 %21 %21\n[*] * * * %2A %2A\n['] %27 ' %27 %27 %27 \n[(] %28 ( %28 %28 %28\n[)] %29 ) %29 %29 %29\n[;] %3B %3B %3B %3B %3B\n[:] %3A %3A %3A %3A %3A\n[@] %40 %40 @ %40 %40\n[&] %26 %26 %26 %26 %26\n[=] %3D %3D %3D %3D %3D\n[+] %2B %2B + %2B %2B\n[$] %24 %24 %24 %24 %24\n[,] %2C %2C %2C %2C %2C\n[/] %2F %2F / %2F %2F\n[?] %3F %3F %3F %3F %3F\n[#] %23 %23 %23 %23 %23\n[[] %5B %5B %5B %5B %5B\n[]] %5D %5D %5D %5D %5D\n----------------------------------------\n[~] %7E ~ %7E %7E ~\n[-] - - - - -\n[_] _ _ _ _ _\n[%] %25 %25 %25 %25 %25\n[\\] %5C %5C %5C %5C %5C\n----------------------------------------\nchar -JAVA- --JavaScript-- -----PHP------\n[ä] %C3%A4 %C3%A4 %E4 %C3%A4 %C3%A4\n[ф] %D1%84 %D1%84 %u0444 %D1%84 %D1%84\n</code></pre>\n"}, {'answer_id': 43537042, 'author': 'Gaurav Tiwari', 'author_id': 7220283, 'author_profile': 'https://Stackoverflow.com/users/7220283', 'pm_score': 3, 'selected': False, 'text': '<p>For the purpose of encoding javascript has given three inbuilt functions -</p>\n\n<ol>\n<li><p><code>escape()</code> - does not encode <code>@*/+</code>\nThis method is deprecated after the ECMA 3 so it should be avoided.</p></li>\n<li><p><code>encodeURI()</code> - does not encode <code>~!@#$&*()=:/,;?+\'</code>\nIt assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.\nThis method is used when the intent is to convert the complete URL instead of some special segment of URL.\nExample - <code>encodeURI(\'http://stackoverflow.com\');</code>\nwill give - <a href="http://stackoverflow.com">http://stackoverflow.com</a></p></li>\n<li><p><code>encodeURIComponent()</code> - does not encode <code>- _ . ! ~ * \' ( )</code>\nThis function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. This method should be used to convert a component of URL. For instance some user input needs to be appended\nExample - <code>encodeURIComponent(\'http://stackoverflow.com\');</code>\nwill give - http%3A%2F%2Fstackoverflow.com</p></li>\n</ol>\n\n<p><em>All this encoding is performed in UTF 8 i.e the characters will be converted in UTF-8 format.</em> </p>\n\n<p><strong><em>encodeURIComponent differ from encodeURI in that it encode reserved characters and Number sign # of encodeURI</em></strong></p>\n'}, {'answer_id': 46441344, 'author': 'Michael', 'author_id': 599912, 'author_profile': 'https://Stackoverflow.com/users/599912', 'pm_score': 2, 'selected': False, 'text': '<p>The accepted answer is good.\nTo extend on the last part:</p>\n\n<blockquote>\n <p>Note that encodeURIComponent does not escape the \' character. A common\n bug is to use it to create html attributes such as href=\'MyUrl\', which\n could suffer an injection bug. If you are constructing html from\n strings, either use " instead of \' for attribute quotes, or add an\n extra layer of encoding (\' can be encoded as %27).</p>\n</blockquote>\n\n<p>If you want to be on the safe side, <a href="https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_unreserved_characters" rel="nofollow noreferrer">percent encoding unreserved characters</a> should be encoded as well. </p>\n\n<p>You can use this method to escape them (source <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow noreferrer">Mozilla</a>)</p>\n\n<pre><code>function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!\'()*]/g, function(c) {\n return \'%\' + c.charCodeAt(0).toString(16);\n });\n}\n\n// fixedEncodeURIComponent("\'") --> "%27"\n</code></pre>\n'}, {'answer_id': 48697555, 'author': 'ryanpcmcquen', 'author_id': 2662028, 'author_profile': 'https://Stackoverflow.com/users/2662028', 'pm_score': 2, 'selected': False, 'text': '<p>Modern rewrite of @johann-echavarria\'s answer:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(\r\n Array(256)\r\n .fill()\r\n .map((ignore, i) => String.fromCharCode(i))\r\n .filter(\r\n (char) =>\r\n encodeURI(char) !== encodeURIComponent(char)\r\n ? {\r\n character: char,\r\n encodeURI: encodeURI(char),\r\n encodeURIComponent: encodeURIComponent(char)\r\n }\r\n : false\r\n )\r\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or if you can use a table, replace <code>console.log</code> with <code>console.table</code> (for the prettier output).</p>\n'}, {'answer_id': 54630088, 'author': 'akinuri', 'author_id': 2202732, 'author_profile': 'https://Stackoverflow.com/users/2202732', 'pm_score': 2, 'selected': False, 'text': '<p>Inspired by <a href="https://stackoverflow.com/questions/75980/when-are-you-supposed-to-use-escape-instead-of-encodeuri-encodeuricomponent/23842171#23842171">Johann\'s table</a>, I\'ve decided to extend the table. I wanted to see which ASCII characters get encoded.</p>\n\n<p><a href="https://i.stack.imgur.com/gjKxF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gjKxF.png" alt="screenshot of console.table"></a></p>\n\n<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">\r\n<div class="snippet-code snippet-currently-hidden">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var ascii = " !\\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";\r\n\r\nvar encoded = [];\r\n\r\nascii.split("").forEach(function (char) {\r\n var obj = { char };\r\n if (char != encodeURI(char))\r\n obj.encodeURI = encodeURI(char);\r\n if (char != encodeURIComponent(char))\r\n obj.encodeURIComponent = encodeURIComponent(char);\r\n if (obj.encodeURI || obj.encodeURIComponent)\r\n encoded.push(obj);\r\n});\r\n\r\nconsole.table(encoded);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.</p>\n\n<hr>\n\n<p>Just to be extra, I\'m adding another table for <a href="http://php.net/manual/en/function.urlencode.php" rel="nofollow noreferrer"><code>urlencode()</code></a> vs <a href="http://php.net/manual/en/function.rawurlencode.php" rel="nofollow noreferrer"><code>rawurlencode()</code></a>. The only difference seems to be the encoding of space character.</p>\n\n<p><a href="https://i.stack.imgur.com/gJnmU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gJnmU.png" alt="screenshot of console.table"></a></p>\n\n<pre><code><script>\n<?php\n$ascii = str_split(" !\\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);\n$encoded = [];\nforeach ($ascii as $char) {\n $obj = ["char" => $char];\n if ($char != urlencode($char))\n $obj["urlencode"] = urlencode($char);\n if ($char != rawurlencode($char))\n $obj["rawurlencode"] = rawurlencode($char);\n if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))\n $encoded[] = $obj;\n}\necho "var encoded = " . json_encode($encoded) . ";";\n?>\nconsole.table(encoded);\n</script>\n</code></pre>\n'}, {'answer_id': 62436236, 'author': 'HoldOffHunger', 'author_id': 2430549, 'author_profile': 'https://Stackoverflow.com/users/2430549', 'pm_score': 3, 'selected': False, 'text': '<p>Just try <code>encodeURI()</code> and <code>encodeURIComponent()</code> yourself...</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(encodeURIComponent(\'@#$%^&*\'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Input: <code>@#$%^&*</code>. Output: <code>%40%23%24%25%5E%26*</code>. So, wait, what happened to <code>*</code>? Why wasn\'t this converted? It could definitely cause problems if you tried to do <code>linux command "$string"</code>. TLDR: You actually want <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow noreferrer"><code>fixedEncodeURIComponent()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI" rel="nofollow noreferrer"><code>fixedEncodeURI()</code></a>. Long-story...</p>\n<p><em><strong>When to use <code>encodeURI()</code>?</strong></em> Never. <code>encodeURI()</code> fails to adhere to RFC3986 with regard to bracket-encoding. Use <code>fixedEncodeURI()</code>, as defined and further explained at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI" rel="nofollow noreferrer"><strong>MDN encodeURI() Documentation</strong></a>...</p>\n<blockquote>\n<pre><code>function fixedEncodeURI(str) {\n return encodeURI(str).replace(/%5B/g, \'[\').replace(/%5D/g, \']\');\n}\n</code></pre>\n</blockquote>\n<p><em><strong>When to use <code>encodeURIComponent()</code>?</strong></em> Never. <code>encodeURIComponent()</code> fails to adhere to RFC3986 with regard to encoding: <code>!\'()*</code>. Use <code>fixedEncodeURIComponent()</code>, as defined and further explained at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow noreferrer"><strong>MDN encodeURIComponent() Documentation</strong></a>...</p>\n<blockquote>\n<pre><code>function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!\'()*]/g, function(c) {\n return \'%\' + c.charCodeAt(0).toString(16);\n });\n}\n</code></pre>\n</blockquote>\n<p>Then you can use <code>fixedEncodeURI()</code> to encode a single URL piece, whereas <code>fixedEncodeURIComponent()</code> will encode URL pieces and connectors; or, simply, <code>fixedEncodeURI()</code> will not encode <code>+@?=:#;,$&</code> (as <code>&</code> and <code>+</code> are common URL operators), but <code>fixedEncodeURIComponent()</code> will.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/75980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1341/'] |
76,002 | <p>My understanding of the Git pack file format is something like:
<img src="https://content.screencast.com/users/aggieben/folders/Jing/media/dc42fabf-6fd6-47f3-9244-446b9ec04494/2008-09-16_1424.png" alt="alt text"></p>
<p>Where the table is 32-bits wide, and the first three 32-bit words are the pack file header. The last row of 32 bits are the first 4 bytes of an entry. As I understand it, the size of the entry is specified by consecutive bytes with the MSB set, followed by compressed data. </p>
<p>In the first byte whose MSB is not set, is the MSB part of the compressed data, or is it a gap? If it's part of the compressed data, how can you guarantee that when the data is compressed that bit won't be set?</p>
| [{'answer_id': 76030, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 4, 'selected': True, 'text': '<p>My reading of the <a href="http://repo.or.cz/w/git.git?a=blob;f=Documentation/technical/pack-format.txt;h=1803e64e465fa4f8f0fe520fc0fd95d0c9def5bd;hb=HEAD" rel="noreferrer">pack file documentation</a> indicates that the last byte of the size (offset 15 in your example) would have the MSB set to 0.</p>\n'}, {'answer_id': 2947542, 'author': 'Scott Chacon', 'author_id': 119313, 'author_profile': 'https://Stackoverflow.com/users/119313', 'pm_score': 3, 'selected': False, 'text': '<p>There is also some graphical documentation explaining some of the format <a href="http://shafiulazam.com/gitbook/7_the_packfile.html" rel="nofollow noreferrer">here</a>. This section is no longer present in Community book, but still available it the location above.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3279/'] |
76,042 | <p>Has anyone used the new Java 1.6 JDK tool, <a href="http://web.archive.org/web/20070724060100/https://visualvm.dev.java.net/" rel="nofollow noreferrer">VisualVM</a>, to profile a production application and how does the application perform while being profiled?</p>
<p>The documentation say that it is designed for both Production and Development use, but based on previous profiling experience, with other profiling tools, I am hesitant.</p>
| [{'answer_id': 76649, 'author': 'BenCourliss', 'author_id': 8907, 'author_profile': 'https://Stackoverflow.com/users/8907', 'pm_score': 3, 'selected': False, 'text': '<p>While i haven\'t personally used VisualVM, I saw this <a href="http://blog.xebia.com/loitering-objects-make-web-company-lose-money/" rel="nofollow noreferrer">blog post</a> just today that might have some useful information for you. He talks about profiling a production app using it.</p>\n'}, {'answer_id': 153348, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 1, 'selected': False, 'text': "<p>I tried it on a dev box and found that when I turned off profiling it would shut Tomcat down unexpectedly. I'd be very cautious about rolling this out to production- can you simulate load in a staging environment instead? It's not as good as the real thing, but it probably won't get you fired if it goes wrong...</p>\n"}, {'answer_id': 157670, 'author': 'Matt N', 'author_id': 20605, 'author_profile': 'https://Stackoverflow.com/users/20605', 'pm_score': 0, 'selected': False, 'text': '<p>It is possible to remote connect to your server from a different computer using VisualVM. You just need to right click on the "Remote" node and say "Add Remote Host." </p>\n\n<p>This would at least eliminate the VisualVM overhead (if there is any) from impacting performance while it is running.</p>\n\n<p>This may not eliminate all performance concerns, especially in Production environments, but it will help a little.</p>\n'}, {'answer_id': 1534120, 'author': 'Kevin Peterson', 'author_id': 88313, 'author_profile': 'https://Stackoverflow.com/users/88313', 'pm_score': 1, 'selected': False, 'text': "<p>I've used VisualVM before to profile something running locally. A big win was that I just start it up, and it can connect to the running JVM. It's easier to use than other profiling tools I've used before and didn't seem to have as much overhead.</p>\n\n<p>I think it does sampling. The overhead on a CPU intensive application didn't seem significant. I didn't measure anything (I was interested in how my app performed, not how the tool performed), but it definitely didn't have the factor of 10 slowdown I'm used to seeing from profiling.</p>\n"}, {'answer_id': 1534221, 'author': 'gibbss', 'author_id': 116621, 'author_profile': 'https://Stackoverflow.com/users/116621', 'pm_score': 0, 'selected': False, 'text': "<p>I've used the Net Beans profiler which uses the same underpinnings as Visual VM.</p>\n\n<p>I was working with an older version of Weblogic, which meant using the 1.5 JVM, so I couldn't do a dynamic attach. The application I was profiling had several thousand classes and my workstation was pretty much unusable while the profiler instrumented them all. Once instrumentation was complete, the system was sluggish but not completely unusable. The amount of slowdown really depends on what you need to capture. The basic CPU metrics are pretty light weight. Profiling memory allocation slows things down a lot.</p>\n\n<p>I would not use it on a production system. Aside from the potential for slowdown, I eventually ran out of PermGen space because the profiler reinstruments and reloads classes when you change settings. (This may be fixed in the 1.6 agent, I don't know)</p>\n"}, {'answer_id': 1540341, 'author': 'hennings', 'author_id': 77418, 'author_profile': 'https://Stackoverflow.com/users/77418', 'pm_score': 1, 'selected': False, 'text': '<p>For just monitoring your application, running VisualVM remotely should not slow it down much. If the system is not on the edge of collapsing, I still haven\'t seen any problems. It\'s basically just reading out information from the coarse grained built-in instrumentation of the JVM. If you start profiling, however, you\'ll have the same issues as with other profilers. Basically because they all work almost they same way, often using the support in the JVM.</p>\n\n<p>Many people have problems with running VisualVM remotely, due to firewall issues, but you can even run <a href="http://spjelkavik.wordpress.com/2009/08/27/running-visualvm-through-an-ssh-tunnel-with-socks/" rel="nofollow noreferrer">Visual VM remotely over ssh</a>, with some system properties set.</p>\n'}, {'answer_id': 4831993, 'author': 'djangofan', 'author_id': 118228, 'author_profile': 'https://Stackoverflow.com/users/118228', 'pm_score': 0, 'selected': False, 'text': "<p>I've been using VisualVM a lot since before it was included in the JDK. It has a negligable impact on the performance of the system. I've never noticed it cause a problem with performance on the system, but then again, our Java server had enough headroom at the time to support a little extra load. If your server is running at a level that is completely tacked out and can't handle the VisualVM running, then I would say its more likely that you need to buy another server . Any production server should have some memory headroom , otherwise what you have is a disaster just waiting to happen.</p>\n"}, {'answer_id': 6203377, 'author': 'Michael', 'author_id': 719068, 'author_profile': 'https://Stackoverflow.com/users/719068', 'pm_score': 0, 'selected': False, 'text': "<p>I have used VVM(VavaVoom?) quite extensively, works like a charm in the light mode, i.e. no profiling, just getting the basic data from the VM. But once you start profiling and there are many classes, then there is considerable slowdown. I wouldn't profile in a production environment even if you have 128 core board with 2 tera of memory purely because the reloading and re-defining of the classes is tricky, the server classloaders are another thing, also vary from one server implementation to another, interfering with them in production is not a very good idea.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8530/'] |
76,044 | <p>It seems that Microsoft wants Silverlight to take off, yet I cannot find an easy way to develop in it without buying Visual Studio 2008. Has anyone out there found a way to get the silverlight development environment in the express editions of Visual Studio? Any other tools?</p>
| [{'answer_id': 76077, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://blogs.msdn.com/webdevtools/archive/2008/05/12/error-installing-visual-studio-2008-sp1-beta-and-silverlight-tools-beta-1.aspx#8636636" rel="nofollow noreferrer">Apparently</a> express support will come with the final release </p>\n'}, {'answer_id': 76102, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 0, 'selected': False, 'text': '<p>Depending on what you consider "productive", you could work with XAMLPad for a lot of the basic declarative stuff. <br />\nThe Moonlight project is working on an IDE called Lunar Eclipse, that I think they\'re eventually going to be integrating into MonoDevelop. Wikipedia says it\'s in the SVN repository already, but I don\'t know if there\'s any code for that which can actually be run effectively yet. I\'d think if it\'s out there it\'d be unusably basic if it even compiles... still, something to look into!</p>\n'}, {'answer_id': 76112, 'author': 'Mikael Sundberg', 'author_id': 4422, 'author_profile': 'https://Stackoverflow.com/users/4422', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a link for ya: <a href="http://www.informikon.com/component/option,com_mamblog/Itemid,0/&Itemid=/task,show/action,view/id,263/" rel="nofollow noreferrer">HOWTO: Silverlight and Visual Studio Express</a>, \n<br>I haven\'t tried it myself though.</p>\n'}, {'answer_id': 76202, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 0, 'selected': False, 'text': "<p>I only use Visual Studio as a text editor for xaml and C#. I don't use the designer in Visual Studio at all. You can put together most of your UI with Blend, open your C# files individually with Express. You don't have much intelisense in Visual Studio for the xaml anyway.</p>\n"}, {'answer_id': 79867, 'author': 'Jobi Joy', 'author_id': 8091, 'author_profile': 'https://Stackoverflow.com/users/8091', 'pm_score': 0, 'selected': False, 'text': '<p>As @Brian stated, you can just use Expression blend and create any WPF/Silverlight apps. Especially if you have some Flash background/more interested in the interaction design (UX) I would recommend you to buy expression blend than VS2008. \nYou can write C# code in notepad and Blend will take care of the compilation.</p>\n'}, {'answer_id': 202062, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 3, 'selected': True, 'text': '<p>They just released <a href="http://www.eclipse4sl.org/" rel="nofollow noreferrer">Eclipse tools for Silverlight (eclipse4SL)</a> and I remembered this thread!</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13355/'] |
76,065 | <p>I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:</p>
<pre><code>mysql> source script.sql
</code></pre>
<p>How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.</p>
<p>I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.</p>
| [{'answer_id': 76124, 'author': 'Brad Choate', 'author_id': 553, 'author_profile': 'https://Stackoverflow.com/users/553', 'pm_score': 6, 'selected': True, 'text': "<p>Like this:</p>\n\n<pre><code>set @department := 'Engineering';\n</code></pre>\n\n<p>Then, reference <code>@department</code> wherever you need to in script.sql:</p>\n\n<pre><code>update employee set salary = salary + 10000 where department = @department;\n</code></pre>\n"}, {'answer_id': 76287, 'author': 'longneck', 'author_id': 8250, 'author_profile': 'https://Stackoverflow.com/users/8250', 'pm_score': -1, 'selected': False, 'text': "<p>you really should be looking at a more appropriate way of doing this. i'm going to guess that you're trying to run mysql queries via a shell script. you should instead be using something like PERL or PHP.</p>\n"}, {'answer_id': 25109187, 'author': 'Yordan Georgiev', 'author_id': 65706, 'author_profile': 'https://Stackoverflow.com/users/65706', 'pm_score': 5, 'selected': False, 'text': '<pre><code> #!/bin/bash\n\n #verify the passed params\n echo 1 cmd arg : $1\n echo 2 cmd arg : $2\n\n export db=$1\n export tbl=$2\n\n #set the params ... Note the quotes ( needed for non-numeric values )\n mysql -uroot -pMySecretPaassword \\\n -e "set @db=\'${db}\';set @tbl=\'${tbl}\';source run.sql ;" ;\n\n #usage: bash run.sh my_db my_table\n #\n #eof file: run.sh\n\n --file:run.sql\n\n SET @query = CONCAT(\'Select * FROM \', @db , \'.\' , @tbl ) ;\n SELECT \'RUNNING THE FOLLOWING query : \' , @query ;\n PREPARE stmt FROM @query;\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\n\n --eof file: run.sql\n</code></pre>\n\n<p>you can re-use the whole concept from <a href="https://github.com/YordanGeorgiev/mysql-starter" rel="noreferrer">from the following project</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13519/'] |
76,074 | <p>I have a couple old services that I want to completely uninstall. How can I do this?</p>
| [{'answer_id': 76101, 'author': 'Mark Schill', 'author_id': 9482, 'author_profile': 'https://Stackoverflow.com/users/9482', 'pm_score': 6, 'selected': False, 'text': '<p>Click <em>Start</em> | <strong>Run</strong> and type <code>regedit</code> in the Open: line. Click OK.</p>\n\n<p>Navigate to <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services</code></p>\n\n<p>Scroll down the left pane, locate the service name, right click it and <strong>select Delete</strong>.</p>\n\n<p>Reboot the system.</p>\n'}, {'answer_id': 76127, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 11, 'selected': True, 'text': '<p>Use the <em>SC</em> command, like this (you need to be on a command prompt to execute the commands in this post):</p>\n\n<pre><code>SC STOP shortservicename\nSC DELETE shortservicename\n</code></pre>\n\n<hr>\n\n<p><strong>Note:</strong> You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". <strong>Note to PowerShell users:</strong> <code>sc</code> is aliased to <code>set-content</code>. So <code>sc delete service</code> will actually create a file called <code>delete</code> with the content <code>service</code>. To do this in Powershell, use <code>sc.exe delete service</code> instead</p>\n\n<hr>\n\n<p>If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:</p>\n\n<pre><code>SC QUERY state= all >"C:\\Service List.txt"\n</code></pre>\n\n<p>For a more concise list, execute this command:</p>\n\n<pre><code>SC QUERY state= all | FIND "_NAME"\n</code></pre>\n\n<p>The short service name will be listed just above the display name, like this:</p>\n\n<pre><code>SERVICE_NAME: MyService\nDISPLAY_NAME: My Special Service\n</code></pre>\n\n<p>And thus to delete that service:</p>\n\n<pre><code>SC STOP MyService\nSC DELETE MyService\n</code></pre>\n'}, {'answer_id': 76138, 'author': 'Mariano', 'author_id': 12514, 'author_profile': 'https://Stackoverflow.com/users/12514', 'pm_score': 1, 'selected': False, 'text': '<p>sc delete name</p>\n'}, {'answer_id': 76158, 'author': 'asquithea', 'author_id': 13530, 'author_profile': 'https://Stackoverflow.com/users/13530', 'pm_score': 5, 'selected': False, 'text': '<p>Use <strong>services.msc</strong> or (Start > Control Panel > Administrative Tools > Services) to find the service in question. Double-click to see the service name and the path to the executable.</p>\n\n<p>Check the exe version information for a clue as to the owner of the service, and use Add/Remove programs to do a clean uninstall if possible.</p>\n\n<p>Failing that, from the command prompt:</p>\n\n<pre><code>sc stop servicexyz\nsc delete servicexyz\n</code></pre>\n\n<p>No restart should be required.</p>\n'}, {'answer_id': 76239, 'author': 'Lucas', 'author_id': 5966, 'author_profile': 'https://Stackoverflow.com/users/5966', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a vbs script that was passed down to me:</p>\n\n<pre><code>Set servicelist = GetObject("winmgmts:").InstancesOf ("Win32_Service")\n\nfor each service in servicelist\n sname = lcase(service.name)\n If sname = "NameOfMyService" Then \n msgbox(sname)\n service.delete \' the internal name of your service\n end if\nnext\n</code></pre>\n'}, {'answer_id': 242268, 'author': 'CPU_BUSY', 'author_id': 27688, 'author_profile': 'https://Stackoverflow.com/users/27688', 'pm_score': 3, 'selected': False, 'text': '<p>If they are .NET created services you can use the installutil.exe with the /u switch\nits in the .net framework folder like\nC:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727</p>\n'}, {'answer_id': 15275825, 'author': 'user2145033', 'author_id': 2145033, 'author_profile': 'https://Stackoverflow.com/users/2145033', 'pm_score': 3, 'selected': False, 'text': '<p>If you have Windows Vista or above please run this from a command prompt as Administrator:</p>\n\n<pre><code>sc delete [your service name as shown in service.msc e.g moneytransfer]\n</code></pre>\n\n<p>For example: <code>sc delete moneytransfer</code></p>\n\n<p>Delete the folder <code>C:\\Program Files\\BBRTL\\moneytransfer\\</code></p>\n\n<p>Find moneytransfer registry keys and delete them:</p>\n\n<pre><code> HKEY_CLASSES_ROOT\\Installer\\Products\\\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\Software\\Classes\\Installer\\Assemblies\\ [remove .exe references]\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders\n</code></pre>\n\n<p>These steps have been tested on Windows XP, Windows 7, Windows Vista, Windows Server 2003, and Windows Server 2008.</p>\n'}, {'answer_id': 18865199, 'author': 'Sachidananda naik', 'author_id': 1664913, 'author_profile': 'https://Stackoverflow.com/users/1664913', 'pm_score': 4, 'selected': False, 'text': '<pre><code>SC DELETE "service name"\n</code></pre>\n\n<p>Run the command on cmd as Administrator otherwise you will get this error :- </p>\n\n<blockquote>\n <p>openservice failed 5 access is denied</p>\n</blockquote>\n'}, {'answer_id': 18964681, 'author': 'Kevin M', 'author_id': 1838481, 'author_profile': 'https://Stackoverflow.com/users/1838481', 'pm_score': 3, 'selected': False, 'text': '<p>We can do it in two different ways</p>\n<p><strong>Remove Windows Service via Registry</strong></p>\n<p>Its very easy to remove a service from registry if you know the right path. Here is how I did that:</p>\n<ol>\n<li><p>Run <strong>Regedit</strong> or <strong>Regedt32</strong></p>\n</li>\n<li><p>Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"</p>\n</li>\n<li><p>Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).</p>\n</li>\n</ol>\n<p><strong>Delete Windows Service via Command Window</strong></p>\n<p>Alternatively, you can also use command prompt and delete a service using following command:</p>\n<p><strong>sc delete</strong> </p>\n<p>You can also create service by using following command</p>\n<p>sc create "MorganTechService" binpath= "C:\\Program Files\\MorganTechSPace\\myservice.exe"</p>\n<p>Note: You may have to reboot the system to get the list updated in service manager.</p>\n'}, {'answer_id': 33136790, 'author': 'Demodave', 'author_id': 953496, 'author_profile': 'https://Stackoverflow.com/users/953496', 'pm_score': 0, 'selected': False, 'text': '<p>For me my service that I created had to be uninstalled in Control Panel > Programs and Features</p>\n'}, {'answer_id': 36133683, 'author': 'Dilmasegure', 'author_id': 6094055, 'author_profile': 'https://Stackoverflow.com/users/6094055', 'pm_score': 1, 'selected': False, 'text': '<p>Before removing the service you should review the dependencies.</p>\n\n<p>You can check it:</p>\n\n<p>Open <code>services.msc</code> and find the service name, switch to the "Dependencies" tab.</p>\n\n<p>Source: <a href="http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html" rel="nofollow">http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html</a></p>\n'}, {'answer_id': 49165398, 'author': 'Nic', 'author_id': 2450507, 'author_profile': 'https://Stackoverflow.com/users/2450507', 'pm_score': 5, 'selected': False, 'text': "<p>As described above I executed:</p>\n\n<pre><code>sc delete ServiceName\n</code></pre>\n\n<p>However this didn't work as I was executing it from PowerShell.</p>\n\n<p>When using PowerShell you must specify the full path to <code>sc.exe</code> because PowerShell has a default alias for <code>sc</code> assigning it to <code>Set-Content</code>. Since it's a valid command it doesn't actually show an error message.</p>\n\n<p>To resolve this I executed it as follows:</p>\n\n<pre><code>C:\\Windows\\System32\\sc.exe delete ServiceName\n</code></pre>\n"}, {'answer_id': 60429951, 'author': 'Sergey Vaulin', 'author_id': 3556088, 'author_profile': 'https://Stackoverflow.com/users/3556088', 'pm_score': 1, 'selected': False, 'text': '<p>You can use my small service list editor utility <strong>Service Manager</strong></p>\n\n<p><a href="https://i.stack.imgur.com/Kw4Lc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kw4Lc.png" alt="Preview"></a></p>\n\n<p>You can choose any service > Modify > Delete. Method works immediately, no reboot required.</p>\n\n<p>Executable file: <a href="https://drive.google.com/drive/folders/1NXu810HDv3KYe3LcT8q2gZxQ9zLwuI_n" rel="nofollow noreferrer">[Download]</a></p>\n\n<p>Source code: <a href="https://github.com/devowl/winservicemanager" rel="nofollow noreferrer">[Download]</a></p>\n\n<p>Blog post: <a href="http://www.devowl.net/2019/08/windows-service-create-edit-delete-servicesmsc.html" rel="nofollow noreferrer">[BlogLink]</a></p>\n\n<p>Service editor class: <a href="https://github.com/devowl/winservicemanager/blob/master/WS.Manager/WinService/WinServiceUtils.cs" rel="nofollow noreferrer">WinServiceUtils.cs</a></p>\n'}, {'answer_id': 68771818, 'author': '4F2E4A2E', 'author_id': 543426, 'author_profile': 'https://Stackoverflow.com/users/543426', 'pm_score': 2, 'selected': False, 'text': '<p>This did the job for me on Windows 10:</p>\n<ul>\n<li>start the cmd.exe as admin</li>\n<li>run SC DELETE "com.docker.service"</li>\n<li>reinstall docker</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204/'] |
76,076 | <p>I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.</p>
<p>To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.</p>
<p>I was thinking of using octtrees, but I was wondering if someone knows a better method.</p>
| [{'answer_id': 76185, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 4, 'selected': True, 'text': '<p>Octtrees are the way to go. You subdivide the array into 8 octants:</p>\n\n<pre>\n1 2\n3 4\n\n---\n\n5 6\n7 8\n</pre>\n\n<p>And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above. You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point). This has much, much better cache coherency and locality of reference than the naive layout.</p>\n'}, {'answer_id': 76767, 'author': 'palm3D', 'author_id': 2686, 'author_profile': 'https://Stackoverflow.com/users/2686', 'pm_score': 2, 'selected': False, 'text': '<p>The book <a href="https://rads.stackoverflow.com/amzn/click/com/0123694469" rel="nofollow noreferrer" rel="nofollow noreferrer">Foundations of Multidimensional and Metric Data Structures</a> can help you decide which data structure is fastest for range queries: octrees, kd-trees, R-trees, ...\nIt also describes data layouts for keeping points together in memory.</p>\n'}, {'answer_id': 83362, 'author': 'Nils Pipenbrinck', 'author_id': 15955, 'author_profile': 'https://Stackoverflow.com/users/15955', 'pm_score': 3, 'selected': False, 'text': "<p>One alternative to the tree-method: Use the Morton-Order to encode your data.</p>\n\n<p>In three dimension it goes like this: Take the coordinate components and interleave each bit two zero bits. Here shown in binary: 11111b becomes 1001001001b</p>\n\n<p>A C-function to do this looks like this (shown for clarity and only for 11 bits):</p>\n\n<pre><code>int morton3 (int a)\n{\n int result = 0;\n int i;\n for (i=0; i<11; i++)\n {\n // check if the i'th bit is set.\n int bit = a&(1<<i);\n if (bit)\n {\n // if so set the 3*i'th bit in the result:\n result |= 1<<(i*3);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>You can use this function to combine your positions like this:</p>\n\n<pre><code>index = morton3 (position.x) + \n morton3 (position.y)*2 +\n morton3 (position.z)*4;\n</code></pre>\n\n<p>This turns your three dimensional index into a one dimensional one. Best part of it: Values that are close in 3D space are close in 1D space as well. If you access values close to each other frequently you will also get a very nice speed-up because the morton-order encoding is optimal in terms of cache locality.</p>\n\n<p>For morton3 you better not use the code above. Use a small table to look up 4 or 8 bits at a time and combine them together. </p>\n\n<p>Hope it helps,\n Nils</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13405/'] |
76,079 | <p>can anyone please suggest a <strong>good code example</strong> of vb.net/c# code to put the application in system tray when minized.</p>
| [{'answer_id': 76120, 'author': 'Phillip Wells', 'author_id': 3012, 'author_profile': 'https://Stackoverflow.com/users/3012', 'pm_score': 5, 'selected': True, 'text': '<p>Add a NotifyIcon control to your form, then use the following code:</p>\n\n<pre><code> private void frm_main_Resize(object sender, EventArgs e)\n {\n if (this.WindowState == FormWindowState.Minimized)\n {\n this.ShowInTaskbar = false;\n this.Hide();\n notifyIcon1.Visible = true;\n }\n }\n\n private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)\n {\n this.Show();\n this.WindowState = FormWindowState.Normal;\n this.ShowInTaskbar = true;\n notifyIcon1.Visible = false;\n }\n</code></pre>\n\n<p>You may not need to set the ShowInTaskbar property.</p>\n'}, {'answer_id': 76160, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 2, 'selected': False, 'text': '<p>You can leverage a built in control called NotifyIcon. This creates a tray icon when shown. @Phillip has a code example that is somewhat complete.</p>\n\n<p>There is a gotcha though:</p>\n\n<p>You must override your applications main form Dispose method to call Dispose on NotifyIcon, otherwise it will stay in your tray after application exits.</p>\n\n<pre><code>public void Form_Dispose(object sender, EventArgs e)\n{\n if (this.Disposing)\n notifyIcon1.Dispose();\n}\n</code></pre>\n\n<p>Something like that.</p>\n'}, {'answer_id': 76708, 'author': 'Sean Gough', 'author_id': 12842, 'author_profile': 'https://Stackoverflow.com/users/12842', 'pm_score': 0, 'selected': False, 'text': '<p>You can do this by adding a NotifyIcon to your form and handling the form\'s resize event. To get back from the tray handle the NotifyIcon\'s double-click event.</p>\n\n<p>If you want to add a little animation you can do this too...</p>\n\n<p>1) Add the following module:</p>\n\n<pre><code>Module AnimatedMinimizeToTray\nStructure RECT\n Public left As Integer\n Public top As Integer\n Public right As Integer\n Public bottom As Integer\nEnd Structure\n\nStructure APPBARDATA\n Public cbSize As Integer\n Public hWnd As IntPtr\n Public uCallbackMessage As Integer\n Public uEdge As ABEdge\n Public rc As RECT\n Public lParam As IntPtr\nEnd Structure\n\nEnum ABMsg\n ABM_NEW = 0\n ABM_REMOVE = 1\n ABM_QUERYPOS = 2\n ABM_SETPOS = 3\n ABM_GETSTATE = 4\n ABM_GETTASKBARPOS = 5\n ABM_ACTIVATE = 6\n ABM_GETAUTOHIDEBAR = 7\n ABM_SETAUTOHIDEBAR = 8\n ABM_WINDOWPOSCHANGED = 9\n ABM_SETSTATE = 10\nEnd Enum\n\nEnum ABNotify\n ABN_STATECHANGE = 0\n ABN_POSCHANGED\n ABN_FULLSCREENAPP\n ABN_WINDOWARRANGE\nEnd Enum\n\nEnum ABEdge\n ABE_LEFT = 0\n ABE_TOP\n ABE_RIGHT\n ABE_BOTTOM\nEnd Enum\n\nPublic Declare Function SHAppBarMessage Lib "shell32.dll" Alias "SHAppBarMessage" (ByVal dwMessage As Integer, ByRef pData As APPBARDATA) As Integer\nPublic Const ABM_GETTASKBARPOS As Integer = &H5&\nPublic Const WM_SYSCOMMAND As Integer = &H112\nPublic Const SC_MINIMIZE As Integer = &HF020\n\nPublic Sub AnimateWindow(ByVal ToTray As Boolean, ByRef frm As Form, ByRef icon As NotifyIcon)\n \' get the screen dimensions\n Dim screenRect As Rectangle = Screen.GetBounds(frm.Location)\n\n \' figure out where the taskbar is (and consequently the tray)\n Dim destPoint As Point\n Dim BarData As APPBARDATA\n BarData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(BarData)\n SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, BarData)\n Select Case BarData.uEdge\n Case ABEdge.ABE_BOTTOM, ABEdge.ABE_RIGHT\n \' Tray is to the Bottom Right\n destPoint = New Point(screenRect.Width, screenRect.Height)\n\n Case ABEdge.ABE_LEFT\n \' Tray is to the Bottom Left\n destPoint = New Point(0, screenRect.Height)\n\n Case ABEdge.ABE_TOP\n \' Tray is to the Top Right\n destPoint = New Point(screenRect.Width, 0)\n\n End Select\n\n \' setup our loop based on the direction\n Dim a, b, s As Single\n If ToTray Then\n a = 0\n b = 1\n s = 0.05\n Else\n a = 1\n b = 0\n s = -0.05\n End If\n\n \' "animate" the window\n Dim curPoint As Point, curSize As Size\n Dim startPoint As Point = frm.Location\n Dim dWidth As Integer = destPoint.X - startPoint.X\n Dim dHeight As Integer = destPoint.Y - startPoint.Y\n Dim startWidth As Integer = frm.Width\n Dim startHeight As Integer = frm.Height\n Dim i As Single\n For i = a To b Step s\n curPoint = New Point(startPoint.X + i * dWidth, startPoint.Y + i * dHeight)\n curSize = New Size((1 - i) * startWidth, (1 - i) * startHeight)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n System.Threading.Thread.Sleep(15)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n Next\n\n\n If ToTray Then\n \' hide the form and show the notifyicon\n frm.Hide()\n icon.Visible = True\n Else\n \' hide the notifyicon and show the form\n icon.Visible = False\n frm.Show()\n End If\n\nEnd Sub\nEnd Module\n</code></pre>\n\n<p>2) Add a NotifyIcon to your form an add the following:</p>\n\n<pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)\n If m.Msg = WM_SYSCOMMAND AndAlso m.WParam.ToInt32() = SC_MINIMIZE Then\n AnimateWindow(True, Me, NotifyIcon1)\n Exit Sub\n End If\n MyBase.WndProc(m)\nEnd Sub\n\nPrivate Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick\n AnimateWindow(False, Me, NotifyIcon1)\nEnd Sub\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13337/'] |
76,080 | <p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p>
<p>For reference, here is code to get the Application Data folder under both systems:</p>
<pre><code> HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
</code></pre>
<p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p>
<p>Under Windows XP, the app data subfolder is:</p>
<p>Microsoft\Internet Explorer\Quick Launch</p>
<p>Under Vista, it appears that the sub-folder has been changed to:</p>
<p>Roaming\Microsoft\Internet Explorer\Quick Launch</p>
<p>but I'd like to make sure that this is the correct way to determine the correct location.</p>
<p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p>
<p>EDIT:
The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p>
<p>So the following algorithm is correct per MS:</p>
<pre><code>HRESULT hres;
CString basePath;
hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE);
basePath.ReleaseBuffer();
CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch";
</code></pre>
<p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
| [{'answer_id': 76246, 'author': 'StocksR', 'author_id': 6892, 'author_profile': 'https://Stackoverflow.com/users/6892', 'pm_score': 3, 'selected': True, 'text': '<p>AppData on vista refers to C:\\Users\\xxxx\\AppData\\Roaming not the C:\\Users\\xxxx\\AppData folder it\'s self.</p>\n\n<p>Also this artical <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx</a> on a microsoft site implies that you simply have to use the path relative to the appdata folder </p>\n'}, {'answer_id': 76323, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 1, 'selected': False, 'text': '<p>Great question! </p>\n\n<p>Whatever you do, <strong>don\'t</strong> give into the temptation to <a href="http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx" rel="nofollow noreferrer">dig into the registry</a> to find this info!</p>\n\n<p>Also, we must resist the temptation to hard code some path, even partially. If we get the special AppData path, then simply append a string onto the end, this may break under non-US installs of the software where the folder name is localized to that language. E.g. <code>GetSpecialFolderPath(APP_DATA) + "\\\\Fonts"</code> will not work on non-English versions of Windows.</p>\n\n<p>Hopefully someone has the proper answer to your question; I\'m curious to know it myself!</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10973/'] |
76,096 | <p>I'm trying to keep dependencies to a minimum for a program I contribute to, it's a small text editor.</p>
<p>GTK Textview doesn't seem to come with a built-in undo function. Is there any reference implementation I've been missing on so far? Is everyone writing their own undo function for their TextView widgets?</p>
<p>I'll be happy about any sample code - most happy about python sample code, as our project is in python.</p>
| [{'answer_id': 76453, 'author': 'mlibby', 'author_id': 13468, 'author_profile': 'https://Stackoverflow.com/users/13468', 'pm_score': 3, 'selected': True, 'text': '<p>As far as I know, GTK TextView doesn\'t include an undo function. So while I am not familiar with Python\'s GTK library, I would think it doesn\'t have one.</p>\n\n<p>The Ruby-GNOME2 project has a <a href="http://ruby-gnome2.sourceforge.jp/hiki.cgi?Simple+Text+Editor" rel="nofollow noreferrer">sample text editor</a> that has undo/redo functionality. Basically they are connecting to the insert_text and delete_range signals of the TextView widget and recording the events and associated data in a list.</p>\n'}, {'answer_id': 80992, 'author': 'Kai', 'author_id': 2963, 'author_profile': 'https://Stackoverflow.com/users/2963', 'pm_score': 2, 'selected': False, 'text': '<p>Depending on just how dependency-averse you are, and what kind of text editor you\'re building, <a href="http://projects.gnome.org/gtksourceview/" rel="nofollow noreferrer">GtkSourceView</a> adds undo/redo among many other things. Very worth looking at if you want some of the other <a href="http://projects.gnome.org/gtksourceview/features.html" rel="nofollow noreferrer">features</a> it offers.</p>\n'}, {'answer_id': 586115, 'author': 'Florian Heinle', 'author_id': 64673, 'author_profile': 'https://Stackoverflow.com/users/64673', 'pm_score': 3, 'selected': False, 'text': '<p>as a follwow-up: I ported gtksourceview\'s undo mechanism to python: <a href="http://bitbucket.org/tiax/gtk-textbuffer-with-undo/" rel="noreferrer">http://bitbucket.org/tiax/gtk-textbuffer-with-undo/</a></p>\n\n<p>serves as a drop-in replacement for gtksourceview\'s undo</p>\n\n<p>(OP here, but launchpad open-id doesn\'t work anymore)</p>\n'}, {'answer_id': 48927176, 'author': 'oxidworks', 'author_id': 1907997, 'author_profile': 'https://Stackoverflow.com/users/1907997', 'pm_score': 0, 'selected': False, 'text': '<h1>Use GtkSource</h1>\n<ul>\n<li><a href="https://wiki.gnome.org/Projects/GtkSourceView" rel="nofollow noreferrer">https://wiki.gnome.org/Projects/GtkSourceView</a></li>\n<li><a href="https://lazka.github.io/pgi-docs/GtkSource-3.0/" rel="nofollow noreferrer">https://lazka.github.io/pgi-docs/GtkSource-3.0/</a></li>\n<li><a href="https://lazka.github.io/pgi-docs/GtkSource-3.0/classes.html" rel="nofollow noreferrer">https://lazka.github.io/pgi-docs/GtkSource-3.0/classes.html</a></li>\n</ul>\n<p>.</p>\n<ul>\n<li>[Cmnd] + [Z] for undo (default)</li>\n<li>[Cmnd] + [Shift] + [Z] for redo (default)</li>\n<li>[Cmnd] + [Y] for redo (added manually)</li>\n</ul>\n<h1>example:</h1>\n<pre><code>#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport gi\ngi.require_version(\'Gtk\', \'3.0\')\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\ngi.require_version(\'GtkSource\', \'3.0\')\nfrom gi.repository import GtkSource\n\nimport os\n\n\nclass TreeviewWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self, title="TreeviewWindow")\n self.set_size_request(300, 300)\n self.connect("key-press-event", self._key_press_event)\n self.mainbox = Gtk.VBox(spacing=10)\n self.add(self.mainbox) \n\n self.textbuffer = GtkSource.Buffer()\n textview = GtkSource.View(buffer=self.textbuffer)\n textview.set_editable(True)\n textview.set_cursor_visible(True)\n textview.set_show_line_numbers(True)\n self.mainbox.pack_start(textview, True, True, 0)\n self.show_all() \n\n def _key_press_event(self, widget, event):\n keyval_name = Gdk.keyval_name(event.keyval)\n ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)\n if ctrl and keyval_name == \'y\':\n if self.textbuffer.can_redo():\n self.textbuffer.do_redo(self.textbuffer)\n \n def main(self):\n Gtk.main()\n \nif __name__ == "__main__":\n base = TreeviewWindow()\n base.main()\n \n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64673/'] |
76,134 | <p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p>
<p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p>
<p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>
| [{'answer_id': 76282, 'author': 'tzot', 'author_id': 6899, 'author_profile': 'https://Stackoverflow.com/users/6899', 'pm_score': 2, 'selected': False, 'text': "<p>Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :</p>\n\n<p>Find two points with max inter-distance: these most probably define a diagonal (exception: special cases where the rectangle is almost paralell to the YZ plane, left for the student). Call them A, C. Calculate the BAD, BCD angles. These, compared to right angles, give you orientation in 3d space. To find out about z distance, you need to correlate the projected sides to the known sides, and then, based on the 3d projection method (is it 1/z?) you're on the right track to know distances.</p>\n"}, {'answer_id': 76289, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ll get my linear Algebra book out when I get home if nobody answered. But @ D G, not all matrices are invertible. <a href="http://mathworld.wolfram.com/SingularMatrix.html" rel="nofollow noreferrer">Singular matrices aren\'t invertible</a> (when determinant = 0). This will actually happen all the time, since a projection matrix <em>must</em> have eigenvalues of 0 and 1, and be square (since it is idempotent, so p^2 = p).</p>\n\n<p>An easy example is, [[0 1][0 1]] since the determinant = 0, and that is a projection on the line x = y!</p>\n'}, {'answer_id': 76305, 'author': 'Rob Dickerson', 'author_id': 7530, 'author_profile': 'https://Stackoverflow.com/users/7530', 'pm_score': 1, 'selected': False, 'text': '<p>The projection you have onto the 2D surface has infinitely many 3D rectangles that will project to the same 2D shape.</p>\n\n<p>Think about it this way: you have four 3D points that make up the 3D rectangle. Call them (x0,y0,z0), (x1,y1,z1), (x2,y2,z2) and (x3,y3,z3). When you project these points onto the x-y plane, you drop the z coordinates: (x0,y0), (x1,y1), (x2,y2), (x3,y3).</p>\n\n<p>Now, you want to project back into 3D space, you need to reverse-engineer what z0,..,z3 were. But any set of z coordinates that a) keep the same x-y distance between the points, and b) keep the shape a rectangle will work. So, any member of this (infinite) set will do: {(z0+i, z1+i, z2+i, z3+i) | i <- R}.</p>\n\n<p>Edit @Jarrett: Imagine you solved this and ended up with a rectangle in 3D space. Now, imagine sliding that rectangle up and down the z-axis. Those infinite amount of translated rectangles all have the same x-y projection. How do you know you found the "right" one?</p>\n\n<p>Edit #2: Alright, this is from a comment I made on this question -- a more intuitive approach to reasoning about this.</p>\n\n<p>Imagine holding a piece of paper above your desk. Pretend each corner of the paper has a weightless laser pointer attached to it that points down toward the desk. The paper is the 3D object, and the laser pointer dots on the desk are the 2D projection.</p>\n\n<p>Now, how can you tell how high off the desk the paper is by looking at <em>just</em> the laser pointer dots?</p>\n\n<p>You can\'t. Move the paper straight up and down. The laser pointers will still shine on the same spots on the desk regardless of the height of the paper.</p>\n\n<p>Finding the z-coordinates in the reverse-projection is like trying to find the height of the paper based on the laser pointer dots on the desk alone.</p>\n'}, {'answer_id': 76306, 'author': 'Jarrett Meyer', 'author_id': 5834, 'author_profile': 'https://Stackoverflow.com/users/5834', 'pm_score': 2, 'selected': False, 'text': '<p>From the 2-D space there will be 2 valid rectangles that can be built. Without knowing the original matrix projection, you won\'t know which one is correct. It\'s the same as the "box" problem: you see two squares, one inside the other, with the 4 inside vertices connected to the 4 respective outside vertices. Are you looking at a box from the top-down or the bottom-up?</p>\n\n<p>That being said, you are looking for a matrix transform T where...</p>\n\n<p>{{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4, z4}} x T = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}}</p>\n\n<p>(4 x 3) x T = (4 x 2)</p>\n\n<p>So T must be a (3 x 2) matrix. So we\'ve got 6 unknowns.</p>\n\n<p>Now build a system of constraints on T and solve with Simplex. To build the constraints, you know that a line passing through the first two points must be parallel to the line passing to the second two points. You know a line passing through points 1 and 3 must be parallel to the lines passing through points 2 and 4. You know a line passing through 1 and 2 must be orthogonal to a line passing through points 2 and 3. You know that the length of the line from 1 and 2 must equal the length of the line from 3 and 4. You know that the length of the line from 1 and 3 must equal the length of the line from 2 and 4.</p>\n\n<p>To make this even easier, you know about the rectangle, so you know the length of all the sides.</p>\n\n<p>That should give you plenty of constraints to solve this problem.</p>\n\n<p>Of course, to get back, you can find T-inverse.</p>\n\n<p>@Rob: Yes, there are an infinite number of projections, but not an infinite number of projects where the points must satisfy the requirements of a rectangle.</p>\n\n<p>@nlucaroni: Yes, this is only solvable if you have four points in the projection. If the rectangle projects to just 2 points (i.e. the plane of the rectangle is orthogonal to the projection surface), then this cannot be solved.</p>\n\n<p>Hmmm... I should go home and write this little gem. This sounds like fun.</p>\n\n<p>Updates:</p>\n\n<ol>\n<li>There are an infinite number of projections unless you fix one of the points. If you fix on of the points of the original rectangle, then there are two possible original rectangles.</li>\n</ol>\n'}, {'answer_id': 77003, 'author': 'morechilli', 'author_id': 5427, 'author_profile': 'https://Stackoverflow.com/users/5427', 'pm_score': 1, 'selected': False, 'text': "<p>When you project from 3D to 2D you lose information.</p>\n\n<p>In the simple case of a single point the inverse projection would give you an infinite ray through 3d space.</p>\n\n<p>Stereoscopic reconstruction will typically start with two 2d images and project both back to 3D. Then look for an intersection of the two 3D rays produced.</p>\n\n<p>Projection can take different forms. Orthogonal or perspective. I'm guessing that you are assuming orthogonal projection?</p>\n\n<p>In your case assuming you had the original matrix you would have 4 rays in 3D space. You would then be able to constrain the problem by your 3d rectangle dimensions and attempt to solve. </p>\n\n<p>The solution will not be unique as a rotation around either axis that is parallel to the 2d projection plane will be ambiguous in direction. In other words if the 2d image is perpendicular to the z axis then rotating the 3d rectangle clockwise or anti clockwise around the x axis would produce the same image. Likewise for the y axis.</p>\n\n<p>In the case where the rectangle plane is parallel to the z axis you have even more solutions.</p>\n\n<p>As you don't have the original projection matrix further ambiguity is introduced by an arbitary scaling factor that exists in any projection. You cannot distinguish between a scaling in the projection and a translation in 3d in the direction of the z axis. This is not a problem if you are only interested in the relative positions of the 4 points in 3d space when related to each other and not to the plane of the 2d projection.</p>\n\n<p>In a perspective projection things get harder...</p>\n"}, {'answer_id': 77188, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>If you know the shape is a rectangle in a plane, you can greatly further constrain the problem. You certainly cannot figure out "which" plane, so you can choose that it is lying on the plane where z=0 and one of the corners is at x=y=0, and the edges are parallel to the x/y axis.</p>\n\n<p>The points in 3d are therefore {0,0,0},{w,0,0},{w,h,0},and {0,h,0}. I\'m pretty certain the absolute size will not be found, so only the ratio w/h is releavant, so this is one unknown.</p>\n\n<p>Relative to this plane the camera must be at some point cx,cy,cz in space, must be pointing in a direction nx,ny,nz (a vector of length one so one of these is redundant), and have a focal_length/image_width factor of w. These numbers turn into a 3x3 projection matrix.</p>\n\n<p>That gives a total of 7 unknowns: w/h, cx, cy, cz, nx, ny, and w.</p>\n\n<p>You have a total of 8 knowns: the 4 x+y pairs.</p>\n\n<p>So this can be solved.</p>\n\n<p>Next step is to use Matlab or Mathmatica.</p>\n'}, {'answer_id': 78057, 'author': 'user14208', 'author_id': 14208, 'author_profile': 'https://Stackoverflow.com/users/14208', 'pm_score': 3, 'selected': False, 'text': "<p>For my OpenGL engine, the following snip will convert mouse/screen coordinates into 3D world coordinates. Read the commments for an actual description of what is going on.</p>\n<pre>\n/* FUNCTION: YCamera :: CalculateWorldCoordinates\n ARGUMENTS: x mouse x coordinate\n y mouse y coordinate\n vec where to store coordinates\n RETURN: n/a\n DESCRIPTION: Convert mouse coordinates into world coordinates\n*/\n</pre>\n<pre><code>void YCamera :: CalculateWorldCoordinates(float x, float y, YVector3 *vec)\n{\n // START\n GLint viewport[4];\n GLdouble mvmatrix[16], projmatrix[16];\n \n GLint real_y;\n GLdouble mx, my, mz;\n\n glGetIntegerv(GL_VIEWPORT, viewport);\n glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);\n glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);\n\n real_y = viewport[3] - (GLint) y - 1; // viewport[3] is height of window in pixels\n gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &mx, &my, &mz);\n\n /* 'mouse' is the point where mouse projection reaches FAR_PLANE.\n World coordinates is intersection of line(camera->mouse) with plane(z=0) (see LaMothe 306)\n \n Equation of line in 3D:\n (x-x0)/a = (y-y0)/b = (z-z0)/c \n\n Intersection of line with plane:\n z = 0\n x-x0 = a(z-z0)/c <=> x = x0+a(0-z0)/c <=> x = x0 -a*z0/c\n y = y0 - b*z0/c\n \n */\n double lx = fPosition.x - mx;\n double ly = fPosition.y - my;\n double lz = fPosition.z - mz;\n double sum = lx*lx + ly*ly + lz*lz;\n double normal = sqrt(sum);\n double z0_c = fPosition.z / (lz/normal);\n \n vec->x = (float) (fPosition.x - (lx/normal)*z0_c);\n vec->y = (float) (fPosition.y - (ly/normal)*z0_c);\n vec->z = 0.0f;\n}\n</code></pre>\n"}, {'answer_id': 93779, 'author': 'Nils Pipenbrinck', 'author_id': 15955, 'author_profile': 'https://Stackoverflow.com/users/15955', 'pm_score': 2, 'selected': False, 'text': '<p>To follow up on Rons approach: You can find your z-values if you know how you\'ve rotated your rectangle.</p>\n\n<p>The trick is to find the projective matrix that did the projection. Fortunately this is possible and even cheap to do. The relevant math can be found in the paper "Projective Mappings for Image Warping" by Paul Heckbert. </p>\n\n<p><a href="http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf" rel="nofollow noreferrer">http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf</a></p>\n\n<p>This way you can recover the homogenous part of each vertex back that was lost during projection. </p>\n\n<p>Now you\'re still left with four lines instead of points (as Ron explained). Since you know the size of your original rectangle however nothing is lost. You can now plug the data from Ron\'s method and from the 2D approach into a linear equation solver and solve for z. You get the exact z-values of each vertex that way. </p>\n\n<p>Note: This just works because: </p>\n\n<ol>\n<li>The original shape was a rectangle</li>\n<li>You know the exact size of the rectangle in 3D space.</li>\n</ol>\n\n<p>It\'s a special case really.</p>\n\n<p>Hope it helps,\n Nils</p>\n'}, {'answer_id': 3554754, 'author': 'Julien-L', 'author_id': 143504, 'author_profile': 'https://Stackoverflow.com/users/143504', 'pm_score': 3, 'selected': False, 'text': '<p><em>D. DeMenthon</em> devised an algorithm to compute the <em>pose</em> of an object (its position and orientation in space) from feature points in a 2D image when knowing the model of the object -- <strong>this is your exact problem</strong>:</p>\n\n<blockquote>\n <p>We describe a method for finding the pose of an object from a single image. We assume that we can detect and match in the image four or more noncoplanar feature points of the object, and that we know their relative geometry on the object.</p>\n</blockquote>\n\n<p>The algorithm is known as <strong>Posit</strong> and is described in it classical article "Model-Based Object Pose in 25 Lines of Code" (available on <a href="http://www.cfar.umd.edu/~daniel/Site_2/Research.html" rel="noreferrer">its website</a>, section 4).</p>\n\n<p>Direct link to the article: <a href="http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf" rel="noreferrer">http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf</a>\nOpenCV implementation: <a href="http://opencv.willowgarage.com/wiki/Posit" rel="noreferrer">http://opencv.willowgarage.com/wiki/Posit</a></p>\n\n<p>The idea is to repeatedly approximating the perspective projection by a <em>scaled orthographic projection</em> until converging to an accurate pose.</p>\n'}, {'answer_id': 13937210, 'author': 'dim_tz', 'author_id': 1435500, 'author_profile': 'https://Stackoverflow.com/users/1435500', 'pm_score': 3, 'selected': False, 'text': '<p>This is the Classic problem for marker based Augmented Reality.</p>\n\n<p>You have a square marker (2D Barcode), and you want to find its Pose (translation & rotation in relation to the camera), after finding the four edges of the marker.\n<a href="http://www.brightsideofnews.com/Data/2009_10_26/Zombies-nVidia-Tegra-Augmented-Reality/Zombies_AR_Marker_675.jpg" rel="noreferrer">Overview-Picture</a></p>\n\n<p>I\'m not aware of the latest contributions to the field, but at least up to a point (2009) RPP was supposed to outperform POSIT that is mentioned above (and is indeed a classic approach for this)\nPlease see the links, they also provide source.</p>\n\n<ul>\n<li><p><a href="http://www.emt.tugraz.at/~vmg/schweighofer" rel="noreferrer">http://www.emt.tugraz.at/~vmg/schweighofer</a></p></li>\n<li><p><a href="http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf" rel="noreferrer">http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf</a></p></li>\n<li><p><a href="http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz" rel="noreferrer">http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz</a></p></li>\n</ul>\n\n<p>(PS - I know it\'s a bit old topic, but anyway, the post might be helpful to somebody)</p>\n'}, {'answer_id': 33976739, 'author': 'Vegard', 'author_id': 1697183, 'author_profile': 'https://Stackoverflow.com/users/1697183', 'pm_score': 7, 'selected': False, 'text': '<p>Alright, I came here looking for an answer and didn\'t find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation.</p>\n\n<p>Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates.</p>\n\n<p>Here is a still photo from Thomas the Tank Engine:</p>\n\n<p><a href="https://i.stack.imgur.com/YUhsm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YUhsm.png" alt="Thomas the Tank Engine"></a></p>\n\n<p>Let\'s say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth):</p>\n\n<p><a href="https://i.stack.imgur.com/u8nKF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u8nKF.png" alt="With an outline of the square"></a></p>\n\n<p>I get four points in the 2D image: <code>(318, 247)</code>, <code>(326, 312)</code>, <code>(418, 241)</code>, and <code>(452, 303)</code>.</p>\n\n<p>By convention, we say that these points should correspond to the 3D points: <code>(0, 0, 0)</code>, <code>(0, 0, 1)</code>, <code>(1, 0, 0)</code>, and <code>(1, 0, 1)</code>. In other words, a unit square in the y=0 plane.</p>\n\n<p>Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector <code>[x, y, z, 1]</code> with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what <a href="https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml" rel="noreferrer">gluProject()</a> does, except <code>gluProject()</code> also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the <code>gluProject()</code> documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula.</p>\n\n<p>Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we\'re going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess.</p>\n\n<p>Let\'s define our points:</p>\n\n<pre><code># Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n</code></pre>\n\n<p>We need to start with some matrix, identity matrix seems a natural choice:</p>\n\n<pre><code>mat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n</code></pre>\n\n<p>We need to actually implement the projection (which is basically a matrix multiplication):</p>\n\n<pre><code>def project(p, mat):\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n</code></pre>\n\n<p>This is basically what <code>gluProject()</code> does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You\'ll notice we\'re not calculating z, that\'s because we don\'t really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer).</p>\n\n<p>Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.:</p>\n\n<pre><code># The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)\n</code></pre>\n\n<p>To perturb the matrix, we simply pick an element to perturb by a random amount within some range:</p>\n\n<pre><code>def perturb(amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n</code></pre>\n\n<p>(It\'s worth noting that our <code>project()</code> function doesn\'t actually use <code>mat[2]</code> at all, since we don\'t compute z, and since all our y coordinates are 0 the <code>mat[*][1]</code> values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...)</p>\n\n<p>For convenience, let\'s add a function that does the bulk of the approximation by calling <code>perturb()</code> over and over again on what is the best matrix we\'ve found so far:</p>\n\n<pre><code>def approximate(mat, amount, n=100000):\n est = evaluate(mat)\n\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 < est:\n mat = mat2\n est = est2\n\n return mat, est\n</code></pre>\n\n<p>Now all that\'s left to do is to run it...:</p>\n\n<pre><code>for i in xrange(100):\n mat = approximate(mat, 1)\n mat = approximate(mat, .1)\n</code></pre>\n\n<p>I find this already gives a pretty accurate answer. After running for a while, the matrix I found was:</p>\n\n<pre><code>[\n [1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597],\n [0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ],\n [0, 0, 1, 0 ],\n [0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ],\n]\n</code></pre>\n\n<p>with an error of around <code>2.6e-5</code>. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that\'s because changing these entries would not change the result of the evaluation and so the change would never get carried along.)</p>\n\n<p>We can pass the matrix into OpenGL using <code>glLoadMatrix()</code> (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix):</p>\n\n<pre><code>def transpose(m):\n return [\n [m[0][0], m[1][0], m[2][0], m[3][0]],\n [m[0][1], m[1][1], m[2][1], m[3][1]],\n [m[0][2], m[1][2], m[2][2], m[3][2]],\n [m[0][3], m[1][3], m[2][3], m[3][3]],\n ]\n\nglLoadMatrixf(transpose(mat))\n</code></pre>\n\n<p>Now we can for example translate along the z axis to get different positions along the tracks:</p>\n\n<pre><code>glTranslate(0, 0, frame)\nframe = frame + 1\n\nglBegin(GL_QUADS)\nglVertex3f(0, 0, 0)\nglVertex3f(0, 0, 1)\nglVertex3f(1, 0, 1)\nglVertex3f(1, 0, 0)\nglEnd()\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/dfeEx.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/dfeEx.gif" alt="With 3D translation"></a></p>\n\n<p>For sure this is not very elegant from a mathematical point of view; you don\'t get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it\'s a brute force of sorts, but works, and works well.</p>\n\n<p><a href="https://i.stack.imgur.com/smdR8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/smdR8.png" alt="Choo choo!"></a></p>\n'}, {'answer_id': 39877333, 'author': 'BBSysDyn', 'author_id': 423805, 'author_profile': 'https://Stackoverflow.com/users/423805', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks to @Vegard for an excellent answer. I cleaned up the code a little bit:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nclass Point2:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\nclass Point3:\n def __init__(self,x,y,z):\n self.x = x\n self.y = y\n self.z = z\n\n# Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n\nmat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n\ndef project(p, mat):\n #print mat\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point2(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n\n# The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3) \n\ndef perturb(mat, amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n return mat2\n\ndef approximate(mat, amount, n=1000):\n est = evaluate(mat)\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 < est:\n mat = mat2\n est = est2\n\n return mat, est\n\nfor i in xrange(1000):\n mat,est = approximate(mat, 1)\n print mat\n print est\n</code></pre>\n\n<p>The approximate call with .1 did not work for me, so I took it out. I ran it for a while too, and last I checked it was at </p>\n\n<pre><code>[[0.7576315397559887, 0, 0.11439449272592839, -0.314856490473439], \n[0.06440497208710227, 1, -0.5607502645413118, 0.38338196981556827], \n[0, 0, 1, 0], \n[0.05421620936883742, 0, -0.5673977598434641, 2.693116299312736]]\n</code></pre>\n\n<p>with an error around 0.02. </p>\n'}, {'answer_id': 43801764, 'author': 'Inflight', 'author_id': 2388690, 'author_profile': 'https://Stackoverflow.com/users/2388690', 'pm_score': 0, 'selected': False, 'text': "<p>Yes, Monte Carlo works, but I found better solution for this issue. This code works perfectly (and uses OpenCV):</p>\n\n<pre><code>Cv2.CalibrateCamera(new List<List<Point3f>>() { points3d }, new List<List<Point2f>>() { points2d }, new Size(height, width), cameraMatrix, distCoefs, out rvecs, out tvecs, CalibrationFlags.ZeroTangentDist | CalibrationFlags.FixK1 | CalibrationFlags.FixK2 | CalibrationFlags.FixK3);\n</code></pre>\n\n<p>This function takes known 3d and 2d points, size of screen and returns rotation (rvecs[0]), translation (tvecs[0]) and matrix of intrinsics values of camera. It's everything you need.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8409/'] |
76,179 | <p>What's the best way for determining whether the user's browser can view PDF files? </p>
<p>Ideally, it shouldn't matter on the browser or the operating system.</p>
<p>Is there a specific way of doing it in ASP.NET, or would the answer be just JavaScript?</p>
| [{'answer_id': 76220, 'author': 'dawnerd', 'author_id': 69503, 'author_profile': 'https://Stackoverflow.com/users/69503', 'pm_score': 2, 'selected': False, 'text': '<p>A quick google search <a href="http://www.oreillynet.com//cs/user/view/cs_msg/9920" rel="nofollow noreferrer">found this</a>. Useful for all kinds of plugins.</p>\n'}, {'answer_id': 76253, 'author': 'ddaa', 'author_id': 11549, 'author_profile': 'https://Stackoverflow.com/users/11549', 'pm_score': 5, 'selected': True, 'text': '<p>Neither, none, don\'t try.</p>\n\n<p>Re <a href="https://stackoverflow.com/questions/76179/how-to-determine-if-the-users-browser-can-view-pdf-files#76220">dawnerd</a>: Plug-in detection is not the right answer. I do not have a PDF plugin installed in my browser (Firefox on Ubuntu), yet I am able to view PDF files using the operating system\'s document viewer (which is not Acrobat Reader).</p>\n\n<p>Today, any operating system that can run a web browser can view PDF files out of the box.</p>\n\n<p>If a specific system does not have a PDF viewer installed and the browser configured to use it, that likely means that either it\'s a hand-made install of Windows, a very trimmed down alternate operating system, or something really retro.</p>\n\n<p>It is reasonable to assume that in any of those situation the user will know what a PDF file is and either deliberately choose not to be able to view them or know how to install the required software.</p>\n\n<p>If I am deluding myself, I would love to have it explained to me in which way I am wrong.</p>\n'}, {'answer_id': 76319, 'author': 'Antony', 'author_id': 12361, 'author_profile': 'https://Stackoverflow.com/users/12361', 'pm_score': 2, 'selected': False, 'text': '<p>There are users that choose not to open PDF\'s in the browser and disable the plugin (this allows the file to be opened in the native application external of the browser window). It is better to let the user know that software is required to open something (whether it be PDF or not) than try to detect whether the plugin is available.</p>\n\n<p>Another problem with detection is that what you need to look for changes from version to version (for example, see: "PDF.PdfCtrl.*" vs "AcroPDF.PDF.*" for the Adobe PDF viewer) and different browser implementations (the previously mentioned strings are used in IE for example, while Firefox uses a totally different manner of detection. Then we need to think of Opera and Safari and ???). Also, there are different vendors (think Foxit and Ghostscript, though I am not sure if they supply a plugin for the browser) where there may be differences in detecting the plugin.</p>\n\n<p><p>For a script written in 2008 and some more information about the caveats see <a href="http://www.builtfromsource.com/2007/06/26/detecting-plugins-in-internet-explorer-and-a-few-hints-for-all-the-others/" rel="nofollow noreferrer">Detecting plugins in Internet Explorer (and a few hints for all the others)</a>.</p>\n'}, {'answer_id': 87881, 'author': 'Joe Ratzer', 'author_id': 4092, 'author_profile': 'https://Stackoverflow.com/users/4092', 'pm_score': 2, 'selected': False, 'text': "<p>After initially ignoring the advise on this page the architect went ahead with Acrobat detection, causing an inevitable support nightmare.</p>\n\n<p>As ddaa mentions not all the scenarios can be accurately captured with Plug-in detection. Some users, for example, may choose to view PDF files with FoxIt Reader rather than acrobat. Some user's browsers don't flag that they are Acrobat ready, and certainly not always in the same way.</p>\n\n<p>A better solution would have been to give the user a choice on how they'd like to view the relevant document. Personally, I don't like to have any website rely on a plug-in - it spoils the beauty of the web.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4092/'] |
76,194 | <p>I seldom use inheritance, but when I do, I never use protected attributes because I think it breaks the encapsulation of the inherited classes.</p>
<p>Do you use protected attributes ? what do you use them for ?</p>
| [{'answer_id': 76224, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 3, 'selected': False, 'text': "<p>You may need them for static (or 'global') attribute you want your subclasses or classes from same package (if it is about java) to benefit from.</p>\n\n<p>Those static final attributes representing some kind of 'constant value' have seldom a getter function, so a protected static final attribute might make sense in that case.</p>\n"}, {'answer_id': 76225, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 2, 'selected': False, 'text': "<p>I don't use protected attributes in Java because they are only package protected there. But in C++, I'll use them in abstract classes, allowing the inheriting class to inherit them directly.</p>\n"}, {'answer_id': 76228, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': "<p>C#:</p>\n\n<p>I use protected for abstract or virtual methods that I want base classes to override. I also make a method protected if it may be called by base classes, but I don't want it called outside the class hierarchy.</p>\n"}, {'answer_id': 76231, 'author': 'cynicalman', 'author_id': 410, 'author_profile': 'https://Stackoverflow.com/users/410', 'pm_score': 2, 'selected': False, 'text': "<p>There are never any good reasons to have protected attributes. A base class must be able to depend on state, which means restricting access to data through accessor methods. You can't give anyone access to your private data, even children.</p>\n"}, {'answer_id': 76238, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 1, 'selected': False, 'text': "<p>In general, no you really don't want to use protected data members. This is doubly true if your writing an API. Once someone inherits from your class you can never really do maintenance and not somehow break them in a weird and sometimes wild way. </p>\n"}, {'answer_id': 76243, 'author': 'terminus', 'author_id': 9232, 'author_profile': 'https://Stackoverflow.com/users/9232', 'pm_score': 1, 'selected': False, 'text': "<p>I use them. In short, it's a good way, if you want to have some attributes shared. Granted, you could write set/get functions for them, but if there is no validation, then what's the point? It's also faster.</p>\n\n<p>Consider this: you have a class which is your base class. It has quite a few attributes you wan't to use in the child objects. You could write a get/set function for each, or you can just set them.</p>\n\n<p>My typical example is a file/stream handler. You want to access the handler (i.e. file descriptor), but you want to hide it from other classes. It's way easier than writing a set/get function for it.</p>\n"}, {'answer_id': 76248, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 1, 'selected': False, 'text': '<p>I think protected attributes are a bad idea. I use <a href="http://checkstyle.sourceforge.net/" rel="nofollow noreferrer">CheckStyle</a> to enforce that rule with my Java development teams.</p>\n'}, {'answer_id': 76277, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 1, 'selected': False, 'text': "<p>In general, yes. A protected method is usually better.</p>\n\n<p>In use, there is a level of simplicity given by using a protected <strong>final</strong> variable for an object that is shared by all the children of a class. I'd always advise against using it with primitives or collections since the contracts are impossible to define for those types.</p>\n\n<p>Lately I've come to separate stuff you do with primitives and raw collections from stuff you do with well-formed classes. Primitives and collections should ALWAYS be private.</p>\n\n<p>Also, I've started occasionally exposing public member variables when they are declaired final and are well-formed classes that are not too flexible (again, not primitives or collections). </p>\n\n<p>This isn't some stupid shortcut, I thought it out pretty seriously and decided there is absolutely no difference between a public <strong>final</strong> variable exposing an object and a getter.</p>\n"}, {'answer_id': 76286, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': "<p>Scott Meyers says <em>don't</em> use protected attributes in Effective C++ (3rd ed.):</p>\n\n<blockquote>\n <p>Item 22: Declare data members private.</p>\n</blockquote>\n\n<p>The reason is the same you give: it breaks encapsulations. The consequence is that otherwise local changes to the layout of the class might break dependent types and result in changes in many other places.</p>\n"}, {'answer_id': 87360, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 2, 'selected': False, 'text': '<p>I recently worked on a project were the "protected" member was a very good idea. The class hiearchy was something like:</p>\n\n<pre><code>[+] Base\n |\n +--[+] BaseMap\n | |\n | +--[+] Map\n | |\n | +--[+] HashMap\n |\n +--[+] // something else ?\n</code></pre>\n\n<p>The Base implemented a std::list but nothing else. The direct access to the list was forbidden to the user, but as the Base class was incomplete, it relied anyway on derived classes to implement the indirection to the list.</p>\n\n<p>The indirection could come from at least two flavors: std::map and stdext::hash_map. Both maps will behave the same way but for the fact the hash_map needs the Key to be hashable (in VC2003, castable to size_t).</p>\n\n<p>So BaseMap implemented a TMap as a templated type that was a map-like container.</p>\n\n<p>Map and HashMap were two derived classes of BaseMap, one specializing BaseMap on std::map, and the other on stdext::hash_map.</p>\n\n<p>So:</p>\n\n<ul>\n<li><p>Base was not usable as such (no public accessors !) and only provided common features and code</p></li>\n<li><p>BaseMap needed easy read/write to a std::list</p></li>\n<li><p>Map and HashMap needed easy read/write access to the TMap defined in BaseMap.</p></li>\n</ul>\n\n<p>For me, the only solution was to use protected for the std::list and the TMap member variables. There was no way I would put those "private" because I would anyway expose all or almost all of their features through read/write accessors anyway.</p>\n\n<p>In the end, I guess that if you en up dividing your class into multiple objects, each derivation adding needed features to its mother class, and only the most derived class being really usable, then protected is the way to go. The fact the "protected member" was a class, and so, was almost impossible to "break", helped.</p>\n\n<p>But otherwise, protected should be avoided as much as possible (i.e.: Use private by default, and public when you must expose the method).</p>\n'}, {'answer_id': 1546563, 'author': 'Pascal Thivent', 'author_id': 70604, 'author_profile': 'https://Stackoverflow.com/users/70604', 'pm_score': 5, 'selected': True, 'text': '<p>In this <a href="http://www.artima.com/intv/blochP.html" rel="noreferrer">interview</a> on Design by Bill Venners, Joshua Bloch, the author of <em>Effective Java</em> says:</p>\n\n<blockquote>\n <h2>Trusting Subclasses</h2>\n \n <p><strong>Bill Venners:</strong> <em>Should I trust subclasses more intimately than\n non-subclasses? For example, do I make\n it easier for a subclass\n implementation to break me than I\n would for a non-subclass? In\n particular, how do you feel about\n protected data?</em></p>\n \n <p><strong>Josh Bloch:</strong> To write something that is both subclassable and robust\n against a malicious subclass is\n actually a pretty tough thing to do,\n assuming you give the subclass access\n to your internal data structures. If\n the subclass does not have access to\n anything that an ordinary user\n doesn\'t, then it\'s harder for the\n subclass to do damage. But unless you\n make all your methods final, the\n subclass can still break your\n contracts by just doing the wrong\n things in response to method\n invocation. That\'s precisely why the\n security critical classes like String\n are final. Otherwise someone could\n write a subclass that makes Strings\n appear mutable, which would be\n sufficient to break security. So you\n must trust your subclasses. If you\n don\'t trust them, then you can\'t allow\n them, because subclasses can so easily\n cause a class to violate its\n contracts.</p>\n \n <p>As far as protected data in general,\n it\'s a necessary evil. It should be\n kept to a minimum. Most protected data\n and protected methods amount to\n committing to an implementation\n detail. A protected field is an\n implementation detail that you are\n making visible to subclasses. Even a\n protected method is a piece of\n internal structure that you are making\n visible to subclasses.</p>\n \n <p>The reason you make it visible is that\n it\'s often necessary in order to allow\n subclasses to do their job, or to do\n it efficiently. But once you\'ve done\n it, you\'re committed to it. It is now\n something that you are not allowed to\n change, even if you later find a more\n efficient implementation that no\n longer involves the use of a\n particular field or method.</p>\n \n <p>So all other things being equal, you\n shouldn\'t have any protected members\n at all. But that said, if you have too\n few, then your class may not be usable\n as a super class, or at least not as\n an efficient super class. Often you\n find out after the fact. My philosophy\n is to have as few protected members as\n possible when you first write the\n class. Then try to subclass it. You\n may find out that without a particular\n protected method, all subclasses will\n have to do some bad thing.</p>\n \n <p>As an example, if you look at\n <code>AbstractList</code>, you\'ll find that there\n is a protected method to delete a\n range of the list in one shot\n (<code>removeRange</code>). Why is that in there?\n Because the normal idiom to remove a\n range, based on the public API, is to\n call <code>subList</code> to get a sub-<code>List</code>,\n and then call <code>clear</code> on that\n sub-<code>List</code>. Without this particular\n protected method, however, the only\n thing that <code>clear</code> could do is\n repeatedly remove individual elements.</p>\n \n <p>Think about it. If you have an array\n representation, what will it do? It\n will repeatedly collapse the array,\n doing order N work N times. So it will\n take a quadratic amount of work,\n instead of the linear amount of work\n that it should. By providing this\n protected method, we allow any\n implementation that can efficiently\n delete an entire range to do so. And\n any reasonable <code>List</code> implementation\n can delete a range more efficiently\n all at once.</p>\n \n <p>That we would need this protected\n method is something you would have to\n be way smarter than me to know up\n front. Basically, I implemented the\n thing. Then, as we started to subclass\n it, we realized that range delete was\n quadratic. We couldn\'t afford that, so\n I put in the protected method. I think\n that\'s the best approach with\n protected methods. Put in as few as\n possible, and then add more as needed.\n Protected methods represent\n commitments to designs that you may\n want to change. You can always add\n protected methods, but you can\'t take\n them out.</p>\n \n <p><strong>Bill Venners:</strong> <em>And protected data?</em></p>\n \n <p><strong>Josh Bloch:</strong> The same thing, but even more. Protected data is even more\n dangerous in terms of messing up your\n data invariants. If you give someone\n else access to some internal data,\n they have free reign over it.</p>\n</blockquote>\n\n<p>Short version: it breaks encapsulation but it\'s a necessary evil that should be kept to a minimum.</p>\n'}, {'answer_id': 2034079, 'author': 'Calmarius', 'author_id': 58805, 'author_profile': 'https://Stackoverflow.com/users/58805', 'pm_score': 1, 'selected': False, 'text': '<p>It depends on what you want. If you want a fast class then data should be protected and use protected and public methods.\nBecause I think you should assume that your users who derive from your class know your class quite well or at least they have read your manual at the function they going to override.</p>\n\n<p>If your users mess with your class it is not your problem. Every malicious user can add the following lines when overriding one of your virtuals:</p>\n\n<p>(C#)</p>\n\n<pre><code>static Random rnd=new Random();\n//...\nif (rnd.Next()%1000==0) throw new Exception("My base class sucks! HAHAHAHA! xD");\n//...\n</code></pre>\n\n<p>You can\'t seal every class to prevent this.</p>\n\n<p>Of course if you want a constraint on some of your fields then use accessor functions or properties or something you want and make that field private because there is no other solution...</p>\n\n<p>But I personally don\'t like to stick to the oop principles at all costs. Especially making properties with the only purpose to make data members private.</p>\n\n<p>(C#):</p>\n\n<pre><code>private _foo;\npublic foo\n{\n get {return _foo;}\n set {_foo=value;}\n}\n</code></pre>\n\n<p>This was my personal opinion.</p>\n\n<p>But do what your boss require (if he wants private fields than do that.)</p>\n'}, {'answer_id': 2034129, 'author': 'David R Tribble', 'author_id': 170383, 'author_profile': 'https://Stackoverflow.com/users/170383', 'pm_score': 1, 'selected': False, 'text': "<p>I use protected variables/attributes within base classes that I know I don't plan on changing into methods. That way, subclasses have full access to their inherited variables, and don't have the (artificially created) overhead of going through getters/setters to access them. An example is a class using an underlying I/O stream; there is little reason not to allow subclasses direct access to the underlying stream.</p>\n\n<p>This is fine for member variables that are used in direct simple ways within the base class and all subclasses. But for a variable that has a more complicated use (e.g., accessing it causes side effects in other members within the class), a directly accessible variable is not appropriate. In this case, it can be made private and public/protected getters/setters can be provided instead. An example is an internal buffering mechanism provided by the base class, where accessing the buffers directly from a subclass would compromise the integrity of the algorithms used by the base class to manage them.</p>\n\n<p>It's a design judgment decision, based on how simple the member variable is, and how it is expected to be so in future versions.</p>\n\n<p>Encapsulation is great, but it can be taken too far. I've seen classes whose own private methods accessed its member variables using only getter/setter methods. This is overkill, since if a class can't trust its own private methods with its own private data, who can it trust?</p>\n"}, {'answer_id': 36660453, 'author': 'Jim Balter', 'author_id': 544557, 'author_profile': 'https://Stackoverflow.com/users/544557', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>protected</code> keyword is a conceptual error and language design botch, and several modern languages, such as Nim and Ceylon (see <a href="http://ceylon-lang.org/documentation/faq/language-design/#no_protected_modifier" rel="nofollow noreferrer">http://ceylon-lang.org/documentation/faq/language-design/#no_protected_modifier</a>), that have been carefully designed rather than just copying common mistakes, don\'t have such a keyword.</p>\n\n<p>It\'s not protected members that breaks encapsulation, it\'s exposing members that shouldn\'t be exposed that breaks encapsulation ... it doesn\'t matter whether they are protected or public. The problem with <code>protected</code> is that it is wrongheaded and misleading ... declaring members <code>protected</code> (rather than <code>private</code>) doesn\'t protect them, it does the opposite, exactly as <code>public</code> does. A protected member, being accessible outside the class, is exposed to the world and so its semantics must be maintained forever, just as is the case for <code>public</code>. The whole idea of "protected" is nonsense ... encapsulation is not security, and the keyword just furthers the confusion between the two. You can help a little by avoiding all uses of <code>protected</code> in your own classes -- if something is an internal part of the implementation, isn\'t part of the class\'s semantics, and may change in the future, then make it private or internal to your package, module, assembly, etc. If it is an unchangeable part of the class semantics, then make it public, and then you won\'t annoy users of your class who can see that there\'s a useful member in the documentation but can\'t use it, unless they are creating their own instances and can get at it by subclassing.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13501/'] |
76,204 | <p>I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function).</p>
<p>N.B. I am using .net 2.0 to process the XSLT</p>
<p>Here is a sample of the XML:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>some id</id>
<title>some title</title>
<updated>2008-09-11T15:53:31+01:00</updated>
<link rel="self" href="http://www.somefeedurl.co.uk" />
<author>
<name>some author</name>
<uri>http://someuri.co.uk</uri>
</author>
<generator uri="http://aardvarkmedia.co.uk/">AardvarkMedia script</generator>
<entry>
<id>http://soemaddress.co.uk/branded3/80406</id>
<title type="html">My Ttile</title>
<link rel="alternate" href="http://www.someurl.co.uk" />
<updated>2008-02-13T00:00:00+01:00</updated>
<published>2002-09-11T14:16:20+01:00</published>
<category term="mycategorytext" label="restaurant">Test</category>
<content type="xhtml">
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="vcard">
<p class="fn org">some title</p>
<p class="adr">
<abbr class="type" title="POSTAL" />
<span class="street-address">54 Some Street</span>
,
<span class="locality" />
,
<span class="country-name">UK</span>
</p>
<p class="tel">
<span class="value">0123456789</span>
</p>
<div class="geo">
<span class="latitude">51.99999</span>
,
<span class="longitude">-0.123456</span>
</div>
<p class="note">
<span class="type">Review</span>
<span class="value">Some content</span>
</p>
<p class="note">
<span class="type">Overall rating</span>
<span class="value">8</span>
</p>
</div>
</div>
</content>
<category term="cuisine-54" label="Spanish" />
<Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#">
<lat>51.123456789</lat>
<long>-0.11111111</long>
</Point>
</entry>
</feed>
</code></pre>
<p>This is XSLT</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="uniqueVenuesKey" match="entry" use="id"/>
<xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/>
<xsl:template match="/">
<locations>
<!-- Get all unique venues -->
<xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']">
<xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" ></xsl:variable>
<xsl:variable name="CurrentVenueName" select="*[local-name()='title']" ></xsl:variable>
<xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" ></xsl:variable>
<xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" ></xsl:variable>
<xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" ></xsl:variable>
<xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" ></xsl:variable>
<xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" ></xsl:variable>
<xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" ></xsl:variable>
<xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"></xsl:variable>
<location>
<locationName>
<xsl:value-of select = "$CurrentVenueName" />
</locationName>
<category>
<xsl:value-of select = "$CurrentCategory" />
</category>
<description>
<xsl:value-of select = "$CurrentVenueName" />
</description>
<venueAddress>
<streetName>
<xsl:value-of select = "$CurrentVenueAddress1" />
</streetName>
<town>
<xsl:value-of select = "$CurrentVenueCity" />
</town>
<postcode>
<xsl:value-of select = "$CurrentVenuePostcode" />
</postcode>
<wgs84_latitude>
<xsl:value-of select = "$CurrentVenueLat" />
</wgs84_latitude>
<wgs84_longitude>
<xsl:value-of select = "$CurrentVenueLong" />
</wgs84_longitude>
</venueAddress>
<venuePhone>
<phonenumber>
<xsl:value-of select = "$CurrentVenueTelephone" />
</phonenumber>
</venuePhone>
</location>
</xsl:for-each>
</locations>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>I'm trying to replace the $CurrentCategory variable the appropriate code to display <em>mycategorytext</em></p>
| [{'answer_id': 76497, 'author': 'Santiago Palladino', 'author_id': 12791, 'author_profile': 'https://Stackoverflow.com/users/12791', 'pm_score': 5, 'selected': True, 'text': "<p>I don't have an XSLT editor here, but have you tried using</p>\n\n<pre><code>*[local-name()='category']/@*[local-name()='term']\n</code></pre>\n"}, {'answer_id': 76627, 'author': 'elarson', 'author_id': 5434, 'author_profile': 'https://Stackoverflow.com/users/5434', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not really sure why you have to use local-name(), but if you share a little more info as to what xslt processor you are using along with the language, I\'ll be that can be figured out. I say this b/c you should be able to do something like:</p>\n\n<pre><code><xsl:stylesheet xmlns="http://www.w3.org/2005/Atom" ..>\n\n<xsl:template match="feed">\n <xsl:apply-templates />\n</xsl:template>\n\n<xsl:template match="entry">\n ... \n <xsl:variable name="current-category" select="category/@term" />\n ...\n</xsl:template>\n</code></pre>\n\n<p>The two things I\'m hoping help you out are the xmlns declaration at the top without a prefix. That sets the default namespace so you don\'t have to use the namespace prefixes. Likewise, you could call do \'xmlns:a="http://www.w3.org/2005/Atom"\' and then do \'select="a:feed"\'. The other thing to notice is using the \'@term\' which selects attributes. If you wanted to match on any attribute \'@*\' works just like it would for elements. </p>\n\n<p>Again, depending on the processor, there might be other helpful tools at your disposal so if you can provide a little more information it might help. Also, the <a href="http://www.mulberrytech.com/xsl/xsl-list/" rel="nofollow noreferrer">XSL mailing list</a> might another helpful resource.</p>\n'}, {'answer_id': 76658, 'author': 'Dominic Cronin', 'author_id': 9967, 'author_profile': 'https://Stackoverflow.com/users/9967', 'pm_score': 2, 'selected': False, 'text': '<p>According to <a href="http://www.w3.org/TR/2006/REC-xml-names-20060816/#scoping-defaulting" rel="nofollow noreferrer">http://www.w3.org/TR/2006/REC-xml-names-20060816/#scoping-defaulting</a></p>\n\n<p>"Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear."</p>\n\n<p>This means that your attributes aren\'t in a namespace. Just use "@term". </p>\n\n<p>Just to be a bit clearer, there is no need for using local-name() to solve this problem. \nThe conventional way to deal with it would be to declare a prefix for the atom namespace in your XSLT, and then use that in your xpath queries. </p>\n\n<p>You have already got this declaration on your stylesheet element (xmlns:atom="http://www.w3.org/2005/Atom"), so all that remains is to use it. </p>\n\n<p>As I have already explained, the attribute is not affected by the default namespace, so your code would look like this (assuming that you were to add "xmlns:xhtml=\'<a href="http://www.w3.org/1999/xhtml" rel="nofollow noreferrer">http://www.w3.org/1999/xhtml</a>\'"): </p>\n\n<pre><code> <xsl:for-each select="/atom:feed/atom:entry">\n <xsl:variable name="CurrentVenueKey" select="atom:id" />\n <xsl:variable name="CurrentVenueName" select="atom:title" />\n <xsl:variable name="CurrentVenueAddress1" \n select="atom:content/xhtml:div/xhtml:div/xhtml:p[@class=\'adr\']/xhtml:span[@class=\'street-address\']" />\n <xsl:variable name="CurrentVenueCity" \n select="atom:content/xhtml:div/xhtml:div\'/xhtml:p[@class=\'adr\']/xhtml:span[@class=\'locality\'] />\n...\n <xsl:variable name="CurrentCategory" select="atom:category/@term" />\n\n..... \n</code></pre>\n\n<p>local-name() can be very useful if you really don\'t know the structure of the XML you are transforming, but in this case, if you receive anything other than what you\'re expecting, it will break in any case. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258/'] |
76,206 | <p>Okay, I've seen but haven't programmed in C# before. You can assume I'm competent in C++, and advanced in C (for what good that'll do me). I understand inheritance, polymorphism, etc so OO concepts aren't going to be a huge problem.</p>
<p>Let's say I've been given a task to prototype a quick and dirty program that won't be much different than what I could do in access in a short time.</p>
<ul>
<li>It'll have a DB with 5-6 tables (mostly small, a few with have several thousand rows but only 4 or so columns, etc)</li>
<li>I'll need to have forms generated dynamically from one of the DBs</li>
<li>The results of the forms will be stored in another table</li>
<li>The DB isn't multiuser</li>
</ul>
<p>Basically your run of the mill access app... except without access. I'm sure I can muddle my way through and create horrendously bad code, but I'm equally sure lots of people here can give me a push in the right direction (tutorials, wizards, info, differences and killers moving from C/C++ to C#, etc).</p>
<p>Is there a simple DB I can plug in to get started aside from mdb, or is that the best choice for this particular nail? I'm aiming for a quick and dependency-less install.</p>
<p>Thanks!</p>
<p>-Adam</p>
| [{'answer_id': 76230, 'author': 'Sam', 'author_id': 9406, 'author_profile': 'https://Stackoverflow.com/users/9406', 'pm_score': 1, 'selected': False, 'text': "<p>If you already have MS Access installed, then yes the mdb is probably your quickest way to get started.</p>\n\n<p>Also you will want to just started with a quick ADO.NET tutorial. There are hundreds of these (well almost hundreds, I haven't counted).</p>\n"}, {'answer_id': 76236, 'author': 'NerdFury', 'author_id': 6146, 'author_profile': 'https://Stackoverflow.com/users/6146', 'pm_score': 3, 'selected': True, 'text': '<p>It sounds like for this app, you could use <a href="http://www.asp.net/dynamicdata/" rel="nofollow noreferrer">Microsoft Dynamic Data</a> or <a href="http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle Active Record</a>, and have the application working a few minutes after you finished the database. These tools connect to a database and generate forms for inputing data. Take a look at them.</p>\n\n<p>Access is probably your best choice for database. MS Sql 2005/2008 Express would also work well, but that would require an install.</p>\n'}, {'answer_id': 76237, 'author': 'lakshminb7', 'author_id': 3113, 'author_profile': 'https://Stackoverflow.com/users/3113', 'pm_score': 1, 'selected': False, 'text': '<p>How about using SQLlite instead of access for db? I have never used it but have heard that its good for some light weight and quick db tasks.</p>\n'}, {'answer_id': 76241, 'author': 'japollock', 'author_id': 1210318, 'author_profile': 'https://Stackoverflow.com/users/1210318', 'pm_score': 2, 'selected': False, 'text': "<p>If you're programming in C#, Visual Studio comes with an added install for SQL Server Express. If you're looking to get something up quick and dirty, it would pretty easy to leverage that database in building your app.</p>\n"}, {'answer_id': 76527, 'author': 'MagicKat', 'author_id': 8505, 'author_profile': 'https://Stackoverflow.com/users/8505', 'pm_score': 1, 'selected': False, 'text': '<p>SqlExpress would be your best bet, simply because you already have all the support that you need in System.Data.SqlClient. Other then that, there are some decent help on the MSDN.</p>\n'}, {'answer_id': 81408, 'author': 'jarrodn', 'author_id': 15273, 'author_profile': 'https://Stackoverflow.com/users/15273', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://sqlite.phxsoftware.com/" rel="nofollow noreferrer">SQLite</a> is exactly what you\'re after. It\'s a C library for accessing a file based relational database. The referred site has full visual studio support (System.Data.SQLite).</p>\n'}, {'answer_id': 81426, 'author': 'Paul Dolphin', 'author_id': 10186, 'author_profile': 'https://Stackoverflow.com/users/10186', 'pm_score': 1, 'selected': False, 'text': '<p>I would suggest using <a href="http://subsonicproject.com/" rel="nofollow noreferrer">SubSonic</a> to generate your data access code and scaffold your screens.</p>\n'}, {'answer_id': 3778553, 'author': 'pkspence', 'author_id': 356542, 'author_profile': 'https://Stackoverflow.com/users/356542', 'pm_score': 2, 'selected': False, 'text': '<p>If concurrency is <em>not</em> an issue, then I\'d say go with SQLite. An ADO.NET provider can be found here: <a href="http://sourceforge.net/projects/sqlite-dotnet2/files" rel="nofollow noreferrer">http://sourceforge.net/projects/sqlite-dotnet2/files</a>. As for the concurrency issue, when performing a bunch of inserts, that operation needs to be enclosed within a transaction. However, that transaction places an exclusive lock on the database until the transaction is either commited or rolled back. At least that\'s been my experience, but I\'ve only been using it for a week or two myself.</p>\n\n<p>Hope that helps!</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2915/'] |
76,208 | <p>Is there a good way to time SQL queries when using Linq to SQL? I really like logging feature, but it would be great if you could somehow also time that query. Any ideas?</p>
| [{'answer_id': 76235, 'author': 'Mike Becatti', 'author_id': 6617, 'author_profile': 'https://Stackoverflow.com/users/6617', 'pm_score': 0, 'selected': False, 'text': '<p>We use SQL Profiler to test our queries with LLBLGen Pro. </p>\n'}, {'answer_id': 76262, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': 2, 'selected': False, 'text': "<p>You could use a <code>System.Diagnostics.Stopwatch</code> it will allow you to track the time the query executes. Just remember that Linq->SQL queries aren't executed until you enumerate over them. Also note that if you are logging to <code>Console.Out</code> there will be a significant performance hit.</p>\n"}, {'answer_id': 76298, 'author': 'Eduardo Molteni', 'author_id': 2385, 'author_profile': 'https://Stackoverflow.com/users/2385', 'pm_score': 0, 'selected': False, 'text': '<p>The best is to log the queries to a file and them use SQL Profiler to time them and tweak the indexes for the queries.</p>\n'}, {'answer_id': 79665, 'author': 'KristoferA', 'author_id': 11241, 'author_profile': 'https://Stackoverflow.com/users/11241', 'pm_score': 3, 'selected': False, 'text': '<p>As two people already said, SQL Profiler is the out-of-the-box tool to use for that. I don\'t want to be an echo but I wanted to elaborate a bit more in detail: Not only does it provide the actual timings from SQL Server (as opposed to timing from the app-side where network i/o, connection and connection pool timings are added to the cake) but it also gives you the [often more important] I/O statistics figures, locking info (as needed) etc.</p>\n\n<p>The reason I/O statistics are important is that a very expensive query may run fast while consuming excessive amounts of server resources. If for example a query that is executed often hits large tables and there are no matching indexes resulting table scans, the affected tables will be cached in memory by SQL Server (if it can). This can sometimes cause the same query to execute blazingly fast while in effect it is harming the rest of the system/app/db by eating up server resources.</p>\n\n<p>Locking info is almost as important -> tiny queries doing PK lookups for a single record can have bad timings due to locking and blocking. I read somewhere that this very site was plagued by deadlocks in its\' early beta days. SQL Profiler is your friend for identifying and resolving problems caused by locking too.</p>\n\n<p>To summarize it; whether you use L2S, EF, plain ADO - if you want to make sure your app "behaves nice" towards the database always have SQL Profiler ready during development and testing. It pays off!</p>\n\n<p><strong>Edit:</strong> Since I wrote the answer above I have developed a new runtime profiling tool for L2S that bring the best of both worlds together; I/O stats and server-side timings from SQL Server, SQL Server execution plan, SQL Server\'s "missing index" alerts, combined with the managed call stack to make it easy to find what code generated a certain query, and some advanced filter options to log only queries that fulfill certain criteria. Additionally, the logging component can be distributed with apps to make runtime query profiling in live customer environments easier. The tool can be downloaded from: </p>\n\n<p><a href="http://www.huagati.com/L2SProfiler/" rel="nofollow noreferrer">http://www.huagati.com/L2SProfiler/</a> where you can also get a free 45-day trial license. </p>\n\n<p>A longer background description and intro to the tool is also posted here:<br>\n<a href="http://huagati.blogspot.com/2009/06/profiling-linq-to-sql-applications.html" rel="nofollow noreferrer">http://huagati.blogspot.com/2009/06/profiling-linq-to-sql-applications.html</a></p>\n\n<p>...and a sample/walkthrough of using some of the more advanced filter options is available here:<br>\n<a href="http://huagati.blogspot.com/2009/08/walkthrough-of-newest-filters-and.html" rel="nofollow noreferrer">http://huagati.blogspot.com/2009/08/walkthrough-of-newest-filters-and.html</a></p>\n'}, {'answer_id': 79684, 'author': 'Kevin Sheffield', 'author_id': 590, 'author_profile': 'https://Stackoverflow.com/users/590', 'pm_score': 4, 'selected': True, 'text': '<p>SQL Profiler to get the query and the time, and also Execution Path in Query analyzer to see where the bottlenecks are.</p>\n'}, {'answer_id': 451652, 'author': 'John Farrell', 'author_id': 25300, 'author_profile': 'https://Stackoverflow.com/users/25300', 'pm_score': 1, 'selected': False, 'text': '<p>What you could do is add a custom TextWriter implementation to the DataContext.Log which will write the generated sql to a file or memory. Then loop through those queries, executing them with raw ADO.NET code, surrounding each with a stopwatch.</p>\n\n<p>I\'ve used a similar technique before because it seemed whenever I was developing some code I never had Profiler open, and it was really easy to output those results to a HTML page. Sure your executing them twice per website request, but its helpful to see execution times asap instead of waiting until you catch something in Profiler.</p>\n\n<p>Also if your going to the SQL Tool route I would recommend googling "slowest query DMV" and getting a stored procedure that can give you stats on the slowest queries in your db. Its not always easy to scroll through profiler results to find the bad queries. Also with the right queries over sql 2005\'s dmv you can also do ordering by lets say cpu vs. time and so forth.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11063/'] |
76,210 | <p>What are current practices for enabling developers to build systems that contain private data? Can anyone point to a "best practices" guide for that sort of thing?</p>
<p>We have a Catch-22 here in that developers need to write applications that go against systems that have data that is considered "private." The IT administration would like for us developers to not have access to the data (ie. provide a schema or data structure, but not data itself) whereas most developers (myself included) would like to have access to the production data since not having a representative dataset can lead to bad assumptions (eg. the format of data) and bugs later on.</p>
<p>Does anyone have any formalized "best practices" for this type of thing? Especially official guildines from some "BigCo" (eg. Microsoft, IBM) might help since it is needed to convince management.</p>
| [{'answer_id': 76233, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 2, 'selected': False, 'text': '<p>Often times, a subset of sanitized data will be provided that is representative of the private data, but not the private data itself.</p>\n'}, {'answer_id': 76255, 'author': 'Tom Ritter', 'author_id': 8435, 'author_profile': 'https://Stackoverflow.com/users/8435', 'pm_score': 1, 'selected': False, 'text': "<p>At MediumCo, we strip proprietary data out of our production data in Test and Dev. It has hurt us a little in the past to not have exactly-representative data, but the clients have asked about this point before, and it's usually not an issue, as the environments are populated with a lot of fake proprietary data.</p>\n"}, {'answer_id': 76270, 'author': 'Brian Childress', 'author_id': 721, 'author_profile': 'https://Stackoverflow.com/users/721', 'pm_score': 2, 'selected': False, 'text': '<p>At my company, we started using <a href="http://www.red-gate.com/products/sql_data_generator/index.htm" rel="nofollow noreferrer">Red-gate</a>\'s data generator to generate test data. There is a bit of setup, but you can use the tools to generate very usable test data. Yes, I would prefer to use live production data, but it\'s not feasible (especially if you need to consider in HIPAA). It uses regex for each column and allows you to use look-up table\'s for related tables.</p>\n'}, {'answer_id': 76271, 'author': 'user13276', 'author_id': 13276, 'author_profile': 'https://Stackoverflow.com/users/13276', 'pm_score': 0, 'selected': False, 'text': "<p>I don't have any best practices paper or anything. But I would think that if you're developing out of an environment that is <em>as protected</em> as the environment that hosts the data in production, there wouldn't be a lot of argument to be made against it.</p>\n\n<p>That is, if your production database is in a datacenter hosted and controlled and secured by your IT staff, if you have a development database that lives in the exact same scenario and doesn't offer any new ways to access the information - you would be in pretty good shape. As an added token of good will - it might be nice to offer to allow anyone worried about security a chance to do some kind of penetration test to ensure that you're telling the truth about security.</p>\n\n<p>The other side of this, of course, is the analysis of the cost for not using the data: that is, it will lead to buggier code, which will cost $xxxxxx.xx in development time vs. virtually no cost to allow a small subset of your development team access to said data.</p>\n"}, {'answer_id': 76332, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 0, 'selected': False, 'text': "<p>To avoid the need to manually sanitise/anonymise data, you could use random text replacement - to replace every alphanumeric character in each text field with a random alphanumeric. This:</p>\n\n<ul>\n<li>keeps the data similar in length, size etc. from the developer's point of view</li>\n<li>does not cause problems with character sets</li>\n<li>leaves date and number fields untouched, which allows for accurate testing with respect to date ranges and quantities</li>\n<li>will satisfy most privacy requirements</li>\n</ul>\n\n<p>If you wanted to go a little further you could run random number-for-number replacement on telephone numbers and zip codes, while using alphanumeric replacement on other text fields.</p>\n\n<p>Having an automated replacement script allows you to get up-to-date data dumps from the live system regularly, so your tests are up-to-date with respect to the size and variability of the data in practice.</p>\n\n<p>It does mean that a small number of operations will not be realistic (e.g. indexing on name fields, which in real life are clustered around common letters) but these should be limited.</p>\n"}, {'answer_id': 76345, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 3, 'selected': False, 'text': "<p>My view of the world may be different, as I'm based in the UK, but for the past 20-odd years, I've worked primarily in the public sector on systems handling sensitive data.\nThe rules are **completely** cut-and-dried. No production data is allowed on the development estate.</p>\n\n<p>As a fundamental principle, we do not want to be responsible for the loss of sensitive data. The users are perfectly good at that, themselves.</p>\n\n<p>Within the past 12 months, my wife has moved from the same regime to one in the private sector where they allow developers access to production data and she's horrified by it. The legal implications (in the UK, at least) can be severe.</p>\n\n<p>Developers don't **need** access to production data. It's simply laziness. Define and create test data to exercise defined test cases (including edge cases) and don't rely on the random-esque nature of production data.</p>\n\n<p>If you **must** use production data (i.e. you manage to convince someone who doesn't know any better that it's acceptable), ensure the data is anonymised **before** it reaches the development estate.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64/'] |
76,214 | <p>Does anybody have experience of a decent J2SE (preferably at least Java JDK 1.5-level) Java Virtual Machine for Windows Mobile 6? If you know of any CLDC VMs, I'm also interested because even that would be better than what we <a href="http://www.nsicom.com/Default.aspx?tabid=138" rel="nofollow noreferrer">currently have</a> for the platform. </p>
| [{'answer_id': 76322, 'author': 'pmlarocque', 'author_id': 7419, 'author_profile': 'https://Stackoverflow.com/users/7419', 'pm_score': 1, 'selected': False, 'text': '<p>Honestly I searched a while and there no decent JVM for windows mobile. The best bet I think is this : <a href="http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html" rel="nofollow noreferrer">http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html</a> but it\'s JDK 1.3 compliant the last time I checked.</p>\n'}, {'answer_id': 78250, 'author': 'Jan Gressmann', 'author_id': 6200, 'author_profile': 'https://Stackoverflow.com/users/6200', 'pm_score': 4, 'selected': True, 'text': '<p>Yes, I\'ve tried doing things with Java on Windows Mobile. I tried really hard. The best advise I can give you is: Stop right now, and start using .NET Compact Framework.</p>\n\n<p>Anyway, the two \'good\' JVMs for WM are <a href="http://www-01.ibm.com/software/wireless/weme/" rel="nofollow noreferrer">IBM-J9</a> and NSICom Creme, which still are both terribile to work with. You\'ve already seen Creme - IBM-J9 isn\'t much better. They are slow, clumsy, not native looking and hard to install for end users. Also don\'t ever think of doing exotic things like dialing a phonenumber or even launching another application. If you really want to try, there\'s an evaluation version of J9 available <a href="http://www-128.ibm.com/developerworks/websphere/zones/wireless/weme_eval_runtimes.html?S_CMP=rnav" rel="nofollow noreferrer">here</a>. (which is identical to the full version).</p>\n\n<p>I\'m not against Java in any way, but on Windows Mobile i recommend saving the trouble and using C#.</p>\n'}, {'answer_id': 83094, 'author': 'ctacke', 'author_id': 13154, 'author_profile': 'https://Stackoverflow.com/users/13154', 'pm_score': 0, 'selected': False, 'text': '<p>You might also look at <a href="http://www.skelmir.com/solutions/handheld.html" rel="nofollow noreferrer">Skelmir\'s CEEJ</a>. It\'s been several years since I used it, but even then I was impressed with their code coverage and especially the performance.</p>\n'}, {'answer_id': 550786, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Please check the following like, this is a J2SE compatiable JVM for WM5/WM6:</p>\n\n<p><a href="http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html" rel="nofollow noreferrer">http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html</a></p>\n'}, {'answer_id': 68747534, 'author': 'Anurag Kulshrestha', 'author_id': 6845664, 'author_profile': 'https://Stackoverflow.com/users/6845664', 'pm_score': 0, 'selected': False, 'text': '<p>Try CEEJ VM. It’s very low footprint Java vm with optimisation for embedded systems. Fast and native compiler and interpreter.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4110/'] |
76,217 | <p>I've only been able to find two thus far, namely <a href="http://tinyradius.sourceforge.net/" rel="nofollow noreferrer">TinyRadius</a>, which itself discourages production use and <a href="http://www.axlradius.com/" rel="nofollow noreferrer">AXL</a>, which is pay-only.</p>
<p><a href="http://coova.org/wiki/index.php/JRadius" rel="nofollow noreferrer">JRadius</a> seems tied to <a href="http://freeradius.org/" rel="nofollow noreferrer">FreeRADIUS</a>, which isn't a library and will need a lot of cajoling to function like one.</p>
| [{'answer_id': 80536, 'author': 'Epaga', 'author_id': 6583, 'author_profile': 'https://Stackoverflow.com/users/6583', 'pm_score': 2, 'selected': False, 'text': '<p>List from <a href="http://freeradius.org/related/opensource.html" rel="nofollow noreferrer">http://freeradius.org/related/opensource.html</a> (not copying the descriptions because the page says it\'s copyright <em>rolleyes</em>):</p>\n\n<p>Cistron - <a href="http://www.radius.cistron.nl/" rel="nofollow noreferrer">http://www.radius.cistron.nl/</a></p>\n\n<p>GNU Radius - <a href="http://www.gnu.org/software/radius/" rel="nofollow noreferrer">http://www.gnu.org/software/radius/</a></p>\n\n<p>FreeRADIUS - <a href="http://freeradius.org/" rel="nofollow noreferrer">http://freeradius.org/</a></p>\n\n<p>JRadius - <a href="http://www.coova.org/JRadius" rel="nofollow noreferrer">http://www.coova.org/JRadius</a></p>\n\n<p>ICRADIUS - <a href="http://www.icradius.org/" rel="nofollow noreferrer">http://www.icradius.org/</a></p>\n\n<p>OpenRADIUS - <a href="http://www.openradius.net/" rel="nofollow noreferrer">http://www.openradius.net/</a></p>\n\n<p>XtRADIUS - <a href="http://xtradius.sourceforge.net/" rel="nofollow noreferrer">http://xtradius.sourceforge.net/</a></p>\n\n<p>YARD RADIUS - <a href="http://sourceforge.net/projects/yardradius" rel="nofollow noreferrer">http://sourceforge.net/projects/yardradius</a></p>\n'}, {'answer_id': 161617, 'author': 'Marius Marais', 'author_id': 13455, 'author_profile': 'https://Stackoverflow.com/users/13455', 'pm_score': 2, 'selected': False, 'text': "<p>OK, it seems a pure JAVA open-source RADIUS server simply does not exist. </p>\n\n<p>For completeness, I think I'm going to try one of the Python implementations through Jython to get it running in Java and start replacing pieces as and when needed.</p>\n"}, {'answer_id': 32963933, 'author': 'Pierre Smits', 'author_id': 4365894, 'author_profile': 'https://Stackoverflow.com/users/4365894', 'pm_score': 1, 'selected': False, 'text': '<p>The Apache Directory project (<a href="http://directory.apache.org" rel="nofollow">http://directory.apache.org</a>) is looking into this as people are intending to donate some java code. If and when this is successfully concluded, we (the Directory community) will most probably start a sub project and build a community to further this code into a full-fledged java based Open Source Radius server.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13455/'] |
76,223 | <p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p>
<pre><code> for (int month = 0; month < 13; month++) {
GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
</code></pre>
| [{'answer_id': 76265, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 0, 'selected': False, 'text': "<p>That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to optimize it unless you have to. </p>\n"}, {'answer_id': 76389, 'author': 'Binil Thomas', 'author_id': 3973, 'author_profile': 'https://Stackoverflow.com/users/3973', 'pm_score': 1, 'selected': False, 'text': '<p>Slightly easier to read, brute-force approach:</p>\n\n<pre><code>public int getLastFriday(int month, int year) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1, 0, 0, 0); // set to first day of the month\n cal.set(Calendar.MILLISECOND, 0);\n\n int friday = -1;\n while (cal.get(Calendar.MONTH) == month) { \n if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?\n friday = cal.get(Calendar.DAY_OF_MONTH);\n cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days\n } else {\n cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day\n }\n }\n return friday;\n}\n</code></pre>\n'}, {'answer_id': 76430, 'author': 'Hans Doggen', 'author_id': 9504, 'author_profile': 'https://Stackoverflow.com/users/9504', 'pm_score': 3, 'selected': False, 'text': '<p>I would use a library like <a href="http://joda-time.sourceforge.net" rel="noreferrer">Jodatime</a>. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.</p>\n\n<p>I think that you can have a solution with (but possibly not the shortest, but certainly more readable):</p>\n\n<pre><code>DateTime now = new DateTime(); \nDateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);\nif (dt.getMonthOfYear() != now.getMonthOfYear()) {\n dt = dt.minusDays(7);\n} \nSystem.out.println(dt);\n</code></pre>\n'}, {'answer_id': 76437, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>You never need to loop to find this out. For determining the "last Friday" date for this month, start with the first day of next month. Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on. There\'s your "last Friday." I\'m pretty sure it can be boiled down to a longish one-liner, but I\'m not a java dev. So I\'ll leave that to someone else. </p>\n'}, {'answer_id': 76447, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 1, 'selected': False, 'text': '<p>Though I agree with scubabbl, here is a version without an inner while.</p>\n\n<pre><code>int year = 2008;\nfor (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {\n Calendar cal = new GregorianCalendar(year, m, 1);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);\n if (diff > 0) {\n diff -= 7;\n }\n cal.add(Calendar.DAY_OF_MONTH, diff);\n System.out.println(cal.getTime());\n}\n</code></pre>\n'}, {'answer_id': 76744, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 2, 'selected': False, 'text': '<p>You need to know two things - the number of days in the month, and the weekday the first of the month falls on.</p>\n\n<p>If the first day of the month is a</p>\n\n<ul>\n<li>Sunday, then the last Friday is <em>always</em> the 27th.</li>\n<li>Monday, then the last Friday is <em>always</em> the 26th.</li>\n<li>Tuesday, then the last Friday is <em>always</em> the 25th.</li>\n<li>Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it\'s the 31st</li>\n<li>Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it\'s the 30th.</li>\n<li>Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it\'s the 29th.</li>\n<li>Saturday, then the last Friday is <em>always</em> the 28th.</li>\n</ul>\n\n<p>There are only three special cases. A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)</p>\n\n<p>Work it out on paper. Don\'t need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )</p>\n\n<p><a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#77315">Aaron implemented it in Java.</a></p>\n\n<p>-Adam</p>\n'}, {'answer_id': 77077, 'author': 'ColinD', 'author_id': 13792, 'author_profile': 'https://Stackoverflow.com/users/13792', 'pm_score': 6, 'selected': True, 'text': '<p>Based on <a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437">marked23\'s</a> suggestion:</p>\n\n<pre><code>public Date getLastFriday( int month, int year ) {\n Calendar cal = Calendar.getInstance();\n cal.set( year, month + 1, 1 );\n cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );\n return cal.getTime();\n}\n</code></pre>\n'}, {'answer_id': 77315, 'author': 'Aaron', 'author_id': 7659, 'author_profile': 'https://Stackoverflow.com/users/7659', 'pm_score': 2, 'selected': False, 'text': '<p>code for <a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76744">Adam Davis\'s algorithm</a></p>\n\n<pre><code>public static int getLastFriday(int month, int year)\n{\nCalendar cal = Calendar.getInstance();\ncal.set(year, month, 1, 0, 0, 0); // set to first day of the month\ncal.set(Calendar.MILLISECOND, 0);\n\nint firstDay = cal.get(Calendar.DAY_OF_WEEK);\nint daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);\n\nswitch (firstDay)\n{\n case Calendar.SUNDAY :\n return 27;\n case Calendar.MONDAY :\n return 26;\n case Calendar.TUESDAY :\n return 25;\n case Calendar.WEDNESDAY :\n if (daysOfMonth == 31) return 31;\n return 24;\n case Calendar.THURSDAY :\n if (daysOfMonth >= 30) return 30;\n return 23;\n case Calendar.FRIDAY :\n if (daysOfMonth >= 29) return 29;\n return 22;\n case Calendar.SATURDAY :\n return 28;\n}\nthrow new RuntimeException("what day of the month?");\n}}\n</code></pre>\n'}, {'answer_id': 1067710, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Hope this helps..</p>\n\n<pre><code>public static void getSundaysInThisMonth(int monthNumber, int yearNumber){\n //int year =2009;\n //int dayOfWeek = Calendar.SUNDAY;\n // instantiate Calender and set to first Sunday of 2009\n Calendar cal = new GregorianCalendar();\n cal.set(Calendar.MONTH, monthNumber-1);\n cal.set(Calendar.YEAR, yearNumber);\n cal.set(Calendar.DATE, 1);\n int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n int dateOfWeek = cal.get(Calendar.DATE);\n while (dayOfWeek != Calendar.SUNDAY) {\n cal.set(Calendar.DATE, ++dateOfWeek);\n dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n }\n cal.set(Calendar.DATE, dateOfWeek);\n\n int i = 1;\n while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)\n {\n System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));\n cal.add(Calendar.DAY_OF_MONTH, 7);\n i++;\n }\n\n }\n public static void main(String args[]){\n getSundaysInThisMonth(1,2009);\n }\n</code></pre>\n'}, {'answer_id': 2545695, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Let Calendar.class do its magic for you ;)</p>\n\n<pre><code>pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);\npCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);\n</code></pre>\n'}, {'answer_id': 7806120, 'author': 'josephus', 'author_id': 611228, 'author_profile': 'https://Stackoverflow.com/users/611228', 'pm_score': 2, 'selected': False, 'text': "<p>here's how to get the last friday, or whatever week day, of the month:</p>\n\n<pre><code>Calendar thisMonth = Calendar.getInstance();\ndayOfWeek = Calendar.FRIDAY; // or whatever\nthisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;\nthisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);\nint lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.\n</code></pre>\n"}, {'answer_id': 9469295, 'author': 'Alexeyy Alexeyy', 'author_id': 1192726, 'author_profile': 'https://Stackoverflow.com/users/1192726', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1);\n cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);\n cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);\n return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;\n}\n</code></pre>\n'}, {'answer_id': 10922864, 'author': 'akshay jangid', 'author_id': 1440879, 'author_profile': 'https://Stackoverflow.com/users/1440879', 'pm_score': 1, 'selected': False, 'text': '<p>Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable <code>offset=0</code> means current month(system date), offset=1 means next month, so on. The <code>getLastFridayofMonth(int offset)</code> method will return the last Friday.</p>\n\n<pre><code>import java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\npublic class LastFriday {\n\n public static Calendar getLastFriday(Calendar cal,int offset){\n int dayofweek;//1-Sunday,2-Monday so on....\n cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month\n dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc\n if(dayofweek<Calendar.FRIDAY) //Calendar.FRIDAY will return integer value =5 \n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);\n else\n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); \n\n return cal;\n }\n\n public static String getLastFridayofMonth(int offset) { //offset=0 mean current month\n final String DATE_FORMAT_NOW = "dd-MMM-yyyy";\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);\n cal=getLastFriday(cal,offset);\n return sdf.format(cal.getTime()); \n\n }\n\n public static void main(String[] args) {\n System.out.println(getLastFridayofMonth(0)); //0 = current month\n System.out.println(getLastFridayofMonth(1));//1=next month\n System.out.println(getLastFridayofMonth(2));//2=month after next month\n }\n\n}\n</code></pre>\n'}, {'answer_id': 22397346, 'author': 'Dhananjay Chauhan', 'author_id': 3418626, 'author_profile': 'https://Stackoverflow.com/users/3418626', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static int lastSundayDate()\n{\n Calendar cal = getCalendarInstance();\n cal.setTime(new Date(getUTCTimeMillis()));\n cal.set( Calendar.DAY_OF_MONTH , 25 );\n return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));\n}\n</code></pre>\n'}, {'answer_id': 33867973, 'author': 'Przemek', 'author_id': 1981559, 'author_profile': 'https://Stackoverflow.com/users/1981559', 'pm_score': 4, 'selected': False, 'text': '<h1>java.time</h1>\n\n<p>Using <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> library built into Java 8 and later, you may use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjusters.html#lastInMonth-java.time.DayOfWeek-" rel="noreferrer"><code>TemporalAdjusters.lastInMonth</code></a>:</p>\n\n<pre><code>val now = LocalDate.now() \nval lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))\n</code></pre>\n\n<p>You may choose any day from the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html" rel="noreferrer"><code>DayOfWeek</code></a> enum.</p>\n\n<p>If you need to add time information, you may use any available <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="noreferrer"><code>LocalDate</code></a> to <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html" rel="noreferrer"><code>LocalDateTime</code></a> conversion like</p>\n\n<pre><code>lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00\n</code></pre>\n'}, {'answer_id': 40993952, 'author': 'KayV', 'author_id': 3956731, 'author_profile': 'https://Stackoverflow.com/users/3956731', 'pm_score': 1, 'selected': False, 'text': '<p>In Java 8, we can do it simply as:</p>\n\n<pre><code>LocalDate lastFridayOfMonth = LocalDate\n .now()\n .with(lastDayOfMonth())\n .with(previous(DayOfWeek.FRIDAY));\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7008/'] |
76,227 | <p>I'm teaching a kid programming, and am introducing some basic artificial intelligence concepts at the moment. To begin with we're going to implement a tic-tac-toe game that searches the entire game tree and as such plays perfectly. Once we finish that I want to apply the same concepts to a game that has too many positions to evaluate every single one, so that we need to implement a heuristic to evaluate intermediate positions.</p>
<p>The best thing I could think of was <a href="http://en.wikipedia.org/wiki/Dots-and-boxes" rel="nofollow noreferrer">Dots and Boxes</a>. It has the advantage that I can set the board size arbitrarily large to stop him from searching the entire tree, and I can make a very basic scoring function be the number of my boxes minus the number of opponent boxes. Unfortunately this means that for most of the beginning of the game every position will be evaluated equivalently with a score of 0, because it takes quite a few moves before players actually start making boxes.</p>
<p>Does anyone have any better ideas for games? (Or a better scoring function for dots and boxes)?</p>
| [{'answer_id': 76290, 'author': 'zweiterlinde', 'author_id': 6592, 'author_profile': 'https://Stackoverflow.com/users/6592', 'pm_score': 2, 'selected': False, 'text': '<p>How about <a href="http://en.wikipedia.org/wiki/Reversi" rel="nofollow noreferrer">Reversi</a>? It has a pretty nice space of heuristics based on number of pieces, number of edge pieces, and number of corner pieces. </p>\n'}, {'answer_id': 76299, 'author': 'Dan Williams', 'author_id': 4230, 'author_profile': 'https://Stackoverflow.com/users/4230', 'pm_score': 0, 'selected': False, 'text': "<p>How about starting your Dots and Boxes game with random lines already added. This can get you into the action quickly. Just need to make sure you don't start the game with any boxes.</p>\n"}, {'answer_id': 76311, 'author': 'amrox', 'author_id': 4468, 'author_profile': 'https://Stackoverflow.com/users/4468', 'pm_score': 3, 'selected': False, 'text': '<p>Another game choice could be <a href="http://en.wikipedia.org/wiki/Reversi" rel="noreferrer">Reversi</a> aka Othello.</p>\n\n<p>A naive heuristic would be to simply count the number of tiles gained by each valid move and choose the greatest. From there you can factor in board position and minimizing vulnerably to the opponent.</p>\n'}, {'answer_id': 76337, 'author': 'ima', 'author_id': 5733, 'author_profile': 'https://Stackoverflow.com/users/5733', 'pm_score': 0, 'selected': False, 'text': '<p>Take a look at Go.</p>\n\n<ul>\n<li>Simple enough for kid on very small boards.</li>\n<li>Complexity scales infinitely.</li>\n<li>Has a lot of available papers, algorithms and programs to use either as a scale or basis.</li>\n</ul>\n\n<p>Update: reversi was mentioned, which is a simplified variant of Go. Might be a better choice.</p>\n'}, {'answer_id': 76342, 'author': 'StubbornMule', 'author_id': 13341, 'author_profile': 'https://Stackoverflow.com/users/13341', 'pm_score': 3, 'selected': False, 'text': '<p>One game you may consider is <a href="http://en.wikipedia.org/wiki/Connect_Four" rel="noreferrer">Connect Four</a>. Simple game with straightforward rules but more complicated that Tic-Tac-Toe.</p>\n'}, {'answer_id': 76343, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Connect_Four" rel="nofollow noreferrer">Four in a line</a> Hard enough, but easy enough to come up with an easy working evaluation function, for example, (distance to four from my longest line - distance to four from my opponent\'s longest line)</p>\n'}, {'answer_id': 76355, 'author': 'AShelly', 'author_id': 10396, 'author_profile': 'https://Stackoverflow.com/users/10396', 'pm_score': 2, 'selected': False, 'text': '<p>How about <a href="http://en.wikipedia.org/wiki/Mancala" rel="nofollow noreferrer">Mancala</a>? Only 6 possible moves each turn, and it\'s easy to calculate the resulting score for each, but it\'s important to consider the opponent\'s response, and the game tree gets big pretty fast.</p>\n'}, {'answer_id': 76383, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Gomoku" rel="nofollow noreferrer">Gomoku</a> is a nice, simple game, and fun one to write AI for.</p>\n'}, {'answer_id': 76385, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': '<p>Checkers will let you teach several methods. Simple lookahead, depth search of best-case-worst-case decisions, differences between short-term and long-term gains, and something they could continue to work on after learning what you want to teach them. </p>\n\n<p>Personally I think that last bit is the most critical -- there are natural points in the AI development which are good to stop at, see if you can beat it, and then delve into deeper AI mechanisms. It keeps your student interested without being horribly frustrated, and gives them more to do on their own if they want to continue the project.</p>\n'}, {'answer_id': 83505, 'author': 'Penfold', 'author_id': 11952, 'author_profile': 'https://Stackoverflow.com/users/11952', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.boardgamegeek.com/game/10060" rel="nofollow noreferrer">Rubik\'s Infinity</a>\'s quite fun, it\'s a little bit like Connect Four but subtly different. Evauluating a position is pretty easy.</p>\n\n<p>I knocked together a Perl script to play it a while back, and actually had to reduce the number of moves ahead it looked, or it beat me every time, usually with quite surprising tactics.</p>\n'}, {'answer_id': 129758, 'author': 'David Locke', 'author_id': 1447, 'author_profile': 'https://Stackoverflow.com/users/1447', 'pm_score': 0, 'selected': False, 'text': '<p>In regards to a better heuristic for dots and boxes, I suggest looking at online strategy guides for the game. The <a href="http://cf.geocities.com/ilanpi/tutorial1.html" rel="nofollow noreferrer">first result</a> on Google for "dots and boxes strategy" is quite helpful.</p>\n\n<p>Knowing how to use the chain rule separates an OK player from a good one. Knowing when the chain rule will work against you is what separates the best players from the good ones.</p>\n'}, {'answer_id': 500848, 'author': 'mdm', 'author_id': 25318, 'author_profile': 'https://Stackoverflow.com/users/25318', 'pm_score': 1, 'selected': False, 'text': '<p>I really like Connect Four. Very easy to program using a Minimax algorithm. A good evaluation function could be:</p>\n\n<pre><code>eval_score = 0\nfor all possible rows/lines/diagonals of length 4 on the board:\n if (#player_pieces = 0) // possible to connect four here?\n if (#computer_pieces = 4)\n eval_score = 10000\n break for loop\n else\n eval_score = eval_score + #computer_pieces\n (less pieces to go -> higher score)\n end if\n else if (#player_pieces = 4)\n eval_score = -10000\n break for loop\n end if\nend for\n</code></pre>\n\n<p>To improve the program you can add:</p>\n\n<ol>\n<li>If computer moves first, play in the middle column (this has been proven to be optimal)</li>\n<li>Alpha-Beta Pruning</li>\n<li>Move Ordering</li>\n<li>Zobrist Hashes</li>\n</ol>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12981/'] |
76,254 | <p>Any advice on how to read auto-incrementing identity field assigned to newly created record from call through <code>java.sql.Statement.executeUpdate</code>?</p>
<p>I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in <code>java.sql</code> to do this, and any input on people's experience with this across DB platforms.</p>
| [{'answer_id': 76292, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 0, 'selected': False, 'text': "<p>I've always had to make a second call using query after the insert.</p>\n\n<p>You could use an ORM like hibernate. I think it does this stuff for you.</p>\n"}, {'answer_id': 76348, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 6, 'selected': True, 'text': '<p>The following snibblet of code should do ya\':</p>\n\n<pre><code>PreparedStatement stmt = conn.prepareStatement(sql, \n Statement.RETURN_GENERATED_KEYS);\n// ...\n\nResultSet res = stmt.getGeneratedKeys();\nwhile (res.next())\n System.out.println("Generated key: " + res.getInt(1));\n</code></pre>\n\n<p>This is known to work on the following databases</p>\n\n<ul>\n<li>Derby</li>\n<li>MySQL</li>\n<li>SQL Server</li>\n</ul>\n\n<p>For databases where it doesn\'t work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to <code>SELECT NEXTVAL(...)</code> for the sequence in question.</p>\n\n<p>Note that the parameters for <code>executeUpdate(...)</code> are analogous.</p>\n'}, {'answer_id': 76377, 'author': 'Alexandre Victoor', 'author_id': 11897, 'author_profile': 'https://Stackoverflow.com/users/11897', 'pm_score': 0, 'selected': False, 'text': '<p>@ScArcher2 : I agree, Hibernate needs to make a second call to get the newly generated identity UNLESS an advanced generator strategy is used (sequence, hilo...)</p>\n'}, {'answer_id': 76381, 'author': 'marcospereira', 'author_id': 4600, 'author_profile': 'https://Stackoverflow.com/users/4600', 'pm_score': 2, 'selected': False, 'text': '<pre><code>ResultSet keys = statement.getGeneratedKeys();\n</code></pre>\n\n<p>Later, just iterate over ResultSet.</p>\n'}, {'answer_id': 76451, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 0, 'selected': False, 'text': '<p>@ScArcher2</p>\n\n<p>Making a second call is <em>extremely</em> dangerous. The process of <code>INSERT</code>ing and selecting the resultant auto-generated keys must be atomic, otherwise you may receive inconsistent results on the key select. Consider two asynchronous <code>INSERT</code>s where they both complete before either has a chance to select the generated keys. Which process gets which list of keys? Most cross-database ORMs have to do annoying things like in-process thread locking in order to keep results deterministic. This is <em>not</em> something you want to do by hand, especially if you are using a database which does support atomic generated key retrieval (HSQLDB is the only one I know of which does not).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5446/'] |
76,258 | <p>My production environment involves a pair of IIS 6 web servers, one running legacy .NET 1.1 applications and the other running .NET 2.0 applications. We cannot install .NET 2.0 alongside 1.1 on the same machine because it is a tightly-regulated 'Validated System' and would present a bureaucratic nightmare to revalidate.</p>
<p>Websites on both servers use Basic Authentication against Active Directory user accounts.</p>
<p>Is it possible for a web application on the 1.1 server to securely redirect a user to a page served on the 2.0 server, without requiring users to re-authenticate?</p>
| [{'answer_id': 76285, 'author': 'ScaleOvenStove', 'author_id': 12268, 'author_profile': 'https://Stackoverflow.com/users/12268', 'pm_score': -1, 'selected': False, 'text': '<p>yes, check out here</p>\n\n<p><a href="http://weblogs.asp.net/scottgu/archive/2005/12/10/432851.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2005/12/10/432851.aspx</a></p>\n'}, {'answer_id': 76326, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 0, 'selected': False, 'text': "<p>In order to achieve this you could implement a single sign-on solution. </p>\n\n<p>This solution would have one server be your master authentication server. This server would be responsible for authentication and creating a cookie for the user. When you redirect to the other server (on the same domain) check to see if the authentication cookie exists that was created by the authentication server, and if it exists, and has valid data, auto login the user. Make sure that you set the domain on the forms authentication ticket and cookie, and then both servers which exist on the same domain will be able to access this cookie.</p>\n\n<p>I would google single sign on asp.net. There's a number of ways to achieve it, but it's definitely achievable.</p>\n"}, {'answer_id': 76329, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 2, 'selected': True, 'text': "<p>No, because you're not using cookies for authentication in that scenario, so ScaleOvenStove's link won't help.</p>\n\n<p>Basic authentication sends the login information in the HTTP headers with every request, but it's the browser that does this, when it sees a new server, new password request.</p>\n\n<p>(Or indeed as suggested change the authentication on both systems to support single signon)</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9640/'] |
76,274 | <p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p>
<pre><code>var local = il.DeclareLocal(typeof(Nullable<int>));
il.Emit(OpCodes.Stloc, local);
il.Emit(OpCodes.Ldloca, local);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p>
<pre><code>il.Emit(/* not sure */);
var method = typeof(Nullable<int>).GetMethod("get_HasValue");
il.EmitCall(OpCodes.Call, method, null);
</code></pre>
<p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p>
<p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p>
<p>**** Edit: Additional Notes ****</p>
<p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p>
<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);
var il = m.GetILGenerator();
var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });
il.Emit(OpCodes.Ldc_I4_6);
il.Emit(OpCodes.Newobj, ctor);
//var local = il.DeclareLocal(typeof(Nullable<int>));
//il.Emit(OpCodes.Stloc, local);
//il.Emit(OpCodes.Ldloca, local);
var getValue = typeof(Nullable<int>).GetMethod("get_HasValue");
il.Emit(OpCodes.Call, getValue);
il.Emit(OpCodes.Ret);
Console.WriteLine(m.Invoke(null, null));
</code></pre>
<p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p>
<p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>
| [{'answer_id': 76320, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': 3, 'selected': True, 'text': '<p>If the variable is already on the stack, you can go ahead and just emit the method call. </p>\n\n<p>It seems that the constructor doesn\'t push the variable on the stack in a typed form. After digging into the IL a bit, it appears there are two ways of using the variable after constructing it. </p>\n\n<p>You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so:</p>\n\n<pre><code>DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);\nILGenerator il = method.GetILGenerator();\nType nullable = typeof(Nullable<int>);\nConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) });\nMethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod();\nLocalBuilder value = il.DeclareLocal(nullable); \n\n// load the variable to assign the value from the ctor to\nil.Emit(OpCodes.Ldloca_S, value);\n// load constructor args\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Call, ctor);\nil.Emit(OpCodes.Ldloca_S, value);\n\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(method.Invoke(null, null));\n</code></pre>\n\n<p>The other option is doing it the way you have shown. The only reason for this that I can see is that the ctor methods return void, so they don\'t put their value on the stack like other methods. It does seem strange that you can call Setloc if the new object isn\'t on the stack.</p>\n'}, {'answer_id': 90650, 'author': 'Nick Johnson', 'author_id': 12030, 'author_profile': 'https://Stackoverflow.com/users/12030', 'pm_score': 1, 'selected': False, 'text': "<p>After looking at the options some more and further consideration, I think you're right in assuming it can't be done. If you examine the stack behaviour of MSIL instructions, you can see that no op leaves its operand(s) on the stack. Since this would be a requirement for a 'get address of stack entry' op, I'm fairly confident one doesn't exist.</p>\n\n<p>That leaves you with either dup+box or stloc+ldloca. As you've pointed out, the latter is likely more efficient.</p>\n\n<p>@greg: Many instructions leave their <em>result</em> on the stack, but no instructions leave any of their <em>operands</em> on the stack, which would be required for a 'get stack element address' instruction.</p>\n"}, {'answer_id': 10883566, 'author': 'Mark', 'author_id': 64084, 'author_profile': 'https://Stackoverflow.com/users/64084', 'pm_score': 0, 'selected': False, 'text': "<p>Just wrote a class that does what the OP is asking... here's the IL code that C# compiler produces:</p>\n\n<pre><code> IL_0008: ldarg.0\n IL_0009: ldarg.1\n IL_000a: newobj instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)\n IL_000f: stfld valuetype [mscorlib]System.Nullable`1<int32> ConsoleApplication3.Temptress::_X\n IL_0014: nop\n IL_0015: ret\n</code></pre>\n"}, {'answer_id': 36076570, 'author': 'Mayoor', 'author_id': 4167620, 'author_profile': 'https://Stackoverflow.com/users/4167620', 'pm_score': 2, 'selected': False, 'text': '<p>I figured it out! Luckily I was reading about the <code>unbox</code> opcode and noticed that it pushes the <strong>address</strong> of the value. <code>unbox.any</code> pushes the actual value. So, in order to call a method on a value type without having to store it in a local variable and then load its address, you can simply <code>box</code> followed by <code>unbox</code>. Using your last example:</p>\n\n<pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes);\nvar il = m.GetILGenerator();\nvar ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) });\nil.Emit(OpCodes.Ldc_I4_6);\nil.Emit(OpCodes.Newobj, ctor);\nil.Emit(OpCodes.Box, typeof(Nullable<int>)); // box followed by unbox\nil.Emit(OpCodes.Unbox, typeof(Nullable<int>));\nvar getValue = typeof(Nullable<int>).GetMethod("get_HasValue");\nil.Emit(OpCodes.Call, getValue);\nil.Emit(OpCodes.Ret);\nConsole.WriteLine(m.Invoke(null, null));\n</code></pre>\n\n<p>The downside to this is that boxing causes memory allocation for the boxed object, so it is a bit slower than using local variables (which would already be allocated). But, it saves you from having to determine, declare, and reference all of the local variables you need.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13552/'] |
76,275 | <p>I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user_1 without killing attachemate.exe started by user_2.</p>
<p>I want to use VBScript.</p>
| [{'answer_id': 76309, 'author': 'Colin Neller', 'author_id': 12571, 'author_profile': 'https://Stackoverflow.com/users/12571', 'pm_score': 2, 'selected': False, 'text': '<p>Shell out to pskill from <a href="http://sysinternals.com/" rel="nofollow noreferrer">http://sysinternals.com/</a></p>\n\n<p>Commandline: pskill -u user_1 attachemate.exe</p>\n'}, {'answer_id': 89397, 'author': 'unrealtrip', 'author_id': 11130, 'author_profile': 'https://Stackoverflow.com/users/11130', 'pm_score': 4, 'selected': True, 'text': '<p>You could use this to find out who the process owner is, then once you have that you can use Win32_Process to kill the process by the process ID.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa394372.aspx" rel="noreferrer">MSDN Win32_Process class details</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx" rel="noreferrer">MSDN Terminating a process with Win32_Process</a></p>\n\n<p>There is surely a cleaner way to do this, but here\'s what I came up with. NOTE: This doesn\'t deal with multiple processes of the same name of course, but I figure you can work that part out with an array to hold them or something like that. :)</p>\n\n<pre><code>strComputer = "."\nstrOwner = "A111111"\nstrProcess = "\'notepad.exe\'"\n\n\' Connect to WMI service and Win32_Process filtering by name\'\nSet objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\\\" _\n & strComputer & "\\root\\cimv2")\nSet colProcessbyName = objWMIService.ExecQuery("Select * from Win32_Process Where Name = " _\n & strProcess)\n\n\' Get the process ID for the process started by the user in question\'\nFor Each objProcess in colProcessbyName\n colProperties = objProcess.GetOwner(strUsername,strUserDomain)\n if strUsername = strOwner then\n strProcessID = objProcess.ProcessId\n end if\nnext\n\n\' We have the process ID for the app in question for the user, now we kill it\'\nSet colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & strProcessID)\nFor Each objProcess in colProcess\n objProcess.Terminate()\nNext\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9882/'] |
76,291 | <p>Is there a tool to detect unneeded jar-files?</p>
<p>For instance say that I have myapp.jar, which I can launch with a classpath containing hibernate.jar, junit.jar and easymock.jar. But actually it will work fine using only hibernate.jar, since the code that calls junit.jar is not reachable.</p>
<p>I realize that reflection might complicate things, but I could live with a tool that ignored reflection. Except for that it seems like a relatively simple problem to solve.</p>
<p>If there is no such tool, what is best practices for deciding which dependencies are needed? It seems to me that it must be a common problem.</p>
| [{'answer_id': 76338, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 2, 'selected': False, 'text': "<p>This is not possible in a system that might use reflection.</p>\n\n<p>That said, a static analysis tool could do a pretty good job if you don't use ANY reflection.</p>\n"}, {'answer_id': 77021, 'author': 'shadit', 'author_id': 9925, 'author_profile': 'https://Stackoverflow.com/users/9925', 'pm_score': 2, 'selected': False, 'text': '<p>Have you taken a look at Dependency Finder?</p>\n\n<p><a href="http://depfind.sourceforge.net/" rel="nofollow noreferrer">http://depfind.sourceforge.net/</a></p>\n\n<p>A handy list of most of the other available Java dependency tools is also available on that site.</p>\n'}, {'answer_id': 77066, 'author': 'triggerNZ', 'author_id': 13822, 'author_profile': 'https://Stackoverflow.com/users/13822', 'pm_score': 1, 'selected': False, 'text': '<p>I have used </p>\n\n<p><a href="http://code.google.com/p/jarjar/" rel="nofollow noreferrer">http://code.google.com/p/jarjar/</a> </p>\n\n<p>and found it to be pretty good.</p>\n\n<p>Also, you will find out if you have broken any reflection easily if you have a good set of unit/acceptance tests :).</p>\n'}, {'answer_id': 77081, 'author': 'Nikolai Prokoschenko', 'author_id': 6460, 'author_profile': 'https://Stackoverflow.com/users/6460', 'pm_score': 0, 'selected': False, 'text': "<p>Something to add to Bill K's reply: you might not use reflection at all, but the JARs you are using might. I remember encountering something like that with xalan & xerces, where a ClassNotFoundException has been thrown at runtime.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5542/'] |
76,300 | <p>In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:</p>
<pre><code>final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
MessageBox mb = /* ... */;
/* set up messagebox */
result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }
</code></pre>
<p>I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?</p>
| [{'answer_id': 76393, 'author': 'Dónal', 'author_id': 2648, 'author_profile': 'https://Stackoverflow.com/users/2648', 'pm_score': 1, 'selected': False, 'text': '<p>ArrayList is <em>not</em> thread-safe. From the relevant <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html" rel="nofollow noreferrer">Javadoc</a>:</p>\n\n<blockquote>\n <p>Note that this implementation is not\n synchronized. If multiple threads\n access an ArrayList instance\n concurrently, and at least one of the\n threads modifies the list\n structurally, it must be synchronized\n externally.</p>\n</blockquote>\n\n<p>If you need a thread-safe implementation of List, there are (at least) two provided in the JDK: CopyOnWriteArrayList and Vector.</p>\n'}, {'answer_id': 76431, 'author': 'Heath Borders', 'author_id': 9636, 'author_profile': 'https://Stackoverflow.com/users/9636', 'pm_score': 4, 'selected': True, 'text': '<p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html" rel="nofollow noreferrer"><code>ArrayList</code> is not thread-safe</a>. You can obtain a thread-safe <code>List</code> with <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29" rel="nofollow noreferrer"><code>Collections.synchronizedList</code></a>. However, it is much simpler to use an <code>AtomicInteger</code> in your case or <code>AtomicReference</code> in a more general case.</p>\n\n<pre><code>final AtomicInteger resultAtomicInteger = new AtomicInteger();\nDisplay.getCurrent().syncExec(new Runnable() { \n public void run() {\n MessageBox mb = /* ... */;\n /* set up messagebox */\n resultAtomicInteger.set(mb.open());\n}});\nif (SWT.OK == resultAtomicInteger.get()) { /* ... */ }\n</code></pre>\n'}, {'answer_id': 76443, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 1, 'selected': False, 'text': "<p>You could use an Integer[1] array to make it more concise but I don't think it can directly update a non-final variable from inside an anonymous inner class.</p>\n\n<pre><code>final Integer[] result = new Integer[1];\n</code></pre>\n\n<p>I thought that you had to declare results as final (but that change wouldn't affect your code). Since the current Thread blocks until the inner Thread is finished I don't think you need to worry about synchronization (but you might need to make the variable violate so that you see the result).</p>\n"}, {'answer_id': 101304, 'author': 'Bahadır Yağan', 'author_id': 3812, 'author_profile': 'https://Stackoverflow.com/users/3812', 'pm_score': 1, 'selected': False, 'text': '<p>If this happens often, you better use subscribe/notify model between your process and view. Your view subscribes to the event which should trigger that message box and gets notified when conditions met.</p>\n'}, {'answer_id': 8941478, 'author': 'crevos', 'author_id': 1160611, 'author_profile': 'https://Stackoverflow.com/users/1160611', 'pm_score': 2, 'selected': False, 'text': "<p>I just tackled this problem and my first try was similar - array or list of desired type items. But after a while I made up something like this:</p>\n\n<pre><code>abstract class MyRunnable<T> implements Runnable{\n T result;\n}\nMyRunnable<Integer> runBlock = new MyRunnable<Integer>(){\n MessageBox mb = /* ... */;\n /* set up messagebox */\n result = mb.open();\n}\nGUI.display().syncExec(runBlock);\nrunBlock.result; //holds a result Integer\n</code></pre>\n\n<p>It's much tidier and removes redundant variables.</p>\n\n<p>BTW. My really first try was to use UIThreadRunnable, but I didn't want SWTBot dependency, so I dropped this solution. After I made my own solution I found out, they use similar work around in there.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13581/'] |
76,314 | <p>I'm trying to figure out what a Java applet's class file is doing under the hood. Opening it up with Notepad or Textpad just shows a bunch of gobbledy-gook.</p>
<p>Is there any way to wrangle it back into a somewhat-readable format so I can try to figure out what it's doing?</p>
<ul>
<li>Environment == Windows w/ VS 2008 installed.</li>
</ul>
| [{'answer_id': 76330, 'author': 'Rasmus Faber', 'author_id': 5542, 'author_profile': 'https://Stackoverflow.com/users/5542', 'pm_score': 2, 'selected': False, 'text': '<p>Using <a href="http://www.javadecompilers.com/jad" rel="nofollow noreferrer">Jad</a> to decompile it is probably your best option. Unless the code has been obfuscated, it will produce an okay result.</p>\n'}, {'answer_id': 76336, 'author': 'cynicalman', 'author_id': 410, 'author_profile': 'https://Stackoverflow.com/users/410', 'pm_score': 1, 'selected': False, 'text': '<p>That\'s compiled code, you\'ll need to use a decompiler like JAD: <a href="http://www.kpdus.com/jad.html" rel="nofollow noreferrer">http://www.kpdus.com/jad.html</a></p>\n'}, {'answer_id': 76351, 'author': 'Drew Frezell', 'author_id': 10954, 'author_profile': 'https://Stackoverflow.com/users/10954', 'pm_score': 3, 'selected': False, 'text': '<p>You want a java decompiler, you can use the command line tool <code>javap</code> to do this. Also, <a href="http://www.faqs.org/docs/Linux-HOWTO/Java-Decompiler-HOWTO.html" rel="noreferrer">Java Decompiler HOW-TO</a> describes how you can decompile a class file.</p>\n'}, {'answer_id': 76356, 'author': 'David Beleznay', 'author_id': 13359, 'author_profile': 'https://Stackoverflow.com/users/13359', 'pm_score': 2, 'selected': False, 'text': '<p>what you are looking for is a java de-compiler. I recommend JAD <a href="http://www.kpdus.com/jad.html" rel="nofollow noreferrer">http://www.kpdus.com/jad.html</a> It\'s free for non commercial use and gets the job done. </p>\n\n<p>Note: this isn\'t going to make the code exactly the same as what was written. i.e. you\'re going to lose comments and possibly variable names, so it\'s going to be a little bit harder than just reading normal source code. If the developer is really secretive they will have obfuscated their code as well, making it even harder to read. </p>\n'}, {'answer_id': 76371, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>As suggested you can use JAD to decompile it and view the files. To make it easier to read you can use the JADclipse plugin for eclipse to integrate JAD directly to eclipse or use DJ Java Decompiler which is much easier to use than command line JAD</p>\n'}, {'answer_id': 76375, 'author': 'Michael Myers', 'author_id': 13531, 'author_profile': 'https://Stackoverflow.com/users/13531', 'pm_score': 6, 'selected': False, 'text': "<p>If you don't mind reading bytecode, javap should work fine. It's part of the standard JDK installation.</p>\n\n<pre><code>Usage: javap <options> <classes>...\n\nwhere options include:\n -c Disassemble the code\n -classpath <pathlist> Specify where to find user class files\n -extdirs <dirs> Override location of installed extensions\n -help Print this usage message\n -J<flag> Pass <flag> directly to the runtime system\n -l Print line number and local variable tables\n -public Show only public classes and members\n -protected Show protected/public classes and members\n -package Show package/protected/public classes\n and members (default)\n -private Show all classes and members\n -s Print internal type signatures\n -bootclasspath <pathlist> Override location of class files loaded\n by the bootstrap class loader\n -verbose Print stack size, number of locals and args for methods\n If verifying, print reasons for failure\n</code></pre>\n"}, {'answer_id': 76392, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 0, 'selected': False, 'text': '<p>JAD is an excellent option if you want readable Java code as a result. If you really want to dig into the internals of the <code>.class</code> file format though, you\'re going to want <code>javap</code>. It\'s bundled with the JDK and allows you to "decompile" the hexadecimal bytecode into readable ASCII. The language it produces is still bytecode (not anything like Java), but it\'s fairly readable and extremely instructive.</p>\n\n<p>Also, if you <em>really</em> want to, you can open up any <code>.class</code> file in a hex editor and read the bytecode directly. The result is identical to using <code>javap</code>.</p>\n'}, {'answer_id': 76410, 'author': 'DarenW', 'author_id': 10468, 'author_profile': 'https://Stackoverflow.com/users/10468', 'pm_score': 9, 'selected': True, 'text': '<p><a href="http://jd.benow.ca/" rel="noreferrer">jd-gui</a> is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.</p>\n'}, {'answer_id': 76419, 'author': 'Zac Gochenour', 'author_id': 1812999, 'author_profile': 'https://Stackoverflow.com/users/1812999', 'pm_score': 1, 'selected': False, 'text': "<p>You need to use a decompiler. Others have suggested JAD, there are other options, JAD is the best.</p>\n\n<p>I'll echo the comments that you may lose a bit compared to the original source code. It is going to look especially funny if the code used generics, due to erasure.</p>\n"}, {'answer_id': 76728, 'author': 'John Gardner', 'author_id': 13687, 'author_profile': 'https://Stackoverflow.com/users/13687', 'pm_score': 1, 'selected': False, 'text': '<p>JAD and/or JADclipse Eclipse plugin, for sure.</p>\n'}, {'answer_id': 76848, 'author': 'Arno', 'author_id': 13685, 'author_profile': 'https://Stackoverflow.com/users/13685', 'pm_score': 0, 'selected': False, 'text': '<p>There is no need to decompile Applet.class. The public Java API classes sourcecode comes with the JDK (if you choose to install it), and is better readable than decompiled bytecode. You can find compressed in src.zip (located in your JDK installation folder).</p>\n'}, {'answer_id': 84499, 'author': 'arturh', 'author_id': 4186, 'author_profile': 'https://Stackoverflow.com/users/4186', 'pm_score': 1, 'selected': False, 'text': '<p>If the class file you want to look into is open source, you should not decompile it, but instead attach the source files directly into your IDE. that way, you can just view the code of some library class as if it were your own</p>\n'}, {'answer_id': 389596, 'author': 'Emmanuel Dupuy', 'author_id': 37785, 'author_profile': 'https://Stackoverflow.com/users/37785', 'pm_score': 2, 'selected': False, 'text': '<p>cpuguru, if your applet has been compiled with javac 1.3 (or less), your best option is to use Jad.</p>\n\n<p>Unfortunately, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.</p>\n\n<p>If your applet has been compiled with a more recent compiler, you could try <a href="http://java.decompiler.free.fr" rel="nofollow noreferrer">JD-GUI</a> : this decompiler is under development, nevertheless, it generates correct Java sources, most of time, for classes compiled with the JDKs 1.4, 1.5 or 1.6.</p>\n\n<p>DarenW, thank you for your post. JD-GUI is not the best decompiler yet ... but I\'m working on :)</p>\n'}, {'answer_id': 19048083, 'author': 'Karthikeyan Subramanian', 'author_id': 2606929, 'author_profile': 'https://Stackoverflow.com/users/2606929', 'pm_score': 2, 'selected': False, 'text': '<p>jd-gui "<a href="http://code.google.com/p/innlab/downloads/detail?name=jd-gui-0.3.3.windows.zip&can=2&q=" rel="nofollow">http://code.google.com/p/innlab/downloads/detail?name=jd-gui-0.3.3.windows.zip&can=2&q=</a>" is the best and user friendly option for decompiling .class file....</p>\n'}, {'answer_id': 41721294, 'author': 'tidbeck', 'author_id': 562935, 'author_profile': 'https://Stackoverflow.com/users/562935', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.benf.org/other/cfr/" rel="nofollow noreferrer">CFR - another java decompiler</a> is a great decompiler for modern Java written i Java 6.</p>\n'}, {'answer_id': 48830353, 'author': 'Nilashish C', 'author_id': 9252645, 'author_profile': 'https://Stackoverflow.com/users/9252645', 'pm_score': 4, 'selected': False, 'text': '<p>As pointed out by @MichaelMyers, use </p>\n\n<pre><code>javap -c <name of java class file> \n</code></pre>\n\n<p>to get the JVM assembly code. You may also redirect the output to a text file for better visibility.</p>\n\n<pre><code>javap -c <name of java class file> > decompiled.txt\n</code></pre>\n'}, {'answer_id': 48947226, 'author': 'Prachi Sharma', 'author_id': 8405520, 'author_profile': 'https://Stackoverflow.com/users/8405520', 'pm_score': 2, 'selected': False, 'text': '<p>you can also use the online java decompilers available. For e.g. <a href="http://www.javadecompilers.com" rel="nofollow noreferrer">http://www.javadecompilers.com</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2312/'] |
76,324 | <p>I really want to get the google Calendar Api up an running. I found a <a href="http://www.ibm.com/developerworks/library/x-googleclndr/" rel="nofollow noreferrer">great article</a> about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading.</p>
<p>I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar.</p>
<pre><code>Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?'
</code></pre>
<p>I have looked in many places to try to get OpenSSL running on my machine and installed. </p>
<p>Does anyone know of a simple failsafe tutorial to get this combination up and running?</p>
| [{'answer_id': 76608, 'author': 'DustinB', 'author_id': 7888, 'author_profile': 'https://Stackoverflow.com/users/7888', 'pm_score': 0, 'selected': False, 'text': '<p>Could you have mistyped the PROTOCOL in the URL? It should be HTTPS, not "SSL". For example, , not SSL://www.google.com:443. Can you double check this in your example client and make sure it is HTTPS, not SSL.</p>\n'}, {'answer_id': 76975, 'author': 'Toby Allen', 'author_id': 6244, 'author_profile': 'https://Stackoverflow.com/users/6244', 'pm_score': 2, 'selected': True, 'text': '<p>I think this use of SSL is part of the Zend GData library so I assume it is correct. I think not having OpenSSL correctly installed is my main issue.</p>\n'}, {'answer_id': 202809, 'author': 'Daniel Rucci', 'author_id': 27604, 'author_profile': 'https://Stackoverflow.com/users/27604', 'pm_score': 2, 'selected': False, 'text': '<p>First it would be helpful if you mentioned your OS, I\'ll assume windows.</p>\n\n<p>Check the output of </p>\n\n<pre><code><?php echo phpinfo();?>\n</code></pre>\n\n<p>If the OpenSSL library is enabled "Registered Stream Socket Transports" will mention ssl</p>\n\n<p>Your php.ini should have </p>\n\n<pre><code>[PHP_OPENSSL]\nextension=php_openssl.dll\n</code></pre>\n\n<p>If its not there, or you add it and php complains then you should re-run the installer and go through the list of extensions, it would be under OpenSSL.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6244/'] |
76,325 | <p>How do I move an active directory group to another organizational unit using Powershell?</p>
<p>ie.</p>
<p>I would like to move the group "IT Department" from:</p>
<pre><code> (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca)
</code></pre>
<p>to:</p>
<pre><code> (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca)
</code></pre>
| [{'answer_id': 80253, 'author': 'Steven Murawski', 'author_id': 1233, 'author_profile': 'https://Stackoverflow.com/users/1233', 'pm_score': 2, 'selected': False, 'text': '<p>I haven\'t tried this yet, but this should do it..</p>\n\n<pre><code>$objectlocation= \'CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca\'\n$newlocation = \'OU=Temporarily Moved Groups, DC=Company,DC=ca\'\n\n$from = new-object System.DirectoryServices.DirectoryEntry("LDAP://$objectLocation")\n$to = new-object System.DirectoryServices.DirectoryEntry("LDAP://$newlocation")\n$from.MoveTo($newlocation,$from.name)\n</code></pre>\n'}, {'answer_id': 85685, 'author': 'Eldila', 'author_id': 889, 'author_profile': 'https://Stackoverflow.com/users/889', 'pm_score': 4, 'selected': True, 'text': '<p>Your script was really close to correct (and I really appreciate your response).</p>\n\n<p>The following script is what I used to solve my problem.:</p>\n\n<pre><code>$from = [ADSI]"LDAP://CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca"\n$to = [ADSI]"LDAP://OU=Temporarily Moved Groups, DC=Company,DC=ca"\n$from.PSBase.MoveTo($to,"cn="+$from.name)\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/889/'] |
76,327 | <p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p>
| [{'answer_id': 76418, 'author': 'svrist', 'author_id': 86, 'author_profile': 'https://Stackoverflow.com/users/86', 'pm_score': 1, 'selected': False, 'text': '<p><em>EDIT: Cleanup info and summarize</em></p>\n\n<p>Summary:</p>\n\n<ul>\n<li>Its a feature, not a bug</li>\n<li>It can be turned of with -XX:-UsePerfData which might hurt performance</li>\n</ul>\n\n<p>Relevant info:</p>\n\n<ul>\n<li><a href="http://forums.sun.com/thread.jspa?threadID=587299&messageID=4257939" rel="nofollow noreferrer">Sun forum</a></li>\n<li><a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5012932" rel="nofollow noreferrer">Bugreport</a></li>\n</ul>\n'}, {'answer_id': 76423, 'author': 'Kyle Renfro', 'author_id': 8187, 'author_profile': 'https://Stackoverflow.com/users/8187', 'pm_score': 6, 'selected': True, 'text': '<p>Try JVM option <strong>-XX:-UsePerfData</strong></p>\n\n<p><a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html" rel="noreferrer">more info</a></p>\n\n<p>The following might be helpful that is from link <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p>\n\n<pre><code>-XX:+UsePerfData\n\n Enables the perfdata feature. This option is enabled by default\n to allow JVM monitoring and performance testing. Disabling it \n suppresses the creation of the hsperfdata_userid directories. \n To disable the perfdata feature, specify -XX:-UsePerfData.\n</code></pre>\n'}, {'answer_id': 76503, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 1, 'selected': False, 'text': '<p>From svrist\'s link:</p>\n\n<blockquote>\n <p>The first item in <a href="http://java.sun.com/performance/jvmstat/faq.html" rel="nofollow noreferrer">http://java.sun.com/performance/jvmstat/faq.html</a> mentions an option which you can turn off to disable the whole suite of features: -XX:-UsePerfData.</p>\n</blockquote>\n'}, {'answer_id': 76506, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 1, 'selected': False, 'text': '<p>According to the <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5012932" rel="nofollow noreferrer">filed bug report</a> there is a work-around:</p>\n<blockquote>\n<p>This undocumented option will disable\nthe perfdata feature:<br />\n-XX:-UsePerfData</p>\n</blockquote>\n<p>It\'s worth mentioning that it is a feature though, not a bug. The above work-around just disables the feature.</p>\n'}, {'answer_id': 3060276, 'author': 'Zweiberg', 'author_id': 369132, 'author_profile': 'https://Stackoverflow.com/users/369132', 'pm_score': 2, 'selected': False, 'text': '<p>There is also <code>"-XX:+PerfDisableSharedMem"</code> option (recommended by Sun) which should cause less performance issues than use of <code>"-XX:-UsePerfData"</code> option.</p>\n'}, {'answer_id': 3933583, 'author': 'Jon Stafford', 'author_id': 277208, 'author_profile': 'https://Stackoverflow.com/users/277208', 'pm_score': 5, 'selected': False, 'text': '<p>Use the JVM option <strong><code>-XX:-UsePerfData</code></strong>.</p>\n\n<p>This will not have a negative effect on performance, as some other answers say.</p>\n\n<p>By default jvmstat instrumentation is turned on in the HotSpot JVM. The JVM option <code>-XX:-UsePerfData</code> turns it off. If anything, I would speculate, turning off the instrumentation would improve performance (a trivial amount).</p>\n\n<p>So the downside of turning off jvmstat instrumentation is that you lose the performance monitoring information.</p>\n\n<p>jvmstat is described here <a href="http://java.sun.com/performance/jvmstat/" rel="noreferrer">http://java.sun.com/performance/jvmstat/</a></p>\n\n<p>Here\'s a thread with someone who is worried that by turning <strong>on</strong> jvmstat - with the option <code>-XX:+UsePerfData</code> - will hurt performance.\n<a href="http://www.theserverside.com/discussions/thread.tss?thread_id=33833" rel="noreferrer">http://www.theserverside.com/discussions/thread.tss?thread_id=33833</a><br>\n(It probably won\'t since jvmstat is designed to be "\'always on\', yet has negligible performance impact".)</p>\n'}, {'answer_id': 5435817, 'author': 'Mack', 'author_id': 455512, 'author_profile': 'https://Stackoverflow.com/users/455512', 'pm_score': 2, 'selected': False, 'text': '<p>Rather than switching it off, change the java.io.tmpdir location.\nAdd -Djava.io.tmpdir=/mydir/somewhere/else/ to your Java startup command\nand then the file will be somewhere that you control. </p>\n\n<hr>\n\n<p>Note a comment by @simonc: this only works in a few versions of the JVM and is no longer supported. See <a href="http://bugs.sun.com/view_bug.do?bug_id=6447182" rel="nofollow">http://bugs.sun.com/view_bug.do?bug_id=6447182</a>, <a href="http://bugs.sun.com/view_bug.do?bug_id=6938627" rel="nofollow">http://bugs.sun.com/view_bug.do?bug_id=6938627</a>, <a href="http://bugs.sun.com/view_bug.do?bug_id=7009828" rel="nofollow">http://bugs.sun.com/view_bug.do?bug_id=7009828</a> for more information.</p>\n'}, {'answer_id': 52630279, 'author': 'user6494409', 'author_id': 6494409, 'author_profile': 'https://Stackoverflow.com/users/6494409', 'pm_score': 2, 'selected': False, 'text': '<p>As an addendum to Mack\'s reply (answered Mar 25 \'11 at 17:12), the option java.tmp.dir looks no longer available since Java 8. See the info at: <a href="https://bugs.java.com/view_bug.do?bug_id=8189674" rel="nofollow noreferrer">https://bugs.java.com/view_bug.do?bug_id=8189674</a></p>\n\n<p>So disabling the option using -XX:-UsePerfData seems the only option not to have hsperfdata_* files.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13582/'] |
76,328 | <p>PHP5 has a "magic method" <code>__call()</code>that can be defined on any class that is invoked when an undefined method is called -- it is roughly equivalent to Ruby's <code>method_missing</code> or Perl's <code>AUTOLOAD</code>. Is it possible to do something like this in older versions of PHP?</p>
| [{'answer_id': 76399, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 0, 'selected': False, 'text': '<p>I recall using it, and a little bit of googling suggests that</p>\n\n<pre><code>function __call($method_name, $parameters, &$return)\n{\n $return_value = "You called ${method_name}!";\n}\n</code></pre>\n\n<p>as a member function will do the job.</p>\n'}, {'answer_id': 112606, 'author': 'jes5199', 'author_id': 13195, 'author_profile': 'https://Stackoverflow.com/users/13195', 'pm_score': 2, 'selected': False, 'text': '<p>The most important bit that I was missing was that <code>__call</code> exists in PHP4, but you must enable it on a per-class basis by calling <code>overload()</code>, as seen in <a href="http://us2.php.net/manual/en/function.overload.php" rel="nofollow noreferrer">php docs here</a> .\nUnfortunately, the __call() function signatures are different between PHP4 and PHP5, and there does not seem to be a way to make an implementation that will run in both.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13195/'] |
76,334 | <p>Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in <strong>C</strong> (<strong>not C++</strong>, I know that template magic is available there)?</p>
<p>I generally use <strong>GCC</strong> and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).</p>
<p>I'm looking for how to do this in <strong>GCC</strong> (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.</p>
| [{'answer_id': 76746, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 3, 'selected': False, 'text': '<p>I figured it out afterall...</p>\n\n<pre><code>#define GCD(a,b) ((a>=b)*GCD_1(a,b)+(a<b)*GCD_1(b,a))\n#define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b))))\n#define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b))))\n#define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b))))\n#define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b))))\n#define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b))))\n#define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b))))\n#define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b))))\n#define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b))))\n#define GCD_last(a,b) (a)\n\n#define LCM(a,b) (((a)*(b))/GCD(a,b))\n\n\nint main()\n{\n printf("%d, %d\\n", GCD(21,6), LCM(21,6));\n return 0;\n}\n</code></pre>\n\n<p>Note, depending on how large your integers go, you may need to include more intermediate steps (i.e. GCD_9, GCD_10, etc...).</p>\n\n<p>I hope this helps!</p>\n'}, {'answer_id': 77708, 'author': 'Kevin Loney', 'author_id': 13834, 'author_profile': 'https://Stackoverflow.com/users/13834', 'pm_score': 1, 'selected': False, 'text': '<p>I realize your only interested in a C implementation but I thought I\'d comment on C++ and template metaprogramming anyway. I\'m not completely convinced that it is possible in C++ as you need well defined initial conditions in order to terminate the recursive expansion.</p>\n\n<pre><code>template<int A, int B>\nstruct GCD {\n enum { value = GCD<B, A % B>::value };\n};\n\n/*\nBecause GCD terminates when only one of the values is zero it is impossible to define a base condition to satisfy all GCD<N, 0>::value conditions\n*/\ntemplate<>\nstruct GCD<A, 0> { // This is obviously not legal\n enum { value = A };\n};\n\nint main(void)\n{\n ::printf("gcd(%d, %d) = %d", 7, 35, GCD<7, 35>::value);\n}\n</code></pre>\n\n<p>This may be possible with C++0x however not %100 certain though.</p>\n'}, {'answer_id': 78794, 'author': 'harningt', 'author_id': 12713, 'author_profile': 'https://Stackoverflow.com/users/12713', 'pm_score': 2, 'selected': False, 'text': "<p>Partly based on Kevin's answer, here's a macro-sequence that has compile-time failure for constant-values and run-time errors otherwise.</p>\n\n<p>It could also be configured to pull in a non-compile time function if failure is not an option.</p>\n\n<pre><code>#define GCD(a,b) ( ((a) > (b)) ? ( GCD_1((a), (b)) ) : ( GCD_1((b), (a)) ) )\n\n#define GCD_1(a,b) ( ((b) == 0) ? (a) : GCD_2((b), (a) % (b) ) )\n#define GCD_2(a,b) ( ((b) == 0) ? (a) : GCD_3((b), (a) % (b) ) )\n#define GCD_3(a,b) ( ((b) == 0) ? (a) : GCD_4((b), (a) % (b) ) )\n#define GCD_4(a,b) ( ((b) == 0) ? (a) : GCD_5((b), (a) % (b) ) )\n#define GCD_5(a,b) ( ((b) == 0) ? (a) : GCD_6((b), (a) % (b) ) )\n#define GCD_6(a,b) ( ((b) == 0) ? (a) : GCD_7((b), (a) % (b) ) )\n#define GCD_7(a,b) ( ((b) == 0) ? (a) : GCD_8((b), (a) % (b) ) )\n#define GCD_8(a,b) ( ((b) == 0) ? (a) : GCD_9((b), (a) % (b) ) )\n#define GCD_9(a,b) (assert(0),-1)\n</code></pre>\n\n<p>Beware expanding this too large, even if it would terminate early, since the compiler has to fully plug in everything before even evaluating.</p>\n"}, {'answer_id': 70047263, 'author': 'thisismyhomeworkaccount', 'author_id': 17464920, 'author_profile': 'https://Stackoverflow.com/users/17464920', 'pm_score': -1, 'selected': False, 'text': '<pre><code> int gcd(int n1,int n2){\n while(n1!=n2){\n if(n1 > n2) n1 -= n2;\n else n2 -= n1;\n }\n return n1;\n}\nint lcm(int n1, int n2){\n int total =n1*n2;\n return total/gcd(n1,n2);\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12713/'] |
76,346 | <p>I just got surprised by something in TSQL. I thought that if xact_abort was on, calling something like</p>
<pre><code>raiserror('Something bad happened', 16, 1);
</code></pre>
<p>would stop execution of the stored procedure (or any batch).</p>
<p>But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that.</p>
<p>This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:</p>
<pre><code>if @somethingBadHappened
begin;
raiserror('Something bad happened', 16, 1);
return;
end;
</code></pre>
<p>The docs say this:</p>
<blockquote>
<p>When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.</p>
</blockquote>
<p>Does that mean I must be using an explicit transaction?</p>
| [{'answer_id': 76416, 'author': 'Philip Rieck', 'author_id': 12643, 'author_profile': 'https://Stackoverflow.com/users/12643', 'pm_score': 6, 'selected': False, 'text': '<p>This is By Design<sup>TM</sup>, as you can see on <a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=275308" rel="noreferrer">Connect</a> by the SQL Server team\'s response to a similar question:</p>\n\n<blockquote>\n <p>Thank you for your feedback. By design, the XACT_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server. </p>\n</blockquote>\n\n<p>Yes, this is a bit of an issue for some who hoped <code>RAISERROR</code> with a high severity (like <code>16</code>) would be the same as an SQL execution error - it\'s not.</p>\n\n<p>Your workaround is just about what you need to do, and using an explicit transaction doesn\'t have any effect on the behavior you want to change.</p>\n'}, {'answer_id': 77140, 'author': 'ninegrid', 'author_id': 13661, 'author_profile': 'https://Stackoverflow.com/users/13661', 'pm_score': 5, 'selected': False, 'text': '<p>If you use a try/catch block a raiserror error number with severity 11-19 will cause execution to jump to the catch block.</p>\n\n<p>Any severity above 16 is a system error. To demonstrate the following code sets up a try/catch block and executes a stored procedure that we assume will fail:</p>\n\n<p>assume we have a table [dbo].[Errors] to hold errors\nassume we have a stored procedure [dbo].[AssumeThisFails] which will fail when we execute it</p>\n\n<pre><code>-- first lets build a temporary table to hold errors\nif (object_id(\'tempdb..#RAISERRORS\') is null)\n create table #RAISERRORS (ErrorNumber int, ErrorMessage varchar(400), ErrorSeverity int, ErrorState int, ErrorLine int, ErrorProcedure varchar(128));\n\n-- this will determine if the transaction level of the query to programatically determine if we need to begin a new transaction or create a save point to rollback to\ndeclare @tc as int;\nset @tc = @@trancount;\nif (@tc = 0)\n begin transaction;\nelse\n save transaction myTransaction;\n\n-- the code in the try block will be executed\nbegin try\n declare @return_value = \'0\';\n set @return_value = \'0\';\n declare\n @ErrorNumber as int,\n @ErrorMessage as varchar(400),\n @ErrorSeverity as int,\n @ErrorState as int,\n @ErrorLine as int,\n @ErrorProcedure as varchar(128);\n\n\n -- assume that this procedure fails...\n exec @return_value = [dbo].[AssumeThisFails]\n if (@return_value <> 0)\n raiserror(\'This is my error message\', 17, 1);\n\n -- the error severity of 17 will be considered a system error execution of this query will skip the following statements and resume at the begin catch block\n if (@tc = 0)\n commit transaction;\n return(0);\nend try\n\n\n-- the code in the catch block will be executed on raiserror("message", 17, 1)\nbegin catch\n select\n @ErrorNumber = ERROR_NUMBER(),\n @ErrorMessage = ERROR_MESSAGE(),\n @ErrorSeverity = ERROR_SEVERITY(),\n @ErrorState = ERROR_STATE(),\n @ErrorLine = ERROR_LINE(),\n @ErrorProcedure = ERROR_PROCEDURE();\n\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n\n -- if i started the transaction\n if (@tc = 0)\n begin\n if (XACT_STATE() <> 0)\n begin\n select * from #RAISERRORS;\n rollback transaction;\n insert into [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n select * from #RAISERRORS;\n insert [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n return(1);\n end\n end\n -- if i didn\'t start the transaction\n if (XACT_STATE() = 1)\n begin\n rollback transaction myTransaction;\n if (object_id(\'tempdb..#RAISERRORS\') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(2); \n end\n else if (XACT_STATE() = -1)\n begin\n rollback transaction;\n if (object_id(\'tempdb..#RAISERRORS\') is not null)\n insert #RAISERRORS (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)\n values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);\n else\n raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);\n return(3);\n end\n end catch\nend\n</code></pre>\n'}, {'answer_id': 5991091, 'author': 'piyush', 'author_id': 752253, 'author_profile': 'https://Stackoverflow.com/users/752253', 'pm_score': 5, 'selected': False, 'text': "<p>Use <code>RETURN</code> immediately after <code>RAISERROR()</code> and it'll not execute the procedure further.</p>\n"}, {'answer_id': 18222673, 'author': 'Möoz', 'author_id': 1377865, 'author_profile': 'https://Stackoverflow.com/users/1377865', 'pm_score': 4, 'selected': False, 'text': '<p>As pointed out on the docs for <a href="https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql" rel="nofollow noreferrer"><code>SET XACT_ABORT</code></a>, the <code>THROW</code> statement should be used instead of <code>RAISERROR</code>.</p>\n\n<p>The two behave <a href="https://learn.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql" rel="nofollow noreferrer">slightly differently</a>. But when <code>XACT_ABORT</code> is set to ON, then you should always use the <code>THROW</code> command.</p>\n'}, {'answer_id': 68637587, 'author': 'Golden Lion', 'author_id': 4001177, 'author_profile': 'https://Stackoverflow.com/users/4001177', 'pm_score': 0, 'selected': False, 'text': "<p>microsoft suggests using throw instead of raiserror. Use XACT_State to determine commit or rollback for the try catch block</p>\n<pre><code>set XACT_ABORT ON;\n\nBEGIN TRY\n BEGIN TRAN;\n \n insert into customers values('Mark','Davis','[email protected]', '55909090');\n insert into customer values('Zack','Roberts','[email protected]','555919191');\n COMMIT TRAN;\n END TRY\n\nBEGIN CATCH\n IF XACT_STATE()=-1\n ROLLBACK TRAN;\n IF XACT_STATE()=1\n COMMIT TRAN;\n SELECT ERROR_MESSAGE() AS error_message\nEND CATCH\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1219/'] |
76,349 | <p>I have VS2005 and I am currently trying to debug an ASP.net web application. I want to change some code around in the code behind file, but every time I stop at a break point and try to edit something I get the following error message: "Changes are not allowed when the debugger has been attached to an already running process or the code being debugged is optimized."</p>
<p>I'm pretty sure I have all the "Edit and Continue" options enabled. Any suggestions?</p>
| [{'answer_id': 76372, 'author': 'user13276', 'author_id': 13276, 'author_profile': 'https://Stackoverflow.com/users/13276', 'pm_score': 4, 'selected': True, 'text': "<p>The application is actually running off of a compiled version of your code. If you modify it it will have to recompile it in order for your changes to work, which means that it will need to swap out the running version for the new compiled version. This is a pretty hard problem - which is why I think Microsoft has made it impossible to do. It's more to protect you from THINKING some changes were made when they really weren't.</p>\n"}, {'answer_id': 76414, 'author': 'Jarrett Meyer', 'author_id': 5834, 'author_profile': 'https://Stackoverflow.com/users/5834', 'pm_score': 1, 'selected': False, 'text': '<p>You are allowed to make changes to the <code>*.aspx</code> file while it runs, and you can hit refresh on your web instance to see those changes immediately. However, you cannot make changes to the <code>*.cs/*.vb</code> or <code>*.designer.cs/*.designer.vb</code> files while the program runs.</p>\n'}, {'answer_id': 76791, 'author': 'Chris Bilson', 'author_id': 12934, 'author_profile': 'https://Stackoverflow.com/users/12934', 'pm_score': 4, 'selected': False, 'text': '<p>This may seem counter-intuitive, but turn edit and continue off. </p>\n\n<p>There might be another "allow me to edit read-only files" or "allow me to edit even when I am debugging...no really!" setting somewhere, but I don\'t have 2005 to look at to check. </p>\n\n<p>In 2008, turn off edit and continue and you can edit while it\'s running (but those changes aren\'t appplied.)</p>\n\n<p>If you actually want to use edit and continue, you also have to enable it for the project, on the web tab of the project settings.</p>\n'}, {'answer_id': 255059, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 2, 'selected': False, 'text': "<p>For Asp.net it is possible to think of two types of 'edit and continue'. </p>\n\n<p>One is a classic edit and refresh the browser. This works because the browser refresh recompiles everything except precompiled code behind files. This is not referred to as Edit and Continue, though in practice it provides a similar effect. In this mode you cannot change code behind files, because they were precompiled and deployed, but you can change just about anything else.</p>\n\n<p>Another mode allows you to change precompiled code behind files but nothing else ... (this is the mode Chris Bilson mentions which needs to be set on the project properties for ASP.Net). In this case you are using the Edit and Continue feature of the debugger, which knows preciously little about ASP.net. The debugger just sees a loaded .Net assembly and can modify it when stopped in the debugger because there is a project in the solution that claims to know how to build it. In this case you are prevented from modifying things that would otherwise mess up the debugging session. This method however is the only way to change the code while it is running rather than requiring a browser refresh.</p>\n"}, {'answer_id': 2826088, 'author': 'abc', 'author_id': 340180, 'author_profile': 'https://Stackoverflow.com/users/340180', 'pm_score': -1, 'selected': False, 'text': '<p>Check that you are not in release mode.\nIn release mode you cannot edit your code while debugging. Just change mode to Debug</p>\n'}, {'answer_id': 3018600, 'author': 'Rob', 'author_id': 363987, 'author_profile': 'https://Stackoverflow.com/users/363987', 'pm_score': 1, 'selected': False, 'text': '<p>I search for this on Visual Studio 2008 WAP (Web Application Project) and it took me two days to find the solution, so here it is in the hopes it helps somebody else:</p>\n\n<p>There are two locations that have to be checked, one it under tools-options-debugging-Edit And Continue-Enable Edit And Continue, the other is right click project-properties-Web-Enable Edit And Continue</p>\n'}, {'answer_id': 3856333, 'author': 'user279521', 'author_id': 279521, 'author_profile': 'https://Stackoverflow.com/users/279521', 'pm_score': 0, 'selected': False, 'text': '<p>For the record, I had a similar problem with VS 2008 and a different solution resolved the problem for me. <a href="https://stackoverflow.com/questions/2781060/editing-code-in-visual-studio-2008-in-debug-mode">Editing code in Visual Studio 2008 in debug mode</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13556/'] |
76,350 | <p>We are using PowerDesigner at work for database modelling. But there is a hell of a price tag on that piece of software. And frankly, all I use is physical diagrams for MS SQL, which is about 1% of what PD knows.</p>
<p>Are there any good alternatives? I know about Visio and MS SQL Diagrams, but looking for other options.</p>
| [{'answer_id': 76572, 'author': 'digiguru', 'author_id': 5055, 'author_profile': 'https://Stackoverflow.com/users/5055', 'pm_score': 2, 'selected': True, 'text': "<p>I just use SQL Server using the diagrams folder. The designer is pretty simple to use, and can be used to generate tables fairly quickly. Considering it's free with the software, I don't see the issue.</p>\n"}, {'answer_id': 76653, 'author': 'SarekOfVulcan', 'author_id': 2531, 'author_profile': 'https://Stackoverflow.com/users/2531', 'pm_score': 0, 'selected': False, 'text': '<p>You might want to look at <a href="https://www.xcase.com/demo.php" rel="nofollow noreferrer">https://www.xcase.com/demo.php</a>. It\'s not free, but it\'s quite a bit cheaper than PowerDesigner, as far as I can tell. I\'ve used earlier versions, but lately I\'ve had easy access to Visio, so have continued with that instead of investing in xCase.</p>\n'}, {'answer_id': 81330, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': 0, 'selected': False, 'text': "<p>The version of Visio that comes with VS Enterprise Architect has a forward-engineer feature that will generate SQL. There is also a type library for the modelling engine, but (on older versions at least) it won't extract certain items such as comments. However, the generated SQL has the comments in a fairly simple structure that does facilitate parsing the generated SQL.</p>\n\n<p>You can get older versions of VS enterprise architect on E-bay for not very much money (I think mine cost about £250).</p>\n\n<p>One caveat for reverse-engineers is that all pre-VS2005 visio DB modelling engines will not play nicely with the SQL Server 2005 native client. You need to either script out the database and re-load it on a SQL2000 server (dealing with SQL2005 specific features such as schemas is left as an exercise for the reader) or get a more recent version.</p>\n"}, {'answer_id': 141646, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Well there's another alternative. Use it for more than just making tables! Exploit it, get your money's worth. You've already paid for it, you could drop the maintenance and just use it as-is. Anyways, something to ponder.</p>\n"}, {'answer_id': 141679, 'author': 'Huuuze', 'author_id': 10040, 'author_profile': 'https://Stackoverflow.com/users/10040', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://www.sqlpower.ca/page/architect" rel="noreferrer">Power*Architect</a> is the way to go. It\'s free, open source, and does a really great job helping you build your ERDs. Plus, it works on Windows, Linux, and OSX.</p>\n'}, {'answer_id': 3474842, 'author': 'Flaunt', 'author_id': 419301, 'author_profile': 'https://Stackoverflow.com/users/419301', 'pm_score': 2, 'selected': False, 'text': '<p>Open System Architect: www.codebydesign.com - it does job for me perfect</p>\n'}, {'answer_id': 3578795, 'author': 'J. Coughlin', 'author_id': 432262, 'author_profile': 'https://Stackoverflow.com/users/432262', 'pm_score': 1, 'selected': False, 'text': '<p>SourceForge.net Druid project</p>\n\n<p>Has a templating engine to produce DDL or what ever you like.\nHas the ability to have multiple diagrams in one model.\nOnly does physical data model.\nIt is free and has source available.\nIt is a java based tool so it will run on Unix or Windows.</p>\n'}, {'answer_id': 3999554, 'author': 'Brian Taylor', 'author_id': 484516, 'author_profile': 'https://Stackoverflow.com/users/484516', 'pm_score': 2, 'selected': False, 'text': '<p>Check out Sparx Enterprise Architect also.</p>\n'}, {'answer_id': 6718379, 'author': 'mixtly87', 'author_id': 824052, 'author_profile': 'https://Stackoverflow.com/users/824052', 'pm_score': 1, 'selected': False, 'text': '<p>How about MagicDraw? It is a very powerfull tool, but I think it as expensive as PowerDesigner, not sure.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/76350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11063/'] |
Subsets and Splits