input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to make Twitter Bootstrap menu dropdown on hover rather than click <p>I'd like to have my Bootstrap menu automatically drop down on hover, rather than having to click the menu title. I'd also like to lose the little arrows next to the menu titles.</p>
<p>I created a pure on hover dropdown menu based on the latest (v2.0.2) Bootstrap framework that has support for multiple submenus and thought I'd post it for future users:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } .dropdown-menu .sub-menu { left: 100%; position: absolute; top: 0; visibility: hidden; margin-top: -1px; } .dropdown-menu li:hover .sub-menu { visibility: visible; } .dropdown:hover .dropdown-menu { display: block; } .nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu { margin-top: 0; } .navbar .sub-menu:before { border-bottom: 7px solid transparent; border-left: none; border-right: 7px solid rgba(0, 0, 0, 0.2); border-top: 7px solid transparent; left: -7px; top: 10px; } .navbar .sub-menu:after { border-top: 6px solid transparent; border-left: none; border-right: 6px solid #fff; border-bottom: 6px solid transparent; left: 10px; top: 11px; left: -6px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="navbar navbar-fixed-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container-fluid"&gt; &lt;a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a href="#" class="brand"&gt;Project name&lt;/a&gt; &lt;div class="nav-collapse"&gt; &lt;ul class="nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a data-toggle="dropdown" class="dropdown-toggle" href="#"&gt;Dropdown &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt; &lt;a href="#"&gt;2-level Dropdown &lt;i class="icon-arrow-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;ul class="dropdown-menu sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li class="nav-header"&gt;Nav header&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li class="nav-header"&gt;Nav header&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;form action="" class="navbar-search pull-left"&gt; &lt;input type="text" placeholder="Search" class="search-query span2"&gt; &lt;/form&gt; &lt;ul class="nav pull-right"&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li class="divider-vertical"&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a class="#" href="#"&gt;Menu&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- /.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr&gt; &lt;ul class="nav nav-pills"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Regular link&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" data-toggle="dropdown" class="dropdown-toggle"&gt;Dropdown &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu" id="menu1"&gt; &lt;li&gt; &lt;a href="#"&gt;2-level Menu &lt;i class="icon-arrow-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;ul class="dropdown-menu sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li class="nav-header"&gt;Nav header&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#"&gt;Menu&lt;/a&gt; &lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#"&gt;Menu&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/2Smgv/3100/" rel="noreferrer">Demo</a></p>
{ "question_id": 8878033, "question_date": "2012-01-16T09:36:40.593Z", "question_score": 1242, "tags": "css|drop-down-menu|twitter-bootstrap", "answer_id": 10143018, "answer_date": "2012-04-13T14:46:01.720Z", "answer_score": 616 }
Please answer the following Stack Overflow question: Title: Which version of PostgreSQL am I running? <p>I'm in a corporate environment (running Debian Linux) and didn't install it myself. I access the databases using Navicat or phpPgAdmin (if that helps). I also don't have shell access to the server running the database.</p>
<p>Run this query from PostgreSQL:</p> <pre><code>SELECT version(); </code></pre>
{ "question_id": 13733719, "question_date": "2012-12-05T22:34:16.760Z", "question_score": 1240, "tags": "linux|database|postgresql", "answer_id": 13733856, "answer_date": "2012-12-05T22:42:43.690Z", "answer_score": 1931 }
Please answer the following Stack Overflow question: Title: How to remove the space between inline/inline-block elements? <p>There will be a 4 pixel wide space between these <code>span</code> elements:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>span { display: inline-block; width: 100px; background-color: palevioletred; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt; &lt;span&gt; Foo &lt;/span&gt; &lt;span&gt; Bar &lt;/span&gt; &lt;/p&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/dGHFV/" rel="noreferrer">Fiddle Demo</a></p> <p>I understand that I could get rid of that space by removing the white-space between the <code>span</code> elements in the HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; &lt;span&gt; Foo &lt;/span&gt;&lt;span&gt; Bar &lt;/span&gt; &lt;/p&gt; </code></pre> <p>I'm Looking for a CSS solution that doesn't involve:</p> <ul> <li>Altering the HTML.</li> <li>JavaScript.</li> </ul>
<p>Alternatively, you <a href="http://caniuse.com/flexbox" rel="noreferrer">should now use flexbox</a> to achieve many of the layouts that you may previously have used inline-block for: <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">https://css-tricks.com/snippets/css/a-guide-to-flexbox/</a></p> <hr /> <p>Since this answer has become rather popular, I'm rewriting it significantly.</p> <p>Let's not forget the actual question that was asked:</p> <blockquote> <p>How to remove the space between <strong>inline-block elements</strong>? I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with. <strong>Can this issue be solved with CSS alone?</strong></p> </blockquote> <p>It <em>is</em> possible to solve this problem with CSS alone, but there are no <em>completely</em> robust CSS fixes.</p> <p>The solution I had in my initial answer was to add <code>font-size: 0</code> to the parent element, and then declare a sensible <code>font-size</code> on the children.</p> <p><a href="http://jsfiddle.net/thirtydot/dGHFV/1361/" rel="noreferrer">http://jsfiddle.net/thirtydot/dGHFV/1361/</a></p> <p>This works in recent versions of all modern browsers. It works in IE8. It does not work in Safari 5, but it <em>does</em> work in Safari 6. Safari 5 is nearly a dead browser (<a href="http://gs.statcounter.com/#desktop-browser_version_partially_combined-ww-monthly-201408-201508" rel="noreferrer">0.33%, August 2015</a>).</p> <p>Most of the possible issues with relative font sizes are not complicated to fix.</p> <p>However, while this is a reasonable solution if you <em>specifically need</em> a CSS only fix, it's not what I recommend if you're free to change your HTML (as most of us are).</p> <hr /> <p>This is what I, as a reasonably experienced web developer, actually do to solve this problem:</p> <pre><code>&lt;p&gt; &lt;span&gt;Foo&lt;/span&gt;&lt;span&gt;Bar&lt;/span&gt; &lt;/p&gt; </code></pre> <p>Yes, that's right. I remove the whitespace in the HTML between the inline-block elements.</p> <p>It's easy. It's simple. It works everywhere. It's the pragmatic solution.</p> <p>You do sometimes have to carefully consider where whitespace will come from. <em>Will appending another element with JavaScript add whitespace?</em> No, not if you do it properly.</p> <p>Let's go on a magical journey of different ways to remove the whitespace, with some new HTML:</p> <pre><code>&lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> <ul> <li><p>You can do this, as I usually do:</p> <pre><code> &lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt;&lt;li&gt;Item 2&lt;/li&gt;&lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> </li> </ul> <p><a href="http://jsfiddle.net/thirtydot/dGHFV/1362/" rel="noreferrer">http://jsfiddle.net/thirtydot/dGHFV/1362/</a></p> <ul> <li><p>Or, this:</p> <pre><code> &lt;ul&gt; &lt;li&gt;Item 1&lt;/li &gt;&lt;li&gt;Item 2&lt;/li &gt;&lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> </li> <li><p>Or, use comments:</p> <pre><code> &lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;Item 2&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> </li> <li><p>Or, if you are using using PHP or similar:</p> <pre><code> &lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt;&lt;? ?&gt;&lt;li&gt;Item 2&lt;/li&gt;&lt;? ?&gt;&lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> </li> <li><p>Or, <a href="http://validator.w3.org/check?uri=http%3A%2F%2Fjsbin.com%2FOMoXUHO%2F1%2F&amp;charset=%28detect+automatically%29&amp;doctype=Inline&amp;group=0" rel="noreferrer">you can</a> even skip <a href="http://developers.whatwg.org/syntax.html#optional-tags" rel="noreferrer">certain</a> closing tags entirely (all browsers are fine with this):</p> <pre><code> &lt;ul&gt; &lt;li&gt;Item 1 &lt;li&gt;Item 2 &lt;li&gt;Item 3 &lt;/ul&gt; </code></pre> </li> </ul> <p>Now that I've gone and bored you to death with &quot;one thousand different ways to remove whitespace, by thirtydot&quot;, hopefully you've forgotten all about <code>font-size: 0</code>.</p>
{ "question_id": 5078239, "question_date": "2011-02-22T12:41:14.213Z", "question_score": 1240, "tags": "html|css|flexbox", "answer_id": 5078297, "answer_date": "2011-02-22T12:47:40.780Z", "answer_score": 1159 }
Please answer the following Stack Overflow question: Title: Group by in LINQ <p>Let's suppose if we have a class like:</p> <pre><code>class Person { internal int PersonID; internal string car; } </code></pre> <p>I have a list of this class: <code>List&lt;Person&gt; persons;</code></p> <p>And this list can have multiple instances with same <code>PersonID</code>s, for example: </p> <pre><code>persons[0] = new Person { PersonID = 1, car = "Ferrari" }; persons[1] = new Person { PersonID = 1, car = "BMW" }; persons[2] = new Person { PersonID = 2, car = "Audi" }; </code></pre> <p>Is there a way I can group by <code>PersonID</code> and get the list of all the cars he has? </p> <p>For example, the expected result would be </p> <pre><code>class Result { int PersonID; List&lt;string&gt; cars; } </code></pre> <p>So after grouping, I would get: </p> <pre><code>results[0].PersonID = 1; List&lt;string&gt; cars = results[0].cars; result[1].PersonID = 2; List&lt;string&gt; cars = result[1].cars; </code></pre> <p>From what I have done so far: </p> <pre><code>var results = from p in persons group p by p.PersonID into g select new { PersonID = g.Key, // this is where I am not sure what to do </code></pre> <p>Could someone please point me in the right direction? </p>
<p>Absolutely - you basically want:</p> <pre><code>var results = from p in persons group p.car by p.PersonId into g select new { PersonId = g.Key, Cars = g.ToList() }; </code></pre> <p>Or as a non-query expression:</p> <pre><code>var results = persons.GroupBy( p =&gt; p.PersonId, p =&gt; p.car, (key, g) =&gt; new { PersonId = key, Cars = g.ToList() }); </code></pre> <p>Basically the contents of the group (when viewed as an <code>IEnumerable&lt;T&gt;</code>) is a sequence of whatever values were in the projection (<code>p.car</code> in this case) present for the given key.</p> <p>For more on how <code>GroupBy</code> works, see my <a href="http://codeblog.jonskeet.uk/2011/01/01/reimplementing-linq-to-objects-part-21-groupby/" rel="noreferrer">Edulinq post on the topic</a>.</p> <p>(I've renamed <code>PersonID</code> to <code>PersonId</code> in the above, to follow <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions" rel="noreferrer">.NET naming conventions</a>.)</p> <p>Alternatively, you could use a <code>Lookup</code>:</p> <pre><code>var carsByPersonId = persons.ToLookup(p =&gt; p.PersonId, p =&gt; p.car); </code></pre> <p>You can then get the cars for each person very easily:</p> <pre><code>// This will be an empty sequence for any personId not in the lookup var carsForPerson = carsByPersonId[personId]; </code></pre>
{ "question_id": 7325278, "question_date": "2011-09-06T19:44:20.537Z", "question_score": 1239, "tags": "c#|linq|group-by", "answer_id": 7325306, "answer_date": "2011-09-06T19:46:13.043Z", "answer_score": 1992 }
Please answer the following Stack Overflow question: Title: Dealing with "java.lang.OutOfMemoryError: PermGen space" error <p>Recently I ran into this error in my web application:</p> <blockquote> <p>java.lang.OutOfMemoryError: PermGen space</p> </blockquote> <p>It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times.</p> <p>What causes it and what can be done to avoid it? How do I fix the problem?</p>
<p>The solution was to add these flags to JVM command line when Tomcat is started:</p> <pre><code>-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled </code></pre> <p>You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the &quot;Java&quot; tab, add the arguments to the &quot;Java Options&quot; box. Click &quot;OK&quot; and then restart the service.</p> <p>If you get an error <em>the specified service does not exist as an installed service</em> you should run:</p> <pre><code>tomcat6w //ES//servicename </code></pre> <p>where <em><strong>servicename</strong></em> is the name of the server as viewed in services.msc</p> <p>Source: orx's comment on <a href="https://web.archive.org/web/20160124133922/http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang" rel="noreferrer">Eric's Agile Answers</a>.</p>
{ "question_id": 88235, "question_date": "2008-09-17T22:13:48.277Z", "question_score": 1239, "tags": "exception|memory-leaks|out-of-memory|java-6|permgen", "answer_id": 88262, "answer_date": "2008-09-17T22:17:16.973Z", "answer_score": 571 }
Please answer the following Stack Overflow question: Title: How do I use reflection to call a generic method? <p>What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?</p> <p>Consider the following sample code - inside the <code>Example()</code> method, what's the most concise way to invoke <code>GenericMethod&lt;T&gt;()</code> using the <code>Type</code> stored in the <code>myType</code> variable?</p> <pre><code>public class Sample { public void Example(string typeName) { Type myType = FindType(typeName); // What goes here to call GenericMethod&lt;T&gt;()? GenericMethod&lt;myType&gt;(); // This doesn't work // What changes to call StaticMethod&lt;T&gt;()? Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work } public void GenericMethod&lt;T&gt;() { // ... } public static void StaticMethod&lt;T&gt;() { //... } } </code></pre>
<p>You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx" rel="noreferrer">MakeGenericMethod</a>:</p> <pre><code>MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null); </code></pre> <p>For a static method, pass <code>null</code> as the first argument to <code>Invoke</code>. That's nothing to do with generic methods - it's just normal reflection.</p> <p>As noted, a lot of this is simpler as of C# 4 using <code>dynamic</code> - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.</p>
{ "question_id": 232535, "question_date": "2008-10-24T05:17:35.217Z", "question_score": 1239, "tags": "c#|.net|generics|reflection", "answer_id": 232621, "answer_date": "2008-10-24T06:13:34.167Z", "answer_score": 1300 }
Please answer the following Stack Overflow question: Title: Secure hash and salt for PHP passwords <p>It is currently said that MD5 is partially unsafe. Taking this into consideration, I'd like to know which mechanism to use for password protection.</p> <p>This question, <a href="https://stackoverflow.com/questions/348109/is-double-hashing-a-password-less-secure-than-just-hashing-it-once">Is “double hashing” a password less secure than just hashing it once?</a> suggests that hashing multiple times may be a good idea, whereas <a href="https://stackoverflow.com/questions/55862/how-to-implement-password-protection-for-individual-files#55904">How to implement password protection for individual files?</a> suggests using salt.</p> <p>I'm using PHP. I want a safe and fast password encryption system. Hashing a password a million times may be safer, but also slower. How to achieve a good balance between speed and safety? Also, I'd prefer the result to have a constant number of characters.</p> <ol> <li>The hashing mechanism must be available in PHP</li> <li>It must be safe</li> <li>It can use salt (in this case, are all salts equally good? Is there any way to generate good salts?)</li> </ol> <p>Also, should I store two fields in the database (one using MD5 and another one using SHA, for example)? Would it make it safer or unsafer?</p> <p>In case I wasn't clear enough, I want to know which hashing function(s) to use and how to pick a good salt in order to have a safe and fast password protection mechanism.</p> <p><em>Related questions that don't quite cover my question:</em></p> <p><a href="https://stackoverflow.com/questions/157998/whats-the-difference-between-sha-and-md5-in-php">What's the difference between SHA and MD5 in PHP</a><br> <a href="https://stackoverflow.com/questions/30946/simple-password-encryption">Simple Password Encryption</a><br> <a href="https://stackoverflow.com/questions/198803/secure-methods-of-storing-keys-passwords-for-asp-net">Secure methods of storing keys, passwords for asp.net</a><br> <a href="https://stackoverflow.com/questions/205153/how-would-you-implement-salted-passwords-in-tomcat-5-5">How would you implement salted passwords in Tomcat 5.5</a></p>
<blockquote> <p><strong>DISCLAIMER</strong>: This answer was written in 2008.</p> <p>Since then, PHP has given us <a href="http://php.net/manual/en/function.password-hash.php" rel="noreferrer"><code>password_hash</code></a> and <a href="http://php.net/manual/en/function.password-verify.php" rel="noreferrer"><code>password_verify</code></a> and, since their introduction, they are the recommended password hashing &amp; checking method.</p> <p>The theory of the answer is still a good read though.</p> </blockquote> <h2>TL;DR</h2> <h3>Don'ts</h3> <ul> <li>Don't limit what characters users can enter for passwords. Only idiots do this.</li> <li>Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.</li> <li>Don't strip or escape HTML and special characters in the password.</li> <li>Never store your user's password in plain-text.</li> <li>Never email a password to your user <em>except when they have lost theirs, and you sent a temporary one.</em></li> <li>Never, ever log passwords in any manner.</li> <li>Never hash passwords with <a href="http://arstechnica.com/security/2012/12/oh-great-new-attack-makes-some-password-cracking-faster-easier-than-ever/" rel="noreferrer">SHA1</a> or MD5 or even SHA256! <a href="http://securityledger.com/new-25-gpu-monster-devours-passwords-in-seconds/" rel="noreferrer">Modern crackers</a> can exceed 60 and 180 billion hashes/second (respectively).</li> <li>Don't mix <a href="http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html" rel="noreferrer">bcrypt and with the <em>raw</em> output of hash()</a>, either use hex output or base64_encode it. (This applies to any input that may have a rogue <code>\0</code> in it, which can seriously weaken security.)</li> </ul> <h3>Dos</h3> <ul> <li>Use scrypt when you can; bcrypt if you cannot.</li> <li>Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.</li> <li>Reset everyone's passwords when the database is compromised.</li> <li>Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)</li> </ul> <h2>Why hash passwords anyway?</h2> <p>The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.</p> <p>Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at <em>least</em> lock the system down, if not change every password in the database.</p> <p>Jeremiah Grossman, CTO of Whitehat Security, <a href="https://www.whitehatsec.com/blog/cracking-aes-256-dmgs-and-epic-self-pwnage/" rel="noreferrer">stated on White Hat Security blog</a> after a recent password recovery that required brute-force breaking of his password protection:</p> <blockquote> <p>Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. <em>I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity.</em> This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.</p> </blockquote> <p>(Emphasis mine.)</p> <h2>What makes a <em>good</em> password anyway?</h2> <p><a href="http://xkcd.com/936/" rel="noreferrer">Entropy</a>. (Not that I fully subscribe to Randall's viewpoint.)</p> <p>In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!</p> <p>Password entropy is <a href="https://ritcyberselfdefense.wordpress.com/2011/09/24/how-to-calculate-password-entropy/" rel="noreferrer">approximated</a> easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.</p> <p>There's a longer discussion of password entropy on the <a href="https://crypto.stackexchange.com/questions/374/how-should-i-calculate-the-entropy-of-a-password">Crypto StackExchange</a> site. A good Google search will also turn up a lot of results.</p> <p>In the comments I talked with @popnoodles, who pointed out that <em>enforcing</em> a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.</p> <p>So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.</p> <h2>Best practices</h2> <p>Bcrypt and <a href="http://www.tarsnap.com/scrypt.html" rel="noreferrer">scrypt</a> are the current best practices. <a href="http://www.tarsnap.com/scrypt.html" rel="noreferrer">Scrypt</a> will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an <a href="http://rubygems.org/gems/scrypt" rel="noreferrer">scrypt gem</a> that will help you out, and Node.js now has its own <a href="https://npmjs.org/package/scrypt" rel="noreferrer">scrypt</a> package. You can use Scrypt in PHP either via the <a href="https://pecl.php.net/package/scrypt" rel="noreferrer">Scrypt</a> extension or the <a href="https://paragonie.com/book/pecl-libsodium/read/07-password-hashing.md" rel="noreferrer">Libsodium</a> extension (both are available in PECL).</p> <p>I highly suggest reading the documentation for the <a href="http://us.php.net/crypt" rel="noreferrer">crypt function</a> if you want to understand how to use bcrypt, or finding yourself a <a href="https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php/6337021#6337021">good</a> <a href="https://gist.github.com/1070401" rel="noreferrer">wrapper</a> or use something like <a href="http://www.openwall.com/phpass/" rel="noreferrer">PHPASS</a> for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.</p> <p>I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.</p> <h2>Average practices</h2> <p>I almost can't imagine this situation anymore. <a href="http://www.openwall.com/phpass/" rel="noreferrer">PHPASS</a> supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't <em>know for certain</em> that your environment supports bcrypt.</p> <p>But suppose that you cannot use bcrypt or PHPASS at all. What then?</p> <p>Try an implementation of <a href="http://www.itnewb.com/tutorial/Encrypting-Passwords-with-PHP-for-Storage-Using-the-RSA-PBKDF2-Standard" rel="noreferrer">PDKBF2</a> with the <a href="https://security.stackexchange.com/questions/3959/recommended-of-iterations-when-using-pkbdf2-sha256">maximum number of rounds</a> that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use <a href="http://php.net/hash_hmac" rel="noreferrer">hash_hmac()</a> if it is available to make the operation harder to reproduce.</p> <h2>Future Practices</h2> <p>Coming in PHP 5.5 is a <a href="http://php.net/manual/en/ref.password.php" rel="noreferrer">full password protection library</a> that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a <a href="https://github.com/ircmaxell/password_compat" rel="noreferrer">compatibility layer</a> for the coming API that is backward compatible to PHP 5.3.7.</p> <h2>Cryptography Recap &amp; Disclaimer</h2> <p>The computational power required to actually <em>crack</em> a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.</p> <p>You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users <strong>up front</strong>. If you do not, then you might even miss the fact that you were attacked until it's too late... <em>and you're liable</em>. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.</p> <p>Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.</p>
{ "question_id": 401656, "question_date": "2008-12-30T22:02:45.637Z", "question_score": 1239, "tags": "php|security|hash|passwords", "answer_id": 401684, "answer_date": "2008-12-30T22:15:09.027Z", "answer_score": 1020 }
Please answer the following Stack Overflow question: Title: How to get line count of a large file cheaply in Python? <p>How do I get a line count of a large file in the most memory- and time-efficient manner?</p> <pre><code>def file_len(filename): with open(filename) as f: for i, _ in enumerate(f): pass return i + 1 </code></pre>
<p>You can't get any better than that.</p> <p>After all, any solution will have to read the entire file, figure out how many <code>\n</code> you have, and return that result.</p> <p>Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered.</p>
{ "question_id": 845058, "question_date": "2009-05-10T10:22:05.677Z", "question_score": 1238, "tags": "python|text-files|line-count", "answer_id": 845081, "answer_date": "2009-05-10T10:37:42.677Z", "answer_score": 422 }
Please answer the following Stack Overflow question: Title: Putting a simple if-then-else statement on one line <p>I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an <code>if</code>-<code>then</code>-<code>else</code> statement so it fits on one line?</p> <p>For example:</p> <pre><code>if count == N: count = 0 else: count = N + 1 </code></pre> <p>Is there a simpler way of writing this? I mean, in Objective-C I would write this as:</p> <pre><code>count = count == N ? 0 : count + 1; </code></pre> <p>Is there something similar for Python?</p> <p><strong>Update</strong></p> <p>I know that in this instance I can use <code>count == (count + 1) % N</code>. </p> <p>I'm asking about the general syntax.</p>
<p>That's more specifically a <a href="https://docs.python.org/3.10/reference/expressions.html?highlight=ternary#conditional-expressions" rel="noreferrer">ternary operator</a> expression than an if-then, here's the python syntax</p> <pre><code>value_when_true if condition else value_when_false </code></pre> <p><strong>Better Example:</strong> (thanks <a href="https://stackoverflow.com/users/253254/joshua-burns">Mr. Burns</a>)</p> <p><code>'Yes' if fruit == 'Apple' else 'No'</code></p> <p><strong>Now with assignment and contrast with if syntax</strong></p> <pre><code>fruit = 'Apple' isApple = True if fruit == 'Apple' else False </code></pre> <p><strong>vs</strong></p> <pre><code>fruit = 'Apple' isApple = False if fruit == 'Apple' : isApple = True </code></pre>
{ "question_id": 2802726, "question_date": "2010-05-10T12:58:04.050Z", "question_score": 1237, "tags": "python|if-statement|syntax|ternary-operator", "answer_id": 2802748, "answer_date": "2010-05-10T13:00:17.493Z", "answer_score": 2301 }
Please answer the following Stack Overflow question: Title: How do I run two commands in one line in Windows CMD? <p>I want to run two commands in a Windows CMD console.</p> <p>In Linux I would do it like this</p> <pre><code>touch thisfile ; ls -lstrh </code></pre> <p>How is it done on Windows?</p>
<p>Like this on all Microsoft OSes since 2000, and still good today:</p> <pre><code>dir &amp; echo foo </code></pre> <p>If you want the second command to execute only if the first exited successfully:</p> <pre><code>dir &amp;&amp; echo foo </code></pre> <p>The single ampersand (&amp;) syntax to execute multiple commands on one line goes back to Windows XP, Windows 2000, and some earlier NT versions. (4.0 at least, according to one commenter here.)</p> <p>There are quite a few other points about this that you'll find scrolling down this page.</p> <p>Historical data follows, for those who may find it educational.</p> <p>Prior to that, the &amp;&amp; syntax was only a feature of the shell replacement 4DOS before that feature was added to the Microsoft command interpreter.</p> <p>In Windows 95, 98 and ME, you'd use the pipe character instead:</p> <pre><code>dir | echo foo </code></pre> <p>In MS-DOS 5.0 and later, through some earlier Windows and NT versions of the command interpreter, the (undocumented) command separator was character 20 (Ctrl+T) which I'll represent with ^T here.</p> <pre><code>dir ^T echo foo </code></pre>
{ "question_id": 8055371, "question_date": "2011-11-08T18:31:04.110Z", "question_score": 1237, "tags": "windows|batch-file|command-line|cmd", "answer_id": 8055390, "answer_date": "2011-11-08T18:33:22.857Z", "answer_score": 1740 }
Please answer the following Stack Overflow question: Title: How to reformat JSON in Notepad++? <p>I need Notepad++ to take a json string from this</p> <pre><code>{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"},{"value": "Close", "onclick": "CloseDoc()"}]}}} </code></pre> <p>to this...</p> <pre><code>{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }} </code></pre> <p>I looked around at all the TextFX options but couldn't find anything that worked.</p>
<blockquote> <h3>Update:</h3> <p>As of Notepad++ v7.6, use <strong>Plugin Admin</strong> to install JSTool per <a href="https://stackoverflow.com/a/56072664/1315626">this answer</a> </p> </blockquote> <p>INSTALL</p> <p>Download it from <a href="http://sourceforge.net/projects/jsminnpp/" rel="noreferrer">http://sourceforge.net/projects/jsminnpp/</a> and copy JSMinNpp.dll to plugin directory of Notepad++. Or you can just install "JSTool" from Plugin Manager in Notepad++.</p> <p>New Notepad++ install and where did PluginManager go? See <a href="https://stackoverflow.com/questions/46301700/how-to-view-plugin-manager-in-notepad">How to view Plugin Manager in Notepad++</a> </p> <pre><code>{ "menu" : { "id" : "file", "value" : "File", "popup" : { "menuitem" : [{ "value" : "New", "onclick" : "CreateNewDoc()" }, { "value" : "Open", "onclick" : "OpenDoc()" }, { "value" : "Close", "onclick" : "CloseDoc()" } ] } } } </code></pre> <p><a href="https://i.stack.imgur.com/disZy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/disZy.png" alt="enter image description here"></a> Tip: Select the code you want to reformat, then Plugins | JSTool | JSFormat.</p>
{ "question_id": 1560464, "question_date": "2009-10-13T14:06:31.320Z", "question_score": 1237, "tags": "json|parsing|notepad++", "answer_id": 5083037, "answer_date": "2011-02-22T19:40:56.767Z", "answer_score": 1623 }
Please answer the following Stack Overflow question: Title: What does the 'b' character do in front of a string literal? <p>Apparently, the following is the valid syntax:</p> <pre><code>b'The string' </code></pre> <p>I would like to know:</p> <ol> <li>What does this <code>b</code> character in front of the string mean?</li> <li>What are the effects of using it?</li> <li>What are appropriate situations to use it?</li> </ol> <p>I found a <a href="https://stackoverflow.com/q/4749442/346561">related question</a> right here on SO, but that question is about PHP though, and it states the <code>b</code> is used to indicate the string is binary, as opposed to Unicode, which was needed for code to be compatible from version of PHP &lt; 6, when migrating to PHP 6. I don't think this applies to Python.</p> <p>I did find <a href="http://docs.python.org/tutorial/introduction.html#unicode-strings" rel="noreferrer">this documentation</a> on the Python site about using a <code>u</code> character in the same syntax to specify a string as Unicode. Unfortunately, it doesn't mention the <strong>b</strong> character anywhere in that document.</p> <p>Also, just out of curiosity, are there more symbols than the <code>b</code> and <code>u</code> that do other things?</p>
<p>To quote <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="noreferrer">the Python 2.x documentation</a>:</p> <blockquote> <p>A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.</p> </blockquote> <p>The <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="noreferrer">Python 3 documentation</a> states:</p> <blockquote> <p>Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.</p> </blockquote>
{ "question_id": 6269765, "question_date": "2011-06-07T18:14:52.667Z", "question_score": 1237, "tags": "python|string|unicode|binary", "answer_id": 6269785, "answer_date": "2011-06-07T18:16:22.237Z", "answer_score": 528 }
Please answer the following Stack Overflow question: Title: Using Node.js require vs. ES6 import/export <p>In a project I am collaborating on, we have two choices on which module system we can use:</p> <ol> <li>Importing modules using <code>require</code>, and exporting using <code>module.exports</code> and <code>exports.foo</code>.</li> <li>Importing modules using ES6 <code>import</code>, and exporting using ES6 <code>export</code></li> </ol> <p>Are there any performance benefits to using one over the other? Is there anything else that we should know if we were to use ES6 modules over Node ones?</p>
<h5>Update</h5> <p>Since Node v12 (April 2019), support for ES modules is enabled by default, and since Node v15 (October 2020) it's stable (see <a href="https://nodejs.org/api/esm.html#esm_modules_ecmascript_modules" rel="noreferrer">here</a>). Files including node modules must either end in <code>.mjs</code> or the nearest <code>package.json</code> file must contain <code>&quot;type&quot;: &quot;module&quot;</code>. The <a href="https://nodejs.org/api/esm.html" rel="noreferrer">Node documentation</a> has a ton more information, also about interop between CommonJS and ES modules.</p> <p>Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.</p> <p>ES modules can be loaded dynamically via the <code>import()</code> function. Unlike <code>require</code>, this returns a promise.</p> <hr /> <h5>Previous answer</h5> <blockquote> <p>Are there any performance benefits to using one over the other?</p> </blockquote> <p>Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts <code>import</code> and <code>export</code> declaration to CommonJS (<code>require</code>/<code>module.exports</code>) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.</p> <p>There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, <a href="https://github.com/whatwg/loader" rel="noreferrer">but there is an API in development for that</a>.</p> <p>Since ES6 modules are part of the standard, I would use them.</p>
{ "question_id": 31354559, "question_date": "2015-07-11T07:19:47.117Z", "question_score": 1237, "tags": "javascript|node.js|ecmascript-6|babeljs", "answer_id": 31367852, "answer_date": "2015-07-12T12:38:45.477Z", "answer_score": 925 }
Please answer the following Stack Overflow question: Title: What is HEAD in Git? <p>You see the Git documentation saying things like</p> <blockquote> <p>The branch must be fully merged in HEAD.</p> </blockquote> <p>But what is Git <code>HEAD</code> exactly?</p>
<p>You can think of the HEAD as the "current branch". When you switch branches with <code>git checkout</code>, the HEAD revision changes to point to the tip of the new branch.</p> <p>You can see what HEAD points to by doing:</p> <pre><code>cat .git/HEAD </code></pre> <p>In my case, the output is:</p> <pre><code>$ cat .git/HEAD ref: refs/heads/master </code></pre> <p>It is possible for HEAD to refer to a specific revision that is not associated with a branch name. This situation is called a <a href="http://git-scm.com/docs/git-checkout#_detached_head" rel="noreferrer">detached HEAD</a>.</p>
{ "question_id": 2304087, "question_date": "2010-02-20T22:58:13.113Z", "question_score": 1237, "tags": "git", "answer_id": 2304106, "answer_date": "2010-02-20T23:00:49.553Z", "answer_score": 926 }
Please answer the following Stack Overflow question: Title: How do I copy a version of a single file from one Git branch to another? <p>I've got two branches that are fully merged together.</p> <p>However, after the merge is done, I realise that one file has been messed up by the merge (someone else did an auto-format, gah), and it would just be easier to change to the new version in the other branch, and then reinsert my one line change after bringing it over into my branch.</p> <p>So what's the easiest way in Git to do this?</p>
<p>Run this from the branch where you want the file to end up:</p> <pre><code>git checkout otherbranch myfile.txt </code></pre> <p>General formulas:</p> <pre><code>git checkout &lt;commit_hash&gt; &lt;relative_path_to_file_or_dir&gt; git checkout &lt;remote_name&gt;/&lt;branch_name&gt; &lt;file_or_dir&gt; </code></pre> <p>Some notes (from comments):</p> <ul> <li>Using the commit hash, you can pull files from any commit</li> <li>This works for files and directories</li> <li>Overwrites the file <code>myfile.txt</code> and <code>mydir</code></li> <li>Wildcards don't work, but relative paths do</li> <li>Multiple paths can be specified</li> </ul> <p>An alternative:</p> <pre><code>git show commit_id:path/to/file &gt; path/to/file </code></pre>
{ "question_id": 307579, "question_date": "2008-11-21T01:50:37.240Z", "question_score": 1237, "tags": "git|git-branch|branching-and-merging", "answer_id": 307872, "answer_date": "2008-11-21T04:31:21.363Z", "answer_score": 2067 }
Please answer the following Stack Overflow question: Title: Call one constructor from another <p>I have two constructors which feed values to readonly fields.</p> <pre><code>public class Sample { public Sample(string theIntAsString) { int i = int.Parse(theIntAsString); _intField = i; } public Sample(int theInt) =&gt; _intField = theInt; public int IntProperty =&gt; _intField; private readonly int _intField; } </code></pre> <p>One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.</p> <p>Now here's the catch:</p> <ol> <li>I don't want to duplicate the setting code. In this case, just one field is set but of course there may well be more than one.</li> <li>To make the fields readonly, I need to set them from the constructor, so I can't "extract" the shared code to a utility function.</li> <li>I don't know how to call one constructor from another.</li> </ol> <p>Any ideas?</p>
<p>Like this:</p> <pre><code>public Sample(string str) : this(int.Parse(str)) { } </code></pre>
{ "question_id": 4009013, "question_date": "2010-10-24T16:06:31.243Z", "question_score": 1236, "tags": "c#|constructor", "answer_id": 4009032, "answer_date": "2010-10-24T16:09:55.380Z", "answer_score": 1963 }
Please answer the following Stack Overflow question: Title: How to get the ASCII value of a character <p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="noreferrer">ASCII</a> value of a character as an <code>int</code> in Python?</p>
<p>From <a href="http://mail.python.org/pipermail/python-win32/2005-April/003100.html" rel="noreferrer">here</a>:</p> <blockquote> <p>The function <strong><code>ord()</code></strong> gets the int value of the char. And in case you want to convert back after playing with the number, function <strong><code>chr()</code></strong> does the trick.</p> </blockquote> <pre><code>&gt;&gt;&gt; ord('a') 97 &gt;&gt;&gt; chr(97) 'a' &gt;&gt;&gt; chr(ord('a') + 3) 'd' &gt;&gt;&gt; </code></pre> <p>In Python 2, there was also the <code>unichr</code> function, returning the <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> character whose ordinal is the <code>unichr</code> argument:</p> <pre><code>&gt;&gt;&gt; unichr(97) u'a' &gt;&gt;&gt; unichr(1234) u'\u04d2' </code></pre> <p>In Python 3 you can use <code>chr</code> instead of <code>unichr</code>.</p> <hr> <p><a href="https://docs.python.org/3/library/functions.html#ord" rel="noreferrer">ord() - Python 3.6.5rc1 documentation</a></p> <p><a href="https://docs.python.org/2/library/functions.html#ord" rel="noreferrer">ord() - Python 2.7.14 documentation</a></p>
{ "question_id": 227459, "question_date": "2008-10-22T20:39:57.053Z", "question_score": 1235, "tags": "python|ascii", "answer_id": 227472, "answer_date": "2008-10-22T20:43:04.443Z", "answer_score": 1632 }
Please answer the following Stack Overflow question: Title: Are HTTPS URLs encrypted? <p>Are all URLs encrypted when using TLS/SSL (HTTPS) encryption? I would like to know because I want all URL data to be hidden when using TLS/SSL (HTTPS).</p> <p>If TLS/SSL gives you total URL encryption then I don't have to worry about hiding confidential information from URLs.</p>
<p>Yes, the SSL connection is between the TCP layer and the HTTP layer. The client and server first establish a secure encrypted TCP connection (via the SSL/TLS protocol) and then the client will send the HTTP request (GET, POST, DELETE...) over that encrypted TCP connection.</p> <p><a href="https://www.baeldung.com/cs/https-urls-encrypted#:%7E:text=So%2C%20Are%20HTTPS%20URLS%20Encrypted,part%20of%20the%20TLS%20negotiation." rel="noreferrer">Note however</a> (as also noted in the comments) that the <strong>domain name</strong> part of the URL is sent in clear text during the first part of the TLS negotiation. So, the domain name of the server can be sniffed. But not the rest of the URL.</p>
{ "question_id": 499591, "question_date": "2009-01-31T21:15:34.577Z", "question_score": 1235, "tags": "ssl|https|httprequest", "answer_id": 499594, "answer_date": "2009-01-31T21:17:39.770Z", "answer_score": 1063 }
Please answer the following Stack Overflow question: Title: How do servlets work? Instantiation, sessions, shared variables and multithreading <p>Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables.</p> <p>Now, if 2 or more users send request to this server then what happens to the session variables?<br> Will they all be common for all the users or they will be different for each user?<br> If they are different, then how was the server able to differentiate between different users?</p> <p>One more similar question, if there are <code>n</code> users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately?<br> In other words, what happens to the instance variables?</p>
<h2><code>ServletContext</code></h2> <p>When the servlet container (like <a href="http://tomcat.apache.org" rel="noreferrer">Apache Tomcat</a>) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/ServletContext.html" rel="noreferrer"><code>ServletContext</code></a> once and keeps it in the server's memory. The web app's <code>web.xml</code> and all of included <code>web-fragment.xml</code> files is parsed, and each <code>&lt;servlet&gt;</code>, <code>&lt;filter&gt;</code> and <code>&lt;listener&gt;</code> found (or each class annotated with <code>@WebServlet</code>, <code>@WebFilter</code> and <code>@WebListener</code> respectively) will be instantiated once and be kept in the server's memory as well, registred via the <code>ServletContext</code>. For each instantiated filter, its <code>init()</code> method is invoked with a new <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/FilterConfig.html" rel="noreferrer"><code>FilterConfig</code></a> argument which in turn contains the involved <code>ServletContext</code>.</p> <p>When a <code>Servlet</code> has a <code>&lt;servlet&gt;&lt;load-on-startup&gt;</code> or <code>@WebServlet(loadOnStartup)</code> value greater than <code>0</code>, then its <code>init()</code> method is also invoked during startup with a new <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/ServletConfig.html" rel="noreferrer"><code>ServletConfig</code></a> argument which in turn contains the involved <code>ServletContext</code>. Those servlets are initialized in the same order specified by that value (<code>1</code> is 1st, <code>2</code> is 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the same order as they appear in the <code>web.xml</code>, <code>web-fragment.xml</code>, or <code>@WebServlet</code> classloading. In the event the &quot;load-on-startup&quot; value is absent, the <code>init()</code> method will be invoked whenever the <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_message" rel="noreferrer">HTTP request</a> hits that servlet for the very first time.</p> <p>When the servlet container is finished with all of the above described initialization steps, then the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/ServletContextListener.html#contextInitialized-javax.servlet.ServletContextEvent-" rel="noreferrer"><code>ServletContextListener#contextInitialized()</code></a> will be invoked with a <code>ServletContextEvent</code> argument which in turn contains the involved <code>ServletContext</code>. This will allow the developer the opportunity to programmatically register yet another <code>Servlet</code>, <code>Filter</code> or <code>Listener</code>.</p> <p>When the servlet container shuts down, it unloads all web applications, invokes the <code>destroy()</code> method of all its initialized servlets and filters, and all <code>Servlet</code>, <code>Filter</code> and <code>Listener</code> instances registered via the <code>ServletContext</code> are trashed. Finally the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/ServletContextListener.html#contextDestroyed-javax.servlet.ServletContextEvent-" rel="noreferrer"><code>ServletContextListener#contextDestroyed()</code></a> will be invoked and the <code>ServletContext</code> itself will be trashed.</p> <h2><code>HttpServletRequest</code> and <code>HttpServletResponse</code></h2> <p>The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (e.g. user with a web browser, or <a href="https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests">programmatically using <code>URLConnection</code></a>) sends an HTTP request, the servlet container creates new <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletRequest.html" rel="noreferrer"><code>HttpServletRequest</code></a> and <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletResponse.html" rel="noreferrer"><code>HttpServletResponse</code></a> objects and passes them through any defined <code>Filter</code> in the chain and, eventually, the <code>Servlet</code> instance.</p> <p>In the case of <a href="https://stackoverflow.com/tags/servlet-filters/info">filters</a>, the <code>doFilter()</code> method is invoked. When the servlet container's code calls <code>chain.doFilter(request, response)</code>, the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.</p> <p>In the case of <a href="https://stackoverflow.com/tags/servlets/info">servlets</a>, the <code>service()</code> method is invoked. By default, this method determines which one of the <code>doXxx()</code> methods to invoke based off of <code>request.getMethod()</code>. If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.</p> <p>The request object provides access to all of the information about the HTTP request, such as its <a href="https://en.wikipedia.org/wiki/URL" rel="noreferrer">URL</a>, <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="noreferrer">headers</a>, <a href="https://en.wikipedia.org/wiki/Query_string" rel="noreferrer">query string</a> and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made available for reuse.</p> <h2><code>HttpSession</code></h2> <p>When a client visits the webapp for the first time and/or the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpSession.html" rel="noreferrer"><code>HttpSession</code></a> is obtained for the first time via <code>request.getSession()</code>, the servlet container creates a new <code>HttpSession</code> object, generates a long and unique ID (which you can get by <code>session.getId()</code>), and stores it in the server's memory. The servlet container also sets a <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/Cookie.html" rel="noreferrer"><code>Cookie</code></a> in the <code>Set-Cookie</code> header of the HTTP response with <code>JSESSIONID</code> as its name and the unique session ID as its value.</p> <p>As per the <a href="http://www.faqs.org/rfcs/rfc2965.html" rel="noreferrer">HTTP cookie specification</a> (a contract any decent web browser and web server must adhere to), the client (the web browser) is required to send this <a href="https://en.wikipedia.org/wiki/HTTP_cookie" rel="noreferrer">cookie</a> back in subsequent requests in the <code>Cookie</code> header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the <em>Net/Network</em> tab). The servlet container will check the <code>Cookie</code> header of every incoming HTTP request for the presence of the cookie with the name <code>JSESSIONID</code> and use its value (the session ID) to get the associated <code>HttpSession</code> from server's memory.</p> <p>The <code>HttpSession</code> stays alive until it has been idle (i.e. not used in a request) for more than the timeout value specified in <code>&lt;session-timeout&gt;</code>, a setting in <code>web.xml</code>. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#HTTP_session" rel="noreferrer">session</a>. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.</p> <p>On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new <code>HttpSession</code> to be created, with an entirely new session cookie being used.</p> <h2>In a nutshell</h2> <ul> <li>The <code>ServletContext</code> lives for as long as the web app lives. It is shared among <em>all</em> requests in <em>all</em> sessions.</li> <li>The <code>HttpSession</code> lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among <em>all</em> requests in the <em>same</em> session.</li> <li>The <code>HttpServletRequest</code> and <code>HttpServletResponse</code> live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is <em>not</em> shared elsewhere.</li> <li>All <code>Servlet</code>, <code>Filter</code> and <code>Listener</code> instances live as long as the web app lives. They are shared among <em>all</em> requests in <em>all</em> sessions.</li> <li>Any <code>attribute</code> that is defined in <code>ServletContext</code>, <code>HttpServletRequest</code> and <code>HttpSession</code> will live as long as the object in question lives. The object itself represents the &quot;scope&quot; in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an <code>attribute</code> of its closest matching scope.</li> </ul> <h2>Thread Safety</h2> <p>That said, your major concern is possibly <a href="https://en.wikipedia.org/wiki/Thread_safety" rel="noreferrer"><em>thread safety</em></a>. You should now know that servlets and filters are shared among all requests. That's the nice thing about Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, <code>init()</code> and <code>destroy()</code> them for every single request.</p> <p>You should also realize that you should <strong>never</strong> assign any request or session scoped data as an <em>instance</em> variable of a servlet or filter. It will be shared among all other requests in other sessions. That's <strong>not</strong> thread-safe! The below example illustrates this:</p> <pre><code>public class ExampleServlet extends HttpServlet { private Object thisIsNOTThreadSafe; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object thisIsThreadSafe; thisIsNOTThreadSafe = request.getParameter(&quot;foo&quot;); // BAD!! Shared among all requests! thisIsThreadSafe = request.getParameter(&quot;foo&quot;); // OK, this is thread safe. } } </code></pre> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp">What is the difference between JSF, Servlet and JSP?</a></li> <li><a href="https://stackoverflow.com/questions/1700390/best-option-for-session-management-in-java">Best option for Session management in Java</a></li> <li><a href="https://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern">Difference between / and /* in servlet mapping url pattern</a></li> <li><a href="https://stackoverflow.com/questions/2349633/doget-and-dopost-in-servlets">doGet and doPost in Servlets</a></li> <li><a href="https://stackoverflow.com/questions/8011138/servlet-seems-to-handle-multiple-concurrent-requests-synchronously/">Servlet seems to handle multiple concurrent browser requests synchronously</a></li> <li><a href="https://stackoverflow.com/questions/9555842/why-servlets-are-not-thread-safe/">Why Servlets are not thread Safe?</a></li> </ul>
{ "question_id": 3106452, "question_date": "2010-06-24T00:16:15.440Z", "question_score": 1235, "tags": "java|multithreading|servlets|session-variables|instance-variables", "answer_id": 3106909, "answer_date": "2010-06-24T02:41:44.627Z", "answer_score": 1928 }
Please answer the following Stack Overflow question: Title: How to list branches that contain a given commit? <p>How can I query git to find out which branches contain a given commit? <code>gitk</code> will usually list the branches, unless there are too many, in which case it just says "many (38)" or something like that. I need to know the full list, or at least whether certain branches contain the commit.</p>
<p>From the <a href="https://git-scm.com/docs/git-branch#Documentation/git-branch.txt---containsltcommitgt" rel="noreferrer">git-branch manual page</a>:</p> <pre><code> git branch --contains &lt;commit&gt; </code></pre> <blockquote> <p>Only list branches which contain the specified commit (HEAD if not specified). Implies <code>--list</code>.</p> </blockquote> <hr /> <pre><code> git branch -r --contains &lt;commit&gt; </code></pre> <p>Lists <strong><a href="https://stackoverflow.com/a/4697054/6309">remote tracking branches</a></strong> as well (as mentioned in <a href="https://stackoverflow.com/users/3941992/user3941992">user3941992</a>'s <a href="https://stackoverflow.com/a/25311972/6309">answer</a> below) that is &quot;local branches that have a direct relationship to a remote branch&quot;.</p> <hr /> <p>As <a href="https://stackoverflow.com/a/64690532/6309">noted</a> by <a href="https://stackoverflow.com/users/771768/carl-walsh">Carl Walsh</a>, this applies only to the <a href="https://git-scm.com/book/en/v2/Git-Internals-The-Refspec" rel="noreferrer">default refspec</a></p> <pre><code>fetch = +refs/heads/*:refs/remotes/origin/* </code></pre> <p>If you need to include other ref namespace (<a href="https://gist.github.com/piscisaureus/3342247" rel="noreferrer">pull request</a>, <a href="https://gerrit-review.googlesource.com/Documentation/concept-refs-for-namespace.html" rel="noreferrer">Gerrit</a>, ...), you need to add that new refspec, and fetch again:</p> <pre><code>git config --add remote.origin.fetch &quot;+refs/pull/*/head:refs/remotes/origin/pr/*&quot; git fetch git branch -r --contains &lt;commit&gt; </code></pre> <hr /> <p>See also this <a href="http://www.gitready.com/intermediate/2009/04/03/find-ancestor-commits.html" rel="noreferrer">git ready</a> article.</p> <blockquote> <p>The <code>--contains</code> tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.</p> </blockquote> <pre><code>$ git log -1 tests commit d590f2ac0635ec0053c4a7377bd929943d475297 Author: Nick Quaranto &lt;[email protected]&gt; Date: Wed Apr 1 20:38:59 2009 -0400 Green all around, finally. $ git branch --contains d590f2 tests * master </code></pre> <hr /> <p>Note: <strong>if the commit is on a <a href="https://stackoverflow.com/a/1070851/6309">remote tracking branch</a>, add the <code>-a</code> option</strong>.<br /> (as <a href="https://stackoverflow.com/users/114904/michielb">MichielB</a> comments <a href="https://stackoverflow.com/questions/1419623/how-to-list-branches-that-contain-a-given-commit/1419637#comment27176667_1419637">below</a>)</p> <pre><code>git branch -a --contains &lt;commit&gt; </code></pre> <hr /> <p><a href="https://stackoverflow.com/users/65977/matrixfrog">MatrixFrog</a> comments that it only shows which branches contain that <em>exact</em> commit.<br /> If you want to know which branches contain an &quot;equivalent&quot; commit (i.e. which branches have cherry-picked that commit) that's <strong><a href="https://git-scm.com/docs/git-cherry" rel="noreferrer"><code>git cherry</code></a></strong>:</p> <blockquote> <p>Because <code>git cherry</code> <strong>compares the changeset rather than the commit id (sha1)</strong>, you can use <code>git cherry</code> to find out if a commit you made locally has been applied <code>&lt;upstream&gt;</code> under a different commit id.<br /> For example, this will happen if you’re feeding patches <code>&lt;upstream&gt;</code> via email rather than pushing or pulling commits directly.</p> </blockquote> <pre><code> __*__*__*__*__&gt; &lt;upstream&gt; / fork-point \__+__+__-__+__+__-__+__&gt; &lt;head&gt; </code></pre> <p>(Here, the commits marked '<code>-</code>' wouldn't show up with <code>git cherry</code>, meaning they are already present in <code>&lt;upstream&gt;</code>.)</p>
{ "question_id": 1419623, "question_date": "2009-09-14T04:03:10.537Z", "question_score": 1234, "tags": "git|version-control", "answer_id": 1419637, "answer_date": "2009-09-14T04:08:58.510Z", "answer_score": 1668 }
Please answer the following Stack Overflow question: Title: Is quitting an application frowned upon? <p>Moving on in my attempt to learn Android, I just <a href="http://groups.google.com/group/android-developers/browse_thread/thread/1bf0f7a4a9c62edd/a0a4aedf21ae5f76" rel="noreferrer">read the following</a>:</p> <blockquote> <p>Question: <i>Does the user have a choice to kill the application unless we put a menu option in to kill it? If no such option exists, how does the user terminate the application? </i></p> <p>Answer: (Romain Guy): <i>The user doesn't, the system handles this automatically. That's what the activity lifecycle (especially onPause/onStop/onDestroy) is for. No matter what you do, do not put a "quit" or "exit" application button. It is useless with Android's application model. This is also contrary to how core applications work. </i></p> </blockquote> <p>Hehe, for every step I take in the Android world I run into some sort of problem =(</p> <p>Apparently, you cannot quit an application in Android (but the Android system can very well totally destroy your app whenever it feels like it). What's up with that? I am starting to think that it's impossible to write an app that functions as a "normal app" - that the user can quit the app when he/she decides to do so. That is not something that should be relied upon the OS to do.</p> <p>The application I am trying to create is not an application for the Android Market. It is not an application for "wide use" by the general public, it is a business app that is going to be used in a very narrow business field.</p> <p>I was actually really looking forward to developing for the Android platform, since it addresses a lot of issues that exist in Windows Mobile and .NET. However, the last week has been somewhat of a turnoff for me... I hope I don't have to abandon Android, but it doesn't look very good right now =(</p> <p>Is there a way for me to <b>really</b> quit the application?</p>
<p>This will eventually get to your question, but I first want to address a number of issues you raise in your various comments to the various answers already given at the time of this writing. I have no intention of changing your mind -- rather, these are here for others who come to read this post in the future.</p> <blockquote> <p>The point is that I cannot allow for Android to determine when my app is going to be terminated. that must be the choice of the user.</p> </blockquote> <p>Millions of people are perfectly happy with the model where the environment closes up the application as needed. Those users simply don't think about &quot;terminating&quot; the Android app, any more than they think about &quot;terminating&quot; a Web page or &quot;terminating&quot; a thermostat.</p> <p>iPhone users are much the same way, in that pressing the iPhone button does not necessarily &quot;feel&quot; like the app was terminated since many iPhone apps pick up where the user left off, even if the app really was shut down (since iPhone only allows one third-party app at a time, at present).</p> <blockquote> <p>As I said above, there is a lot of things going on in my app (data being PUSHed to the device, lists with tasks that always should be there, etc.).</p> </blockquote> <p>I don't know what &quot;lists with tasks that always should be there&quot; means, but the &quot;data being PUSHed to the device&quot; is a pleasant fiction and should not be done by activity in any case. Use a scheduled task (via <code>AlarmManager</code>) to update your data for maximum reliability.</p> <blockquote> <p>Our users log in and can't be doing that every time they get a phone call and Android decides to kill the app.</p> </blockquote> <p>There are many iPhone and Android applications that deal with this. Usually, it is because they hold onto login credentials, rather than forcing users to log in every time manually.</p> <blockquote> <p>For example, we want to check updates when exiting the application</p> </blockquote> <p>That is a mistake on any operating system. For all you know, the reason your application is being &quot;exited&quot; is because the OS is shutting down, and then your update process will fail mid-stream. Generally, that's not a good thing. Either check updates on start or check updates totally asynchronously (e.g., via a scheduled task), never on exit.</p> <blockquote> <p>Some comments suggest that hitting the back button does not kill the app at all (see link in my question above).</p> </blockquote> <p>Pressing the BACK button does not &quot;kill the app&quot;. It finishes the activity that was on-screen when the user pressed the BACK button.</p> <blockquote> <p>It should only terminate when the users want to terminate it - never ever any other way. If you can't write apps that behave like that in Android, then I think that Android can't be used for writing real apps =(</p> </blockquote> <p>Then neither can Web applications. Or <a href="https://en.wikipedia.org/wiki/WebOS" rel="noreferrer">WebOS</a>, if I understand their model correctly (haven't had a chance to play with one yet). In all of those, users don't &quot;terminate&quot; anything -- they just leave. iPhone is a bit different, in that it only presently allows one thing to run at a time (with a few exceptions), and so the act of leaving implies a fairly immediate termination of the app.</p> <blockquote> <p>Is there a way for me to really quit the application?</p> </blockquote> <p>As everybody else told you, users (via BACK) or your code (via <code>finish()</code>) can close up your currently-running activity. Users generally don't need anything else, for properly-written applications, any more than they need a &quot;quit&quot; option for using Web applications.</p> <hr /> <p>No two application environments are the same, by definition. This means that you can see trends in environments as new ones arise and others get buried.</p> <p>For example, there is a growing movement to try to eliminate the notion of the &quot;file&quot;. Most Web applications don't force users to think of files. iPhone apps typically don't force users to think of files. Android apps generally don't force users to think of files. And so on.</p> <p>Similarly, there is a growing movement to try to eliminate the notion of &quot;terminating&quot; an app. Most Web applications don't force the user to log out, but rather implicitly log the user out after a period of inactivity. Same thing with Android, and to a lesser extent, iPhone (and possibly WebOS).</p> <p>This requires more emphasis on application design, focusing on business goals, and not sticking with an implementation model tied to a previous application environment. Developers who lack the time or inclination to do this will get frustrated with newer environments that break their existing mental model. This is not the fault of either environment, any more than it is the fault of a mountain for storms flowing around it rather than through it.</p> <p>For example, some development environments, like <a href="https://en.wikipedia.org/wiki/HyperCard" rel="noreferrer">Hypercard</a> and Smalltalk, had the application and the development tools co-mingled in one setup. This concept did not catch on much, outside of language extensions to apps (e.g., <a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" rel="noreferrer">VBA</a> in <a href="http://en.wikipedia.org/wiki/Microsoft_Excel" rel="noreferrer">Excel</a>, <a href="https://en.wikipedia.org/wiki/AutoLISP" rel="noreferrer">Lisp in AutoCAD</a>). Developers who came up with mental models that presumed the existence of development tools in the app itself, therefore, either had to change their model or limit themselves to environments where their model would hold true.</p> <p>So, when you write:</p> <blockquote> <p>Along with other messy things I discovered, I think that developing our app for Android is not going to happen.</p> </blockquote> <p>That would appear to be for the best, for you, for right now. Similarly, I would counsel you against attempting to port your application to the Web, since some of the same problems you have reported with Android you will find in Web applications as well (e.g., no &quot;termination&quot;). Or, conversely, someday if you <em>do</em> port your app to the Web, you may find that the Web application's flow may be a better match for Android, and you can revisit an Android port at that time.</p>
{ "question_id": 2033914, "question_date": "2010-01-09T15:59:46.707Z", "question_score": 1233, "tags": "android", "answer_id": 2034238, "answer_date": "2010-01-09T17:35:40.680Z", "answer_score": 1331 }
Please answer the following Stack Overflow question: Title: How to overlay one div over another div <p>I need assistance with overlaying one individual <code>div</code> over another individual <code>div</code>.</p> <p>My code looks like this:</p> <pre><code>&lt;div class="navi"&gt;&lt;/div&gt; &lt;div id="infoi"&gt; &lt;img src="info_icon2.png" height="20" width="32"/&gt; &lt;/div&gt; </code></pre> <p>Unfortunately I cannot nest the <code>div#infoi</code> or the <code>img</code>, inside the first <code>div.navi</code>.</p> <p>It has to be two separate <code>div</code>s as shown, but I need to know how I could place the <code>div#infoi</code> over the <code>div.navi</code> and to the right most side and centered on top of the <code>div.navi</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { width: 100px; height: 100px; position: relative; } #navi, #infoi { width: 100%; height: 100%; position: absolute; top: 0; left: 0; } #infoi { z-index: 10; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="navi"&gt;a&lt;/div&gt; &lt;div id="infoi"&gt; &lt;img src="https://appharbor.com/assets/images/stackoverflow-logo.png" height="20" width="32" /&gt;b &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I would suggest learning about <code>position: relative</code> and child elements with <code>position: absolute</code>.</p>
{ "question_id": 2941189, "question_date": "2010-05-31T03:15:23.387Z", "question_score": 1232, "tags": "html|css|position|overlay", "answer_id": 2941203, "answer_date": "2010-05-31T03:20:15.927Z", "answer_score": 1500 }
Please answer the following Stack Overflow question: Title: How to perform an integer division, and separately get the remainder, in JavaScript? <p>In <strong>JavaScript</strong>, how do I get:</p> <ol> <li>The whole number of times a given integer goes into another?</li> <li>The remainder?</li> </ol>
<p>For some number <code>y</code> and some divisor <code>x</code> compute the quotient (<code>quotient</code>)<sup>[1]</sup> and remainder (<code>remainder</code>) as:</p> <pre><code>const quotient = Math.floor(y/x); const remainder = y % x; </code></pre> <p>Example:</p> <pre><code>const quotient = Math.floor(13/3); // =&gt; 4 =&gt; the times 3 fits into 13 const remainder = 13 % 3; // =&gt; 1 </code></pre> <hr /> <p>[1] <em>The integer number resulting from the division of one number by another</em></p>
{ "question_id": 4228356, "question_date": "2010-11-19T18:53:13.800Z", "question_score": 1231, "tags": "javascript|math|modulo|integer-division", "answer_id": 4228376, "answer_date": "2010-11-19T18:55:34.843Z", "answer_score": 1652 }
Please answer the following Stack Overflow question: Title: How can I customize the tab-to-space conversion factor? <p>How do I customize the tab-to-space conversion factor when using Visual Studio Code?</p> <p>For instance, right now in HTML it appears to produce two spaces per press of <kbd>TAB</kbd>, but in TypeScript it produces 4.</p>
<p>By default, Visual Studio Code will try to guess your indentation options depending on the file you open.</p> <p>You can turn off indentation guessing via <code>"editor.detectIndentation": false</code>.</p> <p>You can customize this easily via these three settings for <strong>Windows</strong> in menu <em>File</em> → <em>Preferences</em> → <em>User Settings</em> and for <strong>Mac</strong> in menu <em>Code</em> → <em>Preferences</em> → <em>Settings</em> or <code>⌘,</code>:</p> <pre class="lang-js prettyprint-override"><code>// The number of spaces a tab is equal to. This setting is overridden // based on the file contents when `editor.detectIndentation` is true. "editor.tabSize": 4, // Insert spaces when pressing Tab. This setting is overriden // based on the file contents when `editor.detectIndentation` is true. "editor.insertSpaces": true, // When opening a file, `editor.tabSize` and `editor.insertSpaces` // will be detected based on the file contents. Set to false to keep // the values you've explicitly set, above. "editor.detectIndentation": false </code></pre>
{ "question_id": 29972396, "question_date": "2015-04-30T15:54:29.663Z", "question_score": 1231, "tags": "visual-studio-code|vscode-settings", "answer_id": 29972553, "answer_date": "2015-04-30T16:02:19.610Z", "answer_score": 1868 }
Please answer the following Stack Overflow question: Title: Serializing to JSON in jQuery <p>I need to <a href="https://en.wikipedia.org/wiki/Serialization" rel="noreferrer">serialize</a> an object to <a href="https://www.json.org/" rel="noreferrer">JSON</a>. I'm using <a href="https://api.jquery.com/" rel="noreferrer">jQuery</a>. Is there a "standard" way to do this?</p> <p>My specific situation: I have an array defined as shown below:</p> <pre><code>var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ... </code></pre> <p>and I need to turn this into a string to pass to <a href="https://www.w3schools.com/jquery/ajax_ajax.asp" rel="noreferrer"><code>$.ajax()</code></a> like this:</p> <pre><code>$.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'countries':['ga','cd']}", ... </code></pre>
<p><a href="https://github.com/douglascrockford/JSON-js" rel="noreferrer">JSON-js</a> - JSON in JavaScript.</p> <p>To convert an object to a string, use <code>JSON.stringify</code>:</p> <pre><code>var json_text = JSON.stringify(your_object, null, 2); </code></pre> <p>To convert a JSON string to object, use <code>JSON.parse</code>:</p> <pre><code>var your_object = JSON.parse(json_text); </code></pre> <p>It was recently recommended by <a href="http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/" rel="noreferrer">John Resig</a>:</p> <blockquote> <p>...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.</p> <p>In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.</p> </blockquote> <p>I tend to trust what he says on JavaScript matters :)</p> <p><a href="http://caniuse.com/json" rel="noreferrer">All modern browsers</a> (and many older ones which aren't ancient) support the <a href="http://ecma262-5.com/ELS5_Section_15.htm#Section_15.12" rel="noreferrer">JSON object</a> natively. The current version of Crockford's JSON library will only define <code>JSON.stringify</code> and <code>JSON.parse</code> if they're not already defined, leaving any browser native implementation intact.</p>
{ "question_id": 191881, "question_date": "2008-10-10T15:29:56.750Z", "question_score": 1231, "tags": "javascript|jquery|ajax|json|serialization", "answer_id": 912247, "answer_date": "2009-05-26T19:22:40.907Z", "answer_score": 1156 }
Please answer the following Stack Overflow question: Title: How to call shell commands from Ruby <p>How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?</p>
<p>This explanation is based on a commented <a href="http://gist.github.com/4069" rel="noreferrer">Ruby script</a> from a friend of mine. If you want to improve the script, feel free to update it at the link.</p> <p>First, note that when Ruby calls out to a shell, it typically calls <code>/bin/sh</code>, <em>not</em> Bash. Some Bash syntax is not supported by <code>/bin/sh</code> on all systems.</p> <p>Here are ways to execute a shell script:</p> <pre><code>cmd = "echo 'hi'" # Sample string that can be used </code></pre> <ol> <li><p><code>Kernel#`</code> , commonly called backticks – <code>`cmd`</code></p> <p>This is like many other languages, including Bash, PHP, and Perl.</p> <p>Returns the result (i.e. standard output) of the shell command.</p> <p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-60" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-60</a></p> <pre><code>value = `echo 'hi'` value = `#{cmd}` </code></pre></li> <li><p>Built-in syntax, <code>%x( cmd )</code></p> <p>Following the <code>x</code> character is a delimiter, which can be any character. If the delimiter is one of the characters <code>(</code>, <code>[</code>, <code>{</code>, or <code>&lt;</code>, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation <code>#{ ... }</code> is allowed.</p> <p>Returns the result (i.e. standard output) of the shell command, just like the backticks.</p> <p>Docs: <a href="https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings" rel="noreferrer">https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings</a></p> <pre><code>value = %x( echo 'hi' ) value = %x[ #{cmd} ] </code></pre></li> <li><p><code>Kernel#system</code></p> <p>Executes the given command in a subshell. </p> <p>Returns <code>true</code> if the command was found and run successfully, <code>false</code> otherwise.</p> <p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-system" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-system</a></p> <pre><code>wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) </code></pre></li> <li><p><code>Kernel#exec</code></p> <p>Replaces the current process by running the given external command.</p> <p>Returns none, the current process is replaced and never continues.</p> <p>Docs: <a href="http://ruby-doc.org/core/Kernel.html#method-i-exec" rel="noreferrer">http://ruby-doc.org/core/Kernel.html#method-i-exec</a></p> <pre><code>exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above </code></pre></li> </ol> <p>Here's some extra advice: <code>$?</code>, which is the same as <code>$CHILD_STATUS</code>, accesses the status of the last system executed command if you use the backticks, <code>system()</code> or <code>%x{}</code>. You can then access the <code>exitstatus</code> and <code>pid</code> properties:</p> <pre><code>$?.exitstatus </code></pre> <p>For more reading see:</p> <ul> <li><a href="http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands" rel="noreferrer">http://www.elctech.com/blog/i-m-in-ur-commandline-executin-ma-commands</a></li> <li><a href="http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html" rel="noreferrer">http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html</a></li> <li><a href="http://tech.natemurray.com/2007/03/ruby-shell-commands.html" rel="noreferrer">http://tech.natemurray.com/2007/03/ruby-shell-commands.html</a></li> </ul>
{ "question_id": 2232, "question_date": "2008-08-05T12:56:52.770Z", "question_score": 1230, "tags": "ruby|shell|interop", "answer_id": 2400, "answer_date": "2008-08-05T14:42:45.927Z", "answer_score": 1449 }
Please answer the following Stack Overflow question: Title: CSS selector for first element with class <p>I have a bunch of elements with a class name <code>red</code>, but I can't seem to select the first element with the <code>class=&quot;red&quot;</code> using the following CSS rule:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.home .red:first-child { border: 1px solid red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="home"&gt; &lt;span&gt;blah&lt;/span&gt; &lt;p class="red"&gt;first&lt;/p&gt; &lt;p class="red"&gt;second&lt;/p&gt; &lt;p class="red"&gt;third&lt;/p&gt; &lt;p class="red"&gt;fourth&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>What is wrong in this selector and how do I correct it to target the first child with class <code>red</code>?</p>
<p>This is one of the most well-known examples of authors misunderstanding how <code>:first-child</code> works. <a href="https://www.w3.org/TR/CSS21/selector.html#first-child" rel="noreferrer">Introduced in CSS2</a>, the <code>:first-child</code> pseudo-class represents <strong>the very first child of its parent</strong>. That's it. There's a very common misconception that it picks up whichever child element is the first to match the conditions specified by the rest of the compound selector. Due to the way selectors work (see <a href="https://stackoverflow.com/questions/5545649/can-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector/5546296#5546296">here</a> for an explanation), that is simply not true.</p> <p><a href="https://www.w3.org/TR/css3-selectors/#first-of-type-pseudo" rel="noreferrer">Selectors level 3 introduces a <code>:first-of-type</code> pseudo-class</a>, which represents the first element among siblings of its element type. <a href="https://stackoverflow.com/questions/24657555/what-is-the-difference-between-first-child-and-first-of-type/24657721#24657721">This answer</a> explains, with illustrations, the difference between <code>:first-child</code> and <code>:first-of-type</code>. However, as with <code>:first-child</code>, it does not look at any other conditions or attributes. In HTML, the element type is represented by the tag name. In the question, that type is <code>p</code>.</p> <p>Unfortunately, there is no similar <code>:first-of-class</code> pseudo-class for matching the first child element of a given class. At the time this answer was first posted, <a href="https://www.w3.org/TR/2011/WD-selectors4-20110929/#nth-match" rel="noreferrer">the newly published FPWD of Selectors level 4 introduced an <code>:nth-match()</code> pseudo-class</a>, designed around existing selector mechanics as I mentioned in the first paragraph by adding a selector-list argument, through which you can supply the rest of the compound selector to get the desired filtering behavior. In recent years this functionality was <a href="https://www.w3.org/TR/selectors-4/#the-nth-child-pseudo" rel="noreferrer">subsumed into <code>:nth-child()</code> itself</a>, with the selector list appearing as an optional second argument, to simplify things as well as averting the false impression that <code>:nth-match()</code> matched across the entire document (see the final note below).</p> <p>While we await <a href="https://caniuse.com/css-nth-child-of" rel="noreferrer">cross-browser support</a> (seriously, it's been nearly 10 years, and there has only been a single implementation for the last 5 of those years), one workaround that <a href="https://stackoverflow.com/questions/5287272/css-select-first-element-with-a-certain-class/5293095#5293095">Lea Verou</a> and I developed independently (she did it first!) is to first apply your desired styles to <em>all</em> your elements with that class:</p> <pre class="lang-css prettyprint-override"><code>/* * Select all .red children of .home, including the first one, * and give them a border. */ .home &gt; .red { border: 1px solid red; } </code></pre> <p>... then &quot;undo&quot; the styles for elements with the class that <em>come after the first one</em>, using <a href="https://www.w3.org/TR/selectors/#general-sibling-combinators" rel="noreferrer">the general sibling combinator <code>~</code></a> in an overriding rule:</p> <pre class="lang-css prettyprint-override"><code>/* * Select all but the first .red child of .home, * and remove the border from the previous rule. */ .home &gt; .red ~ .red { border: none; } </code></pre> <p>Now only the first element with <code>class=&quot;red&quot;</code> will have a border.</p> <p>Here's an illustration of how the rules are applied:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.home &gt; .red { border: 1px solid red; } .home &gt; .red ~ .red { border: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="home"&gt; &lt;span&gt;blah&lt;/span&gt; &lt;!-- [1] --&gt; &lt;p class="red"&gt;first&lt;/p&gt; &lt;!-- [2] --&gt; &lt;p class="red"&gt;second&lt;/p&gt; &lt;!-- [3] --&gt; &lt;p class="red"&gt;third&lt;/p&gt; &lt;!-- [3] --&gt; &lt;p class="red"&gt;fourth&lt;/p&gt; &lt;!-- [3] --&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <ol> <li><p><strong>No rules are applied; no border is rendered.</strong><br /> This element does not have the class <code>red</code>, so it's skipped.</p> </li> <li><p><strong>Only the first rule is applied; a red border is rendered.</strong><br /> This element has the class <code>red</code>, but it's not preceded by any elements with the class <code>red</code> in its parent. Thus the second rule is not applied, only the first, and the element keeps its border.</p> </li> <li><p><strong>Both rules are applied; no border is rendered.</strong><br /> This element has the class <code>red</code>. It is also preceded by at least one other element with the class <code>red</code>. Thus both rules are applied, and the second <code>border</code> declaration overrides the first, thereby &quot;undoing&quot; it, so to speak.</p> </li> </ol> <p>As a bonus, although it was introduced in Selectors 3, the general sibling combinator is actually pretty well-supported by IE7 and newer, unlike <code>:first-of-type</code> and <code>:nth-of-type()</code> which are only supported by IE9 onward. If you need good browser support, you're in luck.</p> <p>In fact, the fact that the sibling combinator is the only important component in this technique, <em>and</em> it has such amazing browser support, makes this technique very versatile — you can adapt it for filtering elements by other things, besides class selectors:</p> <ul> <li><p>You can use this to work around <code>:first-of-type</code> in IE7 and IE8, by simply supplying a type selector instead of a class selector (again, more on its incorrect usage in the question in a later section):</p> <pre class="lang-css prettyprint-override"><code> article &gt; p { /* Apply styles to article &gt; p:first-of-type, which may or may not be :first-child */ } article &gt; p ~ p { /* Undo the above styles for every subsequent article &gt; p */ } </code></pre> </li> <li><p>You can filter by <a href="https://stackoverflow.com/questions/7128406/css-select-the-first-child-from-elements-with-particular-attribute/7128429#7128429">attribute selectors</a> or any other simple selectors instead of classes.</p> </li> <li><p>You can also combine this overriding technique with <a href="https://stackoverflow.com/questions/8535686/first-child-not-working/8535800#8535800">pseudo-elements</a> even though pseudo-elements technically aren't simple selectors.</p> </li> </ul> <p>Note that in order for this to work, you will need to know in advance what the default styles will be for your other sibling elements so you can override the first rule. Additionally, since this involves overriding rules in CSS, you can't achieve the same thing with a single selector for use with the <a href="https://www.w3.org/TR/selectors-api" rel="noreferrer">Selectors API</a>, or <a href="https://www.selenium.dev" rel="noreferrer">Selenium</a>'s CSS locators.</p> <p>On a final note, keep in mind that this answer assumes that the question is looking for <em>any number of</em> first child elements having a given class. There is neither a pseudo-class nor even a generic CSS solution for the nth match of a complex selector <em>across the entire document</em> — whether a solution exists depends heavily on the document structure. jQuery provides <code>:eq()</code>, <code>:first</code>, <code>:last</code> and more for this purpose, but note again that <a href="https://stackoverflow.com/questions/9983297/difference-between-css-selector-and-jquery-filter/10835694#10835694">they function very differently from <code>:nth-child()</code> et al</a>. Using the Selectors API, you can either use <code>document.querySelector()</code> to obtain the very first match:</p> <pre class="lang-js prettyprint-override"><code>var first = document.querySelector('.home &gt; .red'); </code></pre> <p>Or use <code>document.querySelectorAll()</code> with an indexer to pick any specific match:</p> <pre class="lang-js prettyprint-override"><code>var redElements = document.querySelectorAll('.home &gt; .red'); var first = redElements[0]; var second = redElements[1]; // etc </code></pre> <hr /> <p>Although the <code>.red:nth-of-type(1)</code> solution in the original accepted answer by <a href="https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class/2717515#2717515">Philip Daubmeier</a> works (which was originally written by <a href="https://stackoverflow.com/users/264276/martyn">Martyn</a> but deleted since), it does not behave the way you'd expect it to.</p> <p>For example, if you only wanted to select the <code>p</code> here:</p> <pre class="lang-html prettyprint-override"><code>&lt;p class=&quot;red&quot;&gt;&lt;/p&gt; &lt;div class=&quot;red&quot;&gt;&lt;/div&gt; </code></pre> <p>... then you can't use <code>.red:first-of-type</code> (equivalent to <code>.red:nth-of-type(1)</code>), because each element is the first (and only) one of its type (<code>p</code> and <code>div</code> respectively), so <em>both</em> will be matched by the selector.</p> <p>When the first element of a certain class <em>is also the first of its type</em>, the pseudo-class will work, but <strong>this happens only by coincidence</strong>. This behavior is demonstrated in Philip's answer. The moment you stick in an element of the same type before this element, the selector will fail. Taking the markup from the question:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;home&quot;&gt; &lt;span&gt;blah&lt;/span&gt; &lt;p class=&quot;red&quot;&gt;first&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;second&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;third&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;fourth&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Applying a rule with <code>.red:first-of-type</code> will work, but once you add another <code>p</code> without the class:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;home&quot;&gt; &lt;span&gt;blah&lt;/span&gt; &lt;p&gt;dummy&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;first&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;second&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;third&lt;/p&gt; &lt;p class=&quot;red&quot;&gt;fourth&lt;/p&gt; &lt;/div&gt; </code></pre> <p>... the selector will immediately fail, because the first <code>.red</code> element is now the <em>second</em> <code>p</code> element.</p>
{ "question_id": 2717480, "question_date": "2010-04-26T22:51:13.150Z", "question_score": 1229, "tags": "css|css-selectors", "answer_id": 8539107, "answer_date": "2011-12-16T19:21:56.910Z", "answer_score": 1772 }
Please answer the following Stack Overflow question: Title: Where is the global git config data stored? <p>When using <code>git config --global</code> to set things up, to which file will it write?</p> <p>Example:</p> <pre><code>git config --global core.editor "blah" </code></pre> <p>I can't find it at these places:</p> <pre><code>C:\Program Files\Git\etc\gitconfig C:\myapp\.git\config </code></pre> <p>I have not set an ENV?</p> <p>My Git version: 1.6.5.1.1367.gcd48 – on Windows 7</p>
<p>Update 2016: with git 2.8 (March 2016), you can simply use:</p> <pre><code>git config --list --show-origin </code></pre> <p>And with Git 2.26 (Q1 2020), you can <a href="https://stackoverflow.com/a/60286340/6309">add a <code>--show-scope</code> option</a></p> <pre><code>git config --list --show-origin --show-scope </code></pre> <p>You will see which config is set where.<br /> See &quot;<a href="https://stackoverflow.com/a/35670933/6309">Where do the settings in my Git configuration come from?</a>&quot;</p> <p>As <a href="https://stackoverflow.com/users/3357935/stevoisiak">Stevoisiak</a> points out <a href="https://stackoverflow.com/questions/2114111/where-does-git-config-global-get-written-to/2115116#comment79861204_2115116">in the comments</a>,</p> <blockquote> <p>it will work with non-standard install locations. (i.e. <a href="https://github.com/git-for-windows/git/releases" rel="noreferrer">Git Portable</a>)</p> </blockquote> <p>(like the latest <a href="https://github.com/git-for-windows/git/releases/download/v2.14.2.windows.1/PortableGit-2.14.2-64-bit.7z.exe" rel="noreferrer"><code>PortableGit-2.14.2-64-bit.7z.exe</code></a>, which can be uncompressed anywhere you want)</p> <hr /> <p>Original answer (2010)</p> <p>From <a href="http://git-scm.com/docs/git-config" rel="noreferrer">the docs</a>:</p> <blockquote> <h3>--global</h3> <p>For writing options: write to global <code>~/.gitconfig</code> file rather than the repository <code>.git/config</code>.</p> </blockquote> <p>Since you're using <a href="http://msysgit.github.io/" rel="noreferrer">Git for Windows</a>, it may not be clear what location this corresponds to. But if you look at etc/profile (in <code>C:\Program Files\Git</code>), you'll see:</p> <pre><code>HOME=&quot;$HOMEDRIVE$HOMEPATH&quot; </code></pre> <p>Meaning:</p> <pre><code>C:\Users\MyLogin </code></pre> <p>(on Windows 7)</p> <p>That means the file is in <strong><code>C:\Users\MyLogin\.gitconfig</code></strong> for Git in Windows 7.</p>
{ "question_id": 2114111, "question_date": "2010-01-22T00:34:55.787Z", "question_score": 1228, "tags": "git|config", "answer_id": 2115116, "answer_date": "2010-01-22T05:02:38.163Z", "answer_score": 1525 }
Please answer the following Stack Overflow question: Title: Convert tabs to spaces in Notepad++ <p>How do I convert tabs to spaces in Notepad++? </p> <p>I found <a href="http://www.texteditors.info/notepad-replacements-compared.php" rel="noreferrer">a webpage</a> that suggests it's possible, but I couldn't find any information about how to do it. </p> <p>I would like to be able to do that, because some web forms don't respect code with tabs in them.</p>
<p>To convert existing tabs to spaces, press <code>Edit-&gt;Blank Operations-&gt;TAB to Space</code>.</p> <p>If in the future you want to enter spaces instead of tab when you press tab key:</p> <ol> <li>Go to <code>Settings-&gt;Preferences...-&gt;Language</code> (since version 7.1) or <code>Settings-&gt;Preferences...-&gt;Tab Settings</code> (previous versions)</li> <li>Check <code>Replace by space</code></li> <li>(<em>Optional</em>) You can set the number of spaces to use in place of a Tab by changing the <code>Tab size</code> field.</li> </ol> <p><a href="https://i.stack.imgur.com/cDrHP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cDrHP.png" alt="Screenshot of Replace by space"></a></p>
{ "question_id": 455037, "question_date": "2009-01-18T12:10:16.063Z", "question_score": 1227, "tags": "notepad++|whitespace|indentation", "answer_id": 7471232, "answer_date": "2011-09-19T12:52:26.627Z", "answer_score": 1246 }
Please answer the following Stack Overflow question: Title: How to call asynchronous method from synchronous method in C#? <p>I have a <code>public async void Foo()</code> method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via async methods, but my whole program is not built with async methods.</p> <p>Is this even possible?</p> <p>Here's one example of calling these methods from an asynchronous method:<br /> <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/hh300224(v=vs.110)?redirectedfrom=MSDN" rel="noreferrer">Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic)</a></p> <p>Now I'm looking into calling these async methods from sync methods.</p>
<p>Asynchronous programming does &quot;grow&quot; through the code base. It has been <a href="https://web.archive.org/web/20190126143814/https://blogs.msdn.microsoft.com/lucian/2011/04/15/async-ctp-refresh-design-changes/" rel="noreferrer">compared to a zombie virus</a>. The best solution is to allow it to grow, but sometimes that's not possible.</p> <p>I have written a few types in my <a href="https://github.com/StephenCleary/AsyncEx" rel="noreferrer">Nito.AsyncEx</a> library for dealing with a partially-asynchronous code base. There's no solution that works in every situation, though.</p> <p><strong>Solution A</strong></p> <p>If you have a simple asynchronous method that doesn't need to synchronize back to its context, then you can use <code>Task.WaitAndUnwrapException</code>:</p> <pre><code>var task = MyAsyncMethod(); var result = task.WaitAndUnwrapException(); </code></pre> <p>You do <em>not</em> want to use <code>Task.Wait</code> or <code>Task.Result</code> because they wrap exceptions in <code>AggregateException</code>.</p> <p>This solution is only appropriate if <code>MyAsyncMethod</code> does not synchronize back to its context. In other words, every <code>await</code> in <code>MyAsyncMethod</code> should end with <code>ConfigureAwait(false)</code>. This means it can't update any UI elements or access the ASP.NET request context.</p> <p><strong>Solution B</strong></p> <p>If <code>MyAsyncMethod</code> does need to synchronize back to its context, then you may be able to use <code>AsyncContext.RunTask</code> to provide a nested context:</p> <pre><code>var result = AsyncContext.RunTask(MyAsyncMethod).Result; </code></pre> <hr /> <p>*Update 4/14/2014: In more recent versions of the library the API is as follows:</p> <pre><code>var result = AsyncContext.Run(MyAsyncMethod); </code></pre> <hr /> <p>(It's OK to use <code>Task.Result</code> in this example because <code>RunTask</code> will propagate <code>Task</code> exceptions).</p> <p>The reason you may need <code>AsyncContext.RunTask</code> instead of <code>Task.WaitAndUnwrapException</code> is because of a rather subtle deadlock possibility that happens on WinForms/WPF/SL/ASP.NET:</p> <ol> <li>A synchronous method calls an async method, obtaining a <code>Task</code>.</li> <li>The synchronous method does a blocking wait on the <code>Task</code>.</li> <li>The <code>async</code> method uses <code>await</code> without <code>ConfigureAwait</code>.</li> <li>The <code>Task</code> cannot complete in this situation because it only completes when the <code>async</code> method is finished; the <code>async</code> method cannot complete because it is attempting to schedule its continuation to the <code>SynchronizationContext</code>, and WinForms/WPF/SL/ASP.NET will not allow the continuation to run because the synchronous method is already running in that context.</li> </ol> <p>This is one reason why it's a good idea to use <code>ConfigureAwait(false)</code> within every <code>async</code> method as much as possible.</p> <p><strong>Solution C</strong></p> <p><code>AsyncContext.RunTask</code> won't work in every scenario. For example, if the <code>async</code> method awaits something that requires a UI event to complete, then you'll deadlock even with the nested context. In that case, you could start the <code>async</code> method on the thread pool:</p> <pre><code>var task = Task.Run(async () =&gt; await MyAsyncMethod()); var result = task.WaitAndUnwrapException(); </code></pre> <p>However, this solution requires a <code>MyAsyncMethod</code> that will work in the thread pool context. So it can't update UI elements or access the ASP.NET request context. And in that case, you may as well add <code>ConfigureAwait(false)</code> to its <code>await</code> statements, and use solution A.</p> <p><strong>Update, 2019-05-01:</strong> The current &quot;least-worst practices&quot; are in an <a href="https://msdn.microsoft.com/en-us/magazine/mt238404.aspx" rel="noreferrer">MSDN article here</a>.</p>
{ "question_id": 9343594, "question_date": "2012-02-18T17:49:28.053Z", "question_score": 1224, "tags": "c#|async-await", "answer_id": 9343733, "answer_date": "2012-02-18T18:06:00.493Z", "answer_score": 989 }
Please answer the following Stack Overflow question: Title: How can I generate random alphanumeric strings? <p>How can I generate a random 8 character alphanumeric string in C#?</p>
<p>I heard LINQ is the new black, so here's my attempt using LINQ:</p> <pre><code>private static Random random = new Random(); public static string RandomString(int length) { const string chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;; return new string(Enumerable.Repeat(chars, length) .Select(s =&gt; s[random.Next(s.Length)]).ToArray()); } </code></pre> <p><em>(Note: The use of the <code>Random</code> class makes this <strong>unsuitable for anything security related</strong>, such as creating passwords or tokens. Use the <code>RNGCryptoServiceProvider</code> class if you need a strong random number generator.)</em></p>
{ "question_id": 1344221, "question_date": "2009-08-27T23:07:24.883Z", "question_score": 1224, "tags": "c#|.net|random", "answer_id": 1344242, "answer_date": "2009-08-27T23:13:50.157Z", "answer_score": 2051 }
Please answer the following Stack Overflow question: Title: Converting 'ArrayList<String> to 'String[]' in Java <p>How might I convert an <code>ArrayList&lt;String&gt;</code> object to a <code>String[]</code> array in Java?</p>
<pre><code>List&lt;String&gt; list = ..; String[] array = list.toArray(new String[0]); </code></pre> <p>For example:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(); //add some stuff list.add("android"); list.add("apple"); String[] stringArray = list.toArray(new String[0]); </code></pre> <p>The <code>toArray()</code> method without passing any argument returns <code>Object[]</code>. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.</p> <p><strong>Important update</strong>: Originally the code above used <code>new String[list.size()]</code>. However, <a href="http://shipilev.net/blog/2016/arrays-wisdom-ancients/" rel="noreferrer">this blogpost</a> reveals that due to JVM optimizations, using <code>new String[0]</code> is better now.</p>
{ "question_id": 4042434, "question_date": "2010-10-28T11:30:53.847Z", "question_score": 1224, "tags": "java|arrays|string|arraylist|collections", "answer_id": 4042464, "answer_date": "2010-10-28T11:34:52.060Z", "answer_score": 2015 }
Please answer the following Stack Overflow question: Title: Git push rejected after feature branch rebase <p>OK, I thought this was a simple git scenario, what am I missing?</p> <p>I have a <code>master</code> branch and a <code>feature</code> branch. I do some work on <code>master</code>, some on <code>feature</code>, and then some more on <code>master</code>. I end up with something like this (lexicographic order implies the order of commits):</p> <pre><code>A--B--C------F--G (master) \ D--E (feature) </code></pre> <p>I have no problem to <code>git push origin master</code> to keep the remote <code>master</code> updated, nor with <code>git push origin feature</code> (when on <code>feature</code>) to maintain a remote backup for my <code>feature</code> work. Up until now, we're good.</p> <p>But now I want to rebase <code>feature</code> on top of the <code>F--G</code> commits on master, so I <code>git checkout feature</code> and <code>git rebase master</code>. Still good. Now we have:</p> <pre><code>A--B--C------F--G (master) \ D'--E' (feature) </code></pre> <p><strong>Problem:</strong> the moment I want to backup the new rebased <code>feature</code> branched with <code>git push origin feature</code>, <strong>the push is rejected</strong> since the tree has changed due to the rebasing. This can only be solved with <code>git push --force origin feature</code>.</p> <p>I hate using <code>--force</code> without being sure I need it. So, do I need it? Does the rebasing <em>necessarily</em> imply that the next <code>push</code> should be <code>--force</code>ful?</p> <p>This feature branch is not shared with any other devs, so I have no problem <em>de facto</em> with the force push, I'm not going to lose any data, the question is more conceptual.</p>
<p>The problem is that <code>git push</code> assumes that remote branch can be fast-forwarded to your local branch, that is that all the difference between local and remote branches is in local having some new commits at the end like that:</p> <pre><code>Z--X--R &lt;- origin/some-branch (can be fast-forwarded to Y commit) \ T--Y &lt;- some-branch </code></pre> <p>When you perform <code>git rebase</code> commits D and E are applied to new base and new commits are created. That means after rebase you have something like that:</p> <pre><code>A--B--C------F--G--D'--E' &lt;- feature-branch \ D--E &lt;- origin/feature-branch </code></pre> <p>In that situation remote branch can't be fast-forwarded to local. Though, theoretically local branch can be merged into remote (obviously you don't need it in that case), but as <code>git push</code> performs only fast-forward merges it throws and error.</p> <p>And what <code>--force</code> option does is just ignoring state of remote branch and setting it to the commit you're pushing into it. So <code>git push --force origin feature-branch</code> simply overrides <code>origin/feature-branch</code> with local <code>feature-branch</code>.</p> <p>In my opinion, rebasing feature branches on <code>master</code> and force-pushing them back to remote repository is OK as long as you're the only one who works on that branch.</p>
{ "question_id": 8939977, "question_date": "2012-01-20T10:29:27.330Z", "question_score": 1223, "tags": "git", "answer_id": 8940299, "answer_date": "2012-01-20T10:55:34.163Z", "answer_score": 913 }
Please answer the following Stack Overflow question: Title: How do I get file creation and modification date/times? <p>What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?</p>
<p>In Python 3.4 and above, you can use the object oriented <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer">pathlib module</a> interface which includes wrappers for much of the os module. Here is an example of getting the file stats.</p> <pre><code>&gt;&gt;&gt; import pathlib &gt;&gt;&gt; fname = pathlib.Path('test.py') &gt;&gt;&gt; assert fname.exists(), f'No such file: {fname}' # check that the file exists &gt;&gt;&gt; print(fname.stat()) os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272) </code></pre> <p>For more information about what <code>os.stat_result</code> contains, refer to <a href="https://docs.python.org/3/library/os.html#os.stat_result" rel="noreferrer">the documentation</a>. For the modification time you want <code>fname.stat().st_mtime</code>:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc) &gt;&gt;&gt; print(mtime) datetime.datetime(2018, 10, 17, 10, 49, 0, 249980) </code></pre> <p>If you want the creation time on Windows, or the most recent metadata change on Unix, you would use <code>fname.stat().st_ctime</code>:</p> <pre><code>&gt;&gt;&gt; ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc) &gt;&gt;&gt; print(ctime) datetime.datetime(2018, 4, 11, 16, 57, 52, 151953) </code></pre> <p><a href="https://realpython.com/python-pathlib/" rel="noreferrer">This article</a> has more helpful info and examples for the pathlib module.</p>
{ "question_id": 237079, "question_date": "2008-10-25T21:54:56.553Z", "question_score": 1222, "tags": "python|file", "answer_id": 52858040, "answer_date": "2018-10-17T15:05:36.947Z", "answer_score": 158 }
Please answer the following Stack Overflow question: Title: How to catch and print the full exception traceback without halting/exiting the program? <p>I want to catch and log exceptions without exiting, e.g.,</p> <pre><code>try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, # not just the exception name and details </code></pre> <p>I want to print the exact same output that is printed when the exception is raised without the try/except intercepting the exception, and I do <em>not</em> want it to exit my program.</p>
<p>Some other answer have already pointed out the <a href="http://docs.python.org/3/library/traceback.html">traceback</a> module.</p> <p>Please notice that with <code>print_exc</code>, in some corner cases, you will not obtain what you would expect. In Python 2.x:</p> <pre><code>import traceback try: raise TypeError("Oups!") except Exception, err: try: raise TypeError("Again !?!") except: pass traceback.print_exc() </code></pre> <p>...will display the traceback of the <em>last</em> exception:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "e.py", line 7, in &lt;module&gt; raise TypeError("Again !?!") TypeError: Again !?! </code></pre> <p><strong>If you really need to access the original <em>traceback</em></strong> one solution is to cache the <em>exception infos</em> as returned from <a href="https://docs.python.org/2/library/sys.html#sys.exc_info"><code>exc_info</code></a> in a local variable and display it using <a href="https://docs.python.org/2/library/traceback.html#traceback.print_exception"><code>print_exception</code></a>:</p> <pre><code>import traceback import sys try: raise TypeError("Oups!") except Exception, err: try: exc_info = sys.exc_info() # do you usefull stuff here # (potentially raising an exception) try: raise TypeError("Again !?!") except: pass # end of useful stuff finally: # Display the *original* exception traceback.print_exception(*exc_info) del exc_info </code></pre> <p>Producing:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "t.py", line 6, in &lt;module&gt; raise TypeError("Oups!") TypeError: Oups! </code></pre> <p>Few pitfalls with this though:</p> <ul> <li><p>From the doc of <a href="https://docs.python.org/2/library/sys.html#sys.exc_info"><code>sys_info</code></a>:</p> <blockquote> <p>Assigning the traceback return value to a local variable in a function that is handling an exception will cause a <strong>circular reference</strong>. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] <strong>If you do need the traceback, make sure to delete it after use</strong> (best done with a try ... finally statement)</p> </blockquote></li> <li><p>but, from the same doc:</p> <blockquote> <p><strong>Beginning with Python 2.2, such cycles are automatically reclaimed</strong> when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.</p> </blockquote></li> </ul> <hr> <p>On the other hand, by allowing you to access the traceback <em>associated with</em> an exception, Python 3 produce a less surprising result:</p> <pre><code>import traceback try: raise TypeError("Oups!") except Exception as err: try: raise TypeError("Again !?!") except: pass traceback.print_tb(err.__traceback__) </code></pre> <p>... will display:</p> <pre class="lang-none prettyprint-override"><code> File "e3.py", line 4, in &lt;module&gt; raise TypeError("Oups!") </code></pre>
{ "question_id": 3702675, "question_date": "2010-09-13T17:03:30.953Z", "question_score": 1221, "tags": "python|exception|try-catch|traceback", "answer_id": 16946886, "answer_date": "2013-06-05T18:05:51.730Z", "answer_score": 797 }
Please answer the following Stack Overflow question: Title: Negative matching using grep (match lines that do not contain foo) <p>How do I match all lines not matching a particular pattern using <code>grep</code>? I tried this:</p> <pre><code>grep '[^foo]' </code></pre>
<p><code>grep -v</code> is your friend:</p> <pre><code>grep --help | grep invert </code></pre> <blockquote> <p>-v, --invert-match select non-matching lines</p> </blockquote> <p>Also check out the related <code>-L</code> (the complement of <code>-l</code>).</p> <blockquote> <p>-L, --files-without-match only print FILE names containing no match</p> </blockquote>
{ "question_id": 3548453, "question_date": "2010-08-23T14:24:14.083Z", "question_score": 1221, "tags": "regex|grep", "answer_id": 3548465, "answer_date": "2010-08-23T14:25:40.617Z", "answer_score": 2164 }
Please answer the following Stack Overflow question: Title: How to execute a JavaScript function when I have its name as a string <p>I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?</p> <p>Depending on the circumstances, I may need to pass various arguments into the method too.</p> <p>Some of the functions may take the form of <code>namespace.namespace.function(args[...])</code>.</p>
<p>Don't use <code>eval</code> unless you <em>absolutely, positively</em> have no other choice.</p> <p>As has been mentioned, using something like this would be the best way to do it:</p> <pre><code>window["functionName"](arguments); </code></pre> <p>That, however, will not work with a namespace'd function:</p> <pre><code>window["My.Namespace.functionName"](arguments); // fail </code></pre> <p>This is how you would do that:</p> <pre><code>window["My"]["Namespace"]["functionName"](arguments); // succeeds </code></pre> <p>In order to make that easier and provide some flexibility, here is a convenience function:</p> <pre><code>function executeFunctionByName(functionName, context /*, args */) { var args = Array.prototype.slice.call(arguments, 2); var namespaces = functionName.split("."); var func = namespaces.pop(); for(var i = 0; i &lt; namespaces.length; i++) { context = context[namespaces[i]]; } return context[func].apply(context, args); } </code></pre> <p>You would call it like so:</p> <pre><code>executeFunctionByName("My.Namespace.functionName", window, arguments); </code></pre> <p>Note, you can pass in whatever context you want, so this would do the same as above:</p> <pre><code>executeFunctionByName("Namespace.functionName", My, arguments); </code></pre>
{ "question_id": 359788, "question_date": "2008-12-11T15:47:10.663Z", "question_score": 1221, "tags": "javascript", "answer_id": 359910, "answer_date": "2008-12-11T16:15:36.067Z", "answer_score": 1607 }
Please answer the following Stack Overflow question: Title: How to deal with SettingWithCopyWarning in Pandas <h2>Background</h2> <p>I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:</p> <pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE </code></pre> <p>I want to know what exactly it means? Do I need to change something?</p> <p>How should I suspend the warning if I insist to use <code>quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE</code>?</p> <h2>The function that gives errors</h2> <pre><code>def _decode_stock_quote(list_of_150_stk_str): &quot;&quot;&quot;decode the webpage and return dataframe&quot;&quot;&quot; from cStringIO import StringIO str_of_all = &quot;&quot;.join(list_of_150_stk_str) quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64} quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True) quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]] quote_df['TClose'] = quote_df['TPrice'] quote_df['RT'] = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1) quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19) quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312') quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10]) return quote_df </code></pre> <h2>More error messages</h2> <pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10]) </code></pre>
<p>The <code>SettingWithCopyWarning</code> was created to flag potentially confusing &quot;chained&quot; assignments, such as the following, which does not always work as expected, particularly when the first selection returns a <em>copy</em>. [see <a href="https://github.com/pydata/pandas/pull/5390" rel="noreferrer">GH5390</a> and <a href="https://github.com/pydata/pandas/issues/5597" rel="noreferrer">GH5597</a> for background discussion.]</p> <pre><code>df[df['A'] &gt; 2]['B'] = new_val # new_val not set in df </code></pre> <p>The warning offers a suggestion to rewrite as follows:</p> <pre><code>df.loc[df['A'] &gt; 2, 'B'] = new_val </code></pre> <p>However, this doesn't fit your usage, which is equivalent to:</p> <pre><code>df = df[df['A'] &gt; 2] df['B'] = new_val </code></pre> <p>While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy" rel="noreferrer">docs on indexing</a>, if you'd like to read further. You can safely disable this new warning with the following assignment.</p> <pre><code>import pandas as pd pd.options.mode.chained_assignment = None # default='warn' </code></pre> <hr /> <h2>Other Resources</h2> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="noreferrer">pandas User Guide: Indexing and selecting data</a></li> <li><a href="https://jakevdp.github.io/PythonDataScienceHandbook/03.02-data-indexing-and-selection.html" rel="noreferrer">Python Data Science Handbook: Data Indexing and Selection</a></li> <li><a href="https://realpython.com/pandas-settingwithcopywarning/" rel="noreferrer">Real Python: SettingWithCopyWarning in Pandas: Views vs Copies</a></li> <li><a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="noreferrer">Dataquest: SettingwithCopyWarning: How to Fix This Warning in Pandas</a></li> <li><a href="https://towardsdatascience.com/explaining-the-settingwithcopywarning-in-pandas-ebc19d799d25" rel="noreferrer">Towards Data Science: Explaining the SettingWithCopyWarning in pandas</a></li> </ul>
{ "question_id": 20625582, "question_date": "2013-12-17T03:48:02.570Z", "question_score": 1220, "tags": "python|pandas|dataframe|chained-assignment", "answer_id": 20627316, "answer_date": "2013-12-17T06:20:23.940Z", "answer_score": 1435 }
Please answer the following Stack Overflow question: Title: How do I get ASP.NET Web API to return JSON instead of XML using Chrome? <p>Using the newer <strong>ASP.NET Web API</strong>, in <strong>Chrome</strong> I am seeing XML - how can I change it to request <strong>JSON</strong> so I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?</p>
<h4>Note: Read the comments of this answer, it can produce a XSS Vulnerability if you are using the default error handing of WebAPI</h4> <p>I just add the following in <code>App_Start / WebApiConfig.cs</code> class in my MVC <strong>Web API</strong> project.</p> <pre><code>config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTypeHeaderValue(&quot;text/html&quot;) ); </code></pre> <p>That makes sure you get JSON on most queries, but you can get <code>XML</code> when you send <code>text/xml</code>.</p> <p>If you need to have the response <code>Content-Type</code> as <code>application/json</code> please check <a href="https://stackoverflow.com/a/20556625/287145">Todd's answer below</a>.</p> <p><code>NameSpace</code> is using <code>System.Net.Http.Headers</code>.</p>
{ "question_id": 9847564, "question_date": "2012-03-23T23:04:12.480Z", "question_score": 1220, "tags": "json|google-chrome|asp.net-web-api", "answer_id": 13277616, "answer_date": "2012-11-07T20:25:25.857Z", "answer_score": 1818 }
Please answer the following Stack Overflow question: Title: How does Python's super() work with multiple inheritance? <p>How does <code>super()</code> work with multiple inheritance? For example, given:</p> <pre><code>class First(object): def __init__(self): print &quot;first&quot; class Second(object): def __init__(self): print &quot;second&quot; class Third(First, Second): def __init__(self): super(Third, self).__init__() print &quot;that's it&quot; </code></pre> <p>Which parent method of <code>Third</code> does <code>super().__init__</code> refer to? Can I choose which runs?</p> <p>I know it has something to do with method resolution order (<a href="http://en.wikipedia.org/wiki/C3_linearization" rel="noreferrer">MRO</a>).</p>
<p>This is detailed with a reasonable amount of detail by Guido himself in his blog post <a href="http://python-history.blogspot.com/2010/06/method-resolution-order.html" rel="noreferrer">Method Resolution Order</a> (including two earlier attempts).</p> <p>In your example, <code>Third()</code> will call <code>First.__init__</code>. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for <code>__init__</code>. So, if you define</p> <pre><code>class Third(First, Second): ... </code></pre> <p>Python will start by looking at <code>First</code>, and, if <code>First</code> doesn't have the attribute, then it will look at <code>Second</code>.</p> <p>This situation becomes more complex when inheritance starts crossing paths (for example if <code>First</code> inherited from <code>Second</code>). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.</p> <p>So, for instance, if you had:</p> <pre><code>class First(object): def __init__(self): print &quot;first&quot; class Second(First): def __init__(self): print &quot;second&quot; class Third(First): def __init__(self): print &quot;third&quot; class Fourth(Second, Third): def __init__(self): super(Fourth, self).__init__() print &quot;that's it&quot; </code></pre> <p>the MRO would be <code>[Fourth, Second, Third, First].</code></p> <p>By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.</p> <p>Example of an ambiguous MRO:</p> <pre><code>class First(object): def __init__(self): print &quot;first&quot; class Second(First): def __init__(self): print &quot;second&quot; class Third(First, Second): def __init__(self): print &quot;third&quot; </code></pre> <p>Should <code>Third</code>'s MRO be <code>[First, Second]</code> or <code>[Second, First]</code>? There's no obvious expectation, and Python will raise an error:</p> <pre><code>TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases Second, First </code></pre> <p>Why do the examples above lack <code>super()</code> calls? The point of the examples is to show how the MRO is constructed. They are <strong>not</strong> intended to print <code>&quot;first\nsecond\third&quot;</code> or whatever. You can – and should, of course, play around with the example, add <code>super()</code> calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:</p> <pre><code>&gt;&gt;&gt; Fourth.__mro__ (&lt;class '__main__.Fourth'&gt;, &lt;class '__main__.Second'&gt;, &lt;class '__main__.Third'&gt;, &lt;class '__main__.First'&gt;, &lt;type 'object'&gt;) </code></pre>
{ "question_id": 3277367, "question_date": "2010-07-18T21:40:25.987Z", "question_score": 1220, "tags": "python|multiple-inheritance", "answer_id": 3277407, "answer_date": "2010-07-18T21:52:52.173Z", "answer_score": 870 }
Please answer the following Stack Overflow question: Title: How to make a class JSON serializable <p>How to make a Python class serializable?</p> <pre><code>class FileItem: def __init__(self, fname): self.fname = fname </code></pre> <p>Attempt to serialize to JSON:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; x = FileItem('/foo/bar') &gt;&gt;&gt; json.dumps(x) TypeError: Object of type 'FileItem' is not JSON serializable </code></pre>
<p>Do you have an idea about the expected output? For example, will this do?</p> <pre><code>&gt;&gt;&gt; f = FileItem("/foo/bar") &gt;&gt;&gt; magic(f) '{"fname": "/foo/bar"}' </code></pre> <p>In that case you can merely call <code>json.dumps(f.__dict__)</code>. </p> <p>If you want more customized output then you will have to subclass <a href="https://docs.python.org/library/json.html#json.JSONEncoder" rel="noreferrer"><code>JSONEncoder</code></a> and implement your own custom serialization. </p> <p>For a trivial example, see below.</p> <pre><code>&gt;&gt;&gt; from json import JSONEncoder &gt;&gt;&gt; class MyEncoder(JSONEncoder): def default(self, o): return o.__dict__ &gt;&gt;&gt; MyEncoder().encode(f) '{"fname": "/foo/bar"}' </code></pre> <p>Then you pass this class into the <a href="https://docs.python.org/library/json.html#json.dumps" rel="noreferrer"><code>json.dumps()</code></a> method as <code>cls</code> kwarg:</p> <pre><code>json.dumps(cls=MyEncoder) </code></pre> <p>If you also want to decode then you'll have to supply a custom <code>object_hook</code> to the <a href="https://docs.python.org/library/json.html#json.JSONDecoder" rel="noreferrer"><code>JSONDecoder</code></a> class. For example:</p> <pre><code>&gt;&gt;&gt; def from_json(json_object): if 'fname' in json_object: return FileItem(json_object['fname']) &gt;&gt;&gt; f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}') &gt;&gt;&gt; f &lt;__main__.FileItem object at 0x9337fac&gt; &gt;&gt;&gt; </code></pre>
{ "question_id": 3768895, "question_date": "2010-09-22T11:52:19.813Z", "question_score": 1219, "tags": "python|json|serialization", "answer_id": 3768975, "answer_date": "2010-09-22T12:02:18.377Z", "answer_score": 681 }
Please answer the following Stack Overflow question: Title: Sending command line arguments to npm script <p>The <code>scripts</code> portion of my <code>package.json</code> currently looks like this:</p> <pre class="lang-js prettyprint-override"><code>"scripts": { "start": "node ./script.js server" } </code></pre> <p>...which means I can run <code>npm start</code> to start the server. So far so good.</p> <p>However, I would like to be able to run something like <code>npm start 8080</code> and have the argument(s) passed to <code>script.js</code> (e.g. <code>npm start 8080</code> => <code>node ./script.js server 8080</code>). Is this possible?</p>
<h2>npm 2 and newer</h2> <p>It's possible to <a href="https://github.com/npm/npm/pull/5518" rel="noreferrer">pass args to <code>npm run</code></a> since npm 2 (2014). The syntax is as follows:</p> <p><code>npm run &lt;command&gt; [-- &lt;args&gt;]</code></p> <p>Note the <code>--</code> separator, used to separate the params passed to <code>npm</code> command itself, and the params passed to your script.</p> <p>With the example <code>package.json</code>:</p> <pre><code> &quot;scripts&quot;: { &quot;grunt&quot;: &quot;grunt&quot;, &quot;server&quot;: &quot;node server.js&quot; } </code></pre> <p>here's how to pass the params to those scripts:</p> <pre class="lang-sh prettyprint-override"><code>npm run grunt -- task:target // invokes `grunt task:target` npm run server -- --port=1337 // invokes `node server.js --port=1337` </code></pre> <p><em>Note</em>: <strong>If your param does not start with <code>-</code> or <code>--</code>, then having an explicit <code>--</code> separator is not needed; but it's better to do it anyway for clarity.</strong></p> <pre class="lang-sh prettyprint-override"><code>npm run grunt task:target // invokes `grunt task:target` </code></pre> <p>Note below the difference in behavior (<code>test.js</code> has <code>console.log(process.argv)</code>): the params which start with <code>-</code> or <code>--</code> <em>are passed to <code>npm</code> and not to the script</em>, and are silently swallowed there.</p> <pre class="lang-sh prettyprint-override"><code>$ npm run test foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar'] $ npm run test -foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js'] $ npm run test --foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js'] $ npm run test -- foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', 'foobar'] $ npm run test -- -foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '-foobar'] $ npm run test -- --foobar ['C:\\Program Files\\nodejs\\node.exe', 'C:\\git\\myrepo\\test.js', '--foobar'] </code></pre> <p>The difference is clearer when you use a param <em>actually used by npm</em>:</p> <pre><code>$ npm test --help // this is disguised `npm --help test` npm test [-- &lt;args&gt;] aliases: tst, t </code></pre> <p>To get the parameter value, <a href="https://stackoverflow.com/q/4351521/245966">see this question</a>. For reading named parameters, it's probably best to use a parsing library like <a href="https://github.com/yargs/yargs" rel="noreferrer">yargs</a> or <a href="https://github.com/substack/minimist" rel="noreferrer">minimist</a>; nodejs exposes <code>process.argv</code> globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).</p> <hr /> <p><s><strong>Edit 2013.10.03:</strong> It's not currently possible directly. But there's a related <a href="https://github.com/isaacs/npm/issues/3494" rel="noreferrer">GitHub issue opened on <code>npm</code></a> to implement the behavior you're asking for. Seems the consensus is to have this implemented, but it depends on another issue being solved before.</s></p> <hr /> <p><strong>Original answer (2013.01):</strong> As a some kind of workaround (though not very handy), you can do as follows:</p> <p>Say your package name from <code>package.json</code> is <code>myPackage</code> and you have also</p> <pre><code>&quot;scripts&quot;: { &quot;start&quot;: &quot;node ./script.js server&quot; } </code></pre> <p>Then add in <code>package.json</code>:</p> <pre><code>&quot;config&quot;: { &quot;myPort&quot;: &quot;8080&quot; } </code></pre> <p>And in your <code>script.js</code>:</p> <pre><code>// defaulting to 8080 in case if script invoked not via &quot;npm run-script&quot; but directly var port = process.env.npm_package_config_myPort || 8080 </code></pre> <p>That way, by default <code>npm start</code> will use 8080. You can however configure it (the value will be stored by <code>npm</code> in its internal storage):</p> <pre><code>npm config set myPackage:myPort 9090 </code></pre> <p>Then, when invoking <code>npm start</code>, 9090 will be used (the default from <code>package.json</code> gets overridden).</p>
{ "question_id": 11580961, "question_date": "2012-07-20T14:02:36.277Z", "question_score": 1219, "tags": "javascript|node.js|npm", "answer_id": 14404223, "answer_date": "2013-01-18T17:20:59.277Z", "answer_score": 1677 }
Please answer the following Stack Overflow question: Title: How to kill a process running on particular port in Linux? <p>I tried to close the tomcat using <code>./shutdown.sh</code> from tomcat <code>/bin</code> directory. But found that the server was not closed properly. And thus I was unable to restart<br>My tomcat is running on port <code>8080</code>.</p> <p>I want to kill the tomcat process running on <code>8080</code>. I first want to have the list of processes running on a specific port (8080) in order to select which process to kill.</p>
<p>Use the command</p> <pre><code> sudo netstat -plten |grep java </code></pre> <p>used <code>grep java</code> as <code>tomcat</code> uses <code>java</code> as their processes.</p> <p>It will show the list of processes with port number and process id</p> <pre><code>tcp6 0 0 :::8080 :::* LISTEN 1000 30070621 16085/java </code></pre> <p>the number before <code>/java</code> is a process id. Now use <code>kill</code> command to kill the process</p> <pre><code>kill -9 16085 </code></pre> <p><code>-9</code> implies the process will be killed forcefully.</p>
{ "question_id": 11583562, "question_date": "2012-07-20T16:39:17.320Z", "question_score": 1218, "tags": "linux|unix|port|kill-process", "answer_id": 11583564, "answer_date": "2012-07-20T16:39:17.320Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: What is a correct MIME type for .docx, .pptx, etc.? <p>For older *.doc documents, this was enough:</p> <pre><code>header(&quot;Content-Type: application/msword&quot;); </code></pre> <p>What MIME type should I use for new .docx documents? Also, for pptx and xlsx documents?</p>
<p>Here are the correct Microsoft Office MIME types for HTTP content streaming:</p> <pre><code>Extension MIME Type .doc application/msword .dot application/msword .docx application/vnd.openxmlformats-officedocument.wordprocessingml.document .dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template .docm application/vnd.ms-word.document.macroEnabled.12 .dotm application/vnd.ms-word.template.macroEnabled.12 .xls application/vnd.ms-excel .xlt application/vnd.ms-excel .xla application/vnd.ms-excel .xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template .xlsm application/vnd.ms-excel.sheet.macroEnabled.12 .xltm application/vnd.ms-excel.template.macroEnabled.12 .xlam application/vnd.ms-excel.addin.macroEnabled.12 .xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12 .ppt application/vnd.ms-powerpoint .pot application/vnd.ms-powerpoint .pps application/vnd.ms-powerpoint .ppa application/vnd.ms-powerpoint .pptx application/vnd.openxmlformats-officedocument.presentationml.presentation .potx application/vnd.openxmlformats-officedocument.presentationml.template .ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow .ppam application/vnd.ms-powerpoint.addin.macroEnabled.12 .pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12 .potm application/vnd.ms-powerpoint.template.macroEnabled.12 .ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12 .mdb application/vnd.ms-access </code></pre> <p>For further details check out this <a href="https://docs.microsoft.com/en-us/previous-versions/office/office-2007-resource-kit/ee309278%28v=office.12%29" rel="noreferrer">TechNet article</a> and this <a href="https://web.archive.org/web/20160215155254/http://blogs.msdn.com:80/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx" rel="noreferrer">blog post</a>.</p>
{ "question_id": 4212861, "question_date": "2010-11-18T08:25:43.570Z", "question_score": 1218, "tags": "excel|ms-word|ms-office|powerpoint|mime-types", "answer_id": 4212908, "answer_date": "2010-11-18T08:32:29.577Z", "answer_score": 2860 }
Please answer the following Stack Overflow question: Title: Replace one substring for another string in shell script <p>I have &quot;I love Suzi and Marry&quot; and I want to change &quot;Suzi&quot; to &quot;Sara&quot;.</p> <pre><code>firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; </code></pre> <p>Desired result:</p> <pre><code>firstString=&quot;I love Sara and Marry&quot; </code></pre>
<p>To replace the <em>first</em> occurrence of a pattern with a given string, use <code>${<em>parameter</em>/<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>#!/bin/bash firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; echo &quot;${firstString/Suzi/&quot;$secondString&quot;}&quot; # prints 'I love Sara and Marry' </code></pre> <p>To replace <em>all</em> occurrences, use <code>${<em>parameter</em>//<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>message='The secret code is 12345' echo &quot;${message//[0-9]/X}&quot; # prints 'The secret code is XXXXX' </code></pre> <p>(This is documented in <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion" rel="noreferrer">the <em>Bash Reference Manual</em>, §3.5.3 &quot;Shell Parameter Expansion&quot;</a>.)</p> <p>Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer"><em>The Open Group Technical Standard Base Specifications, Issue 7</em>, the <em>Shell &amp; Utilities</em> volume, §2.6.2 &quot;Parameter Expansion&quot;</a>.</p>
{ "question_id": 13210880, "question_date": "2012-11-03T16:01:23.283Z", "question_score": 1217, "tags": "bash|shell", "answer_id": 13210909, "answer_date": "2012-11-03T16:05:06.823Z", "answer_score": 2045 }
Please answer the following Stack Overflow question: Title: Remove all child elements of a DOM node in JavaScript <p>How would I go about removing all of the child elements of a DOM node in JavaScript?</p> <p>Say I have the following (ugly) HTML:</p> <pre><code>&lt;p id="foo"&gt; &lt;span&gt;hello&lt;/span&gt; &lt;div&gt;world&lt;/div&gt; &lt;/p&gt; </code></pre> <p>And I grab the node I want like so:</p> <pre><code>var myNode = document.getElementById("foo"); </code></pre> <p>How could I remove the children of <code>foo</code> so that just <code>&lt;p id="foo"&gt;&lt;/p&gt;</code> is left?</p> <p>Could I just do:</p> <pre><code>myNode.childNodes = new Array(); </code></pre> <p>or should I be using some combination of <code>removeElement</code>?</p> <p>I'd like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.</p>
<h2>Option 1 A: Clearing <code>innerHTML</code>.</h2> <ul> <li>This approach is simple, but might not be suitable for high-performance applications because it invokes the browser's HTML parser (though browsers <em>may</em> optimize for the case where the value is an empty string).</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>doFoo.onclick = () =&gt; { const myNode = document.getElementById("foo"); myNode.innerHTML = ''; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"&gt; &lt;span&gt;Hello&lt;/span&gt; &lt;/div&gt; &lt;button id='doFoo'&gt;Remove via innerHTML&lt;/button&gt;</code></pre> </div> </div> </p> <h2>Option 1 B: Clearing <code>textContent</code></h2> <ul> <li>As above, but use <code>.textContent</code>. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent" rel="noreferrer">According to MDN</a> this will be faster than <code>innerHTML</code> as browsers won't invoke their HTML parsers and will instead immediately replace all children of the element with a single <code>#text</code> node.</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>doFoo.onclick = () =&gt; { const myNode = document.getElementById("foo"); myNode.textContent = ''; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"&gt; &lt;span&gt;Hello&lt;/span&gt; &lt;/div&gt; &lt;button id='doFoo'&gt;Remove via textContent&lt;/button&gt;</code></pre> </div> </div> </p> <h2>Option 2 A: Looping to remove every <code>lastChild</code>:</h2> <ul> <li>An earlier edit to this answer used <code>firstChild</code>, but this is updated to use <code>lastChild</code> as in computer-science, <em>in general</em>, it's significantly faster to remove the <em>last</em> element of a collection than it is to remove the first element (depending on how the collection is implemented).</li> <li>The loop continues to check for <code>firstChild</code> <em>just in case</em> it's faster to check for <code>firstChild</code> than <code>lastChild</code> (e.g. if the element list is implemented as a directed linked-list by the UA).</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>doFoo.onclick = () =&gt; { const myNode = document.getElementById("foo"); while (myNode.firstChild) { myNode.removeChild(myNode.lastChild); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"&gt; &lt;span&gt;Hello&lt;/span&gt; &lt;/div&gt; &lt;button id='doFoo'&gt;Remove via lastChild-loop&lt;/button&gt;</code></pre> </div> </div> </p> <h2>Option 2 B: Looping to remove every <code>lastElementChild</code>:</h2> <ul> <li>This approach preserves all non-<code>Element</code> (namely <code>#text</code> nodes and <code>&lt;!-- comments --&gt;</code> ) children of the parent (but not their descendants) - and this may be desirable in your application (e.g. some templating systems that use inline HTML comments to store template instructions).</li> <li>This approach wasn't used until recent years as Internet Explorer only added support for <code>lastElementChild</code> in IE9.</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>doFoo.onclick = () =&gt; { const myNode = document.getElementById("foo"); while (myNode.lastElementChild) { myNode.removeChild(myNode.lastElementChild); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"&gt; &lt;!-- This comment won't be removed --&gt; &lt;span&gt;Hello &lt;!-- This comment WILL be removed --&gt;&lt;/span&gt; &lt;!-- But this one won't. --&gt; &lt;/div&gt; &lt;button id='doFoo'&gt;Remove via lastElementChild-loop&lt;/button&gt;</code></pre> </div> </div> </p> <h2>Bonus: <code>Element.clearChildren</code> monkey-patch:</h2> <ul> <li>We can add a new method-property to the <code>Element</code> prototype in JavaScript to simplify invoking it to just <code>el.clearChildren()</code> (where <code>el</code> is <em>any</em> HTML element object).</li> <li>(Strictly speaking this is a monkey-patch, not a polyfill, as this is not a standard DOM feature or missing feature. Note that monkey-patching is rightfully discouraged in many situations.)</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if( typeof Element.prototype.clearChildren === 'undefined' ) { Object.defineProperty(Element.prototype, 'clearChildren', { configurable: true, enumerable: false, value: function() { while(this.firstChild) this.removeChild(this.lastChild); } }); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='foo' style="height: 100px; width: 100px; border: 1px solid black;"&gt; &lt;span&gt;Hello &lt;!-- This comment WILL be removed --&gt;&lt;/span&gt; &lt;/div&gt; &lt;button onclick="this.previousElementSibling.clearChildren()"&gt;Remove via monkey-patch&lt;/button&gt;</code></pre> </div> </div> </p>
{ "question_id": 3955229, "question_date": "2010-10-17T20:51:00.170Z", "question_score": 1217, "tags": "javascript|dom", "answer_id": 3955238, "answer_date": "2010-10-17T20:52:38.077Z", "answer_score": 2154 }
Please answer the following Stack Overflow question: Title: How do I encode and decode a base64 string? <ol> <li><p>How do I return a base64 encoded string given a string?</p></li> <li><p>How do I decode a base64 encoded string into a string?</p></li> </ol>
<h3>Encode</h3> <pre><code>public static string Base64Encode(string plainText) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } </code></pre> <h3>Decode</h3> <pre><code>public static string Base64Decode(string base64EncodedData) { var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } </code></pre>
{ "question_id": 11743160, "question_date": "2012-07-31T15:06:24.827Z", "question_score": 1217, "tags": "c#|base64", "answer_id": 11743162, "answer_date": "2012-07-31T15:06:24.827Z", "answer_score": 2182 }
Please answer the following Stack Overflow question: Title: How can I initialise a static Map? <p>How would you initialise a static <code>Map</code> in Java?</p> <p>Method one: static initialiser <br> Method two: instance initialiser (anonymous subclass) or some other method?</p> <p>What are the pros and cons of each?</p> <p>Here is an example illustrating the two methods:</p> <pre><code>import java.util.HashMap; import java.util.Map; public class Test { private static final Map&lt;Integer, String&gt; myMap = new HashMap&lt;&gt;(); static { myMap.put(1, "one"); myMap.put(2, "two"); } private static final Map&lt;Integer, String&gt; myMap2 = new HashMap&lt;&gt;(){ { put(1, "one"); put(2, "two"); } }; } </code></pre>
<p>The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.</p> <p>You can create an immutable map using a static initialiser too:</p> <pre><code>public class Test { private static final Map&lt;Integer, String&gt; myMap; static { Map&lt;Integer, String&gt; aMap = ....; aMap.put(1, "one"); aMap.put(2, "two"); myMap = Collections.unmodifiableMap(aMap); } } </code></pre>
{ "question_id": 507602, "question_date": "2009-02-03T15:41:33.080Z", "question_score": 1216, "tags": "java|dictionary|collections|initialization|idioms", "answer_id": 507658, "answer_date": "2009-02-03T15:51:04.420Z", "answer_score": 1179 }
Please answer the following Stack Overflow question: Title: Pipe to/from the clipboard in a Bash script <p>Is it possible to pipe to/from the clipboard in Bash?</p> <p>Whether it is piping to/from a device handle or using an auxiliary application, I can't find anything.</p> <p>For example, if <code>/dev/clip</code> was a device linking to the clipboard we could do:</p> <pre><code>cat /dev/clip # Dump the contents of the clipboard cat foo &gt; /dev/clip # Dump the contents of &quot;foo&quot; into the clipboard </code></pre>
<h1>2018 answer</h1> <p>Use <a href="https://github.com/sindresorhus/clipboard-cli" rel="noreferrer">clipboard-cli</a>. It works with macOS, Windows, Linux, OpenBSD, FreeBSD, and Android without any real issues.</p> <p>Install it with:</p> <pre><code>npm install -g clipboard-cli </code></pre> <p>Then you can do:</p> <pre><code>echo foo | clipboard </code></pre> <p>If you want, you can alias to <code>cb</code> by putting the following in your <code>.bashrc</code>, <code>.bash_profile</code>, or <code>.zshrc</code>:</p> <pre><code>alias cb=clipboard </code></pre>
{ "question_id": 749544, "question_date": "2009-04-14T22:06:47.070Z", "question_score": 1215, "tags": "linux|bash|macos|clipboard", "answer_id": 49679848, "answer_date": "2018-04-05T19:13:22.023Z", "answer_score": 65 }
Please answer the following Stack Overflow question: Title: Center a column using Twitter Bootstrap 3 <p>How do I center a div of one column size within the container (12 columns) in <a href="https://en.wikipedia.org/wiki/Bootstrap_%28front-end_framework%29" rel="noreferrer">Twitter Bootstrap 3</a>?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.centered { background-color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;body class="container"&gt; &lt;div class="col-lg-1 col-offset-6 centered"&gt; &lt;img data-src="holder.js/100x100" alt="" /&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>I want a <code>div</code>, with a class <code>.centered</code> to be centered within the container. I may use a row if there are multiple <code>div</code>s, but for now I just want a <code>div</code> with the size of one column centered within the container (12 columns).</p> <p>I am also not sure the above approach is good enough as the intention is not to offset the <code>div</code> by half. I do not need free spaces outside the <code>div</code> and the contents of the <code>div</code> shrink in proportion. I want to <strong>empty space outside the div to be evenly distributed</strong> (shrink till the container width is equal to one column).</p>
<p>There are two approaches to centering a column <code>&lt;div&gt;</code> in Bootstrap 3:</p> <h2><strong>Approach 1 (offsets):</strong></h2> <p>The first approach uses Bootstrap's own offset classes so it requires no change in markup and no extra CSS. The key is to <strong>set an offset equal to half of the remaining size of the row</strong>. So for example, a column of size 2 would be centered by adding an offset of 5, that's <code>(12-2)/2</code>.</p> <p>In markup this would look like:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-md-2 col-md-offset-5"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now, there's an obvious drawback for this method. <strong>It only works for even column sizes</strong>, so only <code>.col-X-2</code>, <code>.col-X-4</code>, <code>col-X-6</code>, <code>col-X-8</code>, and <code>col-X-10</code> are supported.</p> <hr> <h2><strong>Approach 2 (the old <code>margin:auto</code>)</strong></h2> <p>You can <strong>center any column size</strong> by using the proven <code>margin: 0 auto;</code> technique. You just need to take care of the floating that is added by Bootstrap's grid system. I recommend defining a custom CSS class like the following:</p> <pre><code>.col-centered{ float: none; margin: 0 auto; } </code></pre> <p>Now you can add it to any column size at any screen size, and it will work seamlessly with Bootstrap's responsive layout:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-lg-1 col-centered"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Note:</strong> With both techniques you could skip the <code>.row</code> element and have the column centered inside a <code>.container</code>, but you would notice a minimal difference in the actual column size because of the padding in the container class.</p> <hr> <p><strong>Update:</strong></p> <p>Since v3.0.1 Bootstrap has a built-in class named <code>center-block</code> that uses <code>margin: 0 auto</code>, but is missing <code>float:none</code>, you can add that to your CSS to make it work with the grid system.</p>
{ "question_id": 18153234, "question_date": "2013-08-09T18:24:37.443Z", "question_score": 1214, "tags": "css|twitter-bootstrap|twitter-bootstrap-3|centering", "answer_id": 18153551, "answer_date": "2013-08-09T18:45:24.400Z", "answer_score": 2040 }
Please answer the following Stack Overflow question: Title: Can I hide the HTML5 number input’s spin box? <p>Is there a consistent way across browsers to hide the new spin boxes that some browsers (such as Chrome) render for HTML input of type number? I am looking for a CSS or JavaScript method to prevent the up/down arrows from appearing.</p> <pre><code>&lt;input id="test" type="number"&gt; </code></pre>
<p>This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { /* display: none; &lt;- Crashes Chrome on hover */ -webkit-appearance: none; margin: 0; /* &lt;-- Apparently some margin are still there even though it's hidden */ } input[type=number] { -moz-appearance:textfield; /* Firefox */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="number" step="0.01" /&gt;</code></pre> </div> </div> </p> <p>You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":</p> <p><img src="https://i.stack.imgur.com/QATjk.png" alt="Inspector for input type=number (Chrome)"></p>
{ "question_id": 3790935, "question_date": "2010-09-24T20:58:22.300Z", "question_score": 1214, "tags": "javascript|css|html|input|numbers", "answer_id": 4298216, "answer_date": "2010-11-28T18:17:35.167Z", "answer_score": 1380 }
Please answer the following Stack Overflow question: Title: Converting array to list in Java <p>How do I convert an array to a list in Java?</p> <p>I used the <code>Arrays.asList()</code> but the behavior (and signature) somehow changed from Java SE <a href="http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-142docs-2045554.html" rel="noreferrer">1.4.2</a> (docs now in archive) to <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList-T...-" rel="noreferrer">8</a> and most snippets I found on the web use the 1.4.2 behaviour.</p> <p>For example:</p> <pre><code>int[] numbers = new int[] { 1, 2, 3 }; Arrays.asList(numbers) </code></pre> <ul> <li>on 1.4.2 returns a list containing the elements 1, 2, 3</li> <li>on 1.5.0+ returns a list containing the array 'numbers'</li> </ul> <p>In many cases it should be easy to detect, but sometimes it can slip unnoticed:</p> <pre><code>Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1); </code></pre>
<p>In your example, it is because you can't have a List of a primitive type. In other words, <code>List&lt;int&gt;</code> is not possible.</p> <p>You can, however, have a <code>List&lt;Integer&gt;</code> using the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html" rel="noreferrer"><code>Integer</code></a> class that wraps the <code>int</code> primitive. Convert your array to a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html" rel="noreferrer"><code>List</code></a> with the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#asList(T...)" rel="noreferrer"><code>Arrays.asList</code></a> utility method.</p> <pre><code>Integer[] numbers = new Integer[] { 1, 2, 3 }; List&lt;Integer&gt; list = Arrays.asList(numbers); </code></pre> <p>See this <a href="https://ideone.com/KVd5j4" rel="noreferrer">code run live at IdeOne.com</a>.</p>
{ "question_id": 2607289, "question_date": "2010-04-09T12:20:20.827Z", "question_score": 1213, "tags": "java|arrays|list", "answer_id": 2607335, "answer_date": "2010-04-09T12:27:23.720Z", "answer_score": 1634 }
Please answer the following Stack Overflow question: Title: How to tag an older commit in Git? <p>We are new to git, and I want to set a tag at the beginning of our repository. Our production code is the same as the beginning repository, but we've made commits since then. A tag at the beginning would allow us to "roll back" production to a known, stable state.</p> <p>So how to add a tag to an arbitrary, older commit?</p>
<p>Example:</p> <pre><code>git tag -a v1.2 9fceb02 -m "Message here" </code></pre> <p>Where <code>9fceb02</code> is the beginning part of the commit id.</p> <p>You can then push the tag using <code>git push origin v1.2</code>.</p> <p>You can do <code>git log</code> to show all the commit id's in your current branch.</p> <p>There is also a good chapter on <a href="http://git-scm.com/book/en/Git-Basics-Tagging" rel="noreferrer">tagging</a> in the Pro Git book.</p> <p><strong>Warning:</strong> This creates tags with the <em>current date</em> (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at <a href="https://stackoverflow.com/a/21759466/674039">another answer</a>.</p>
{ "question_id": 4404172, "question_date": "2010-12-09T23:23:16.667Z", "question_score": 1213, "tags": "git|version-control|git-tag", "answer_id": 4404197, "answer_date": "2010-12-09T23:27:28.277Z", "answer_score": 1840 }
Please answer the following Stack Overflow question: Title: How to clear the canvas for redrawing <p>After experimenting with composite operations and drawing images on the canvas I'm now trying to remove images and compositing. How do I do this?</p> <p>I need to clear the canvas for redrawing other images; this can go on for a while so I don't think drawing a new rectangle every time will be the most efficient option.</p>
<p>Given that <code>canvas</code> is a canvas element or an <a href="https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas" rel="noreferrer"><code>OffscreenCanvas</code> object</a>,</p> <pre><code>const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); </code></pre>
{ "question_id": 2142535, "question_date": "2010-01-26T20:50:42.417Z", "question_score": 1212, "tags": "javascript|html|canvas|html5-canvas|composite", "answer_id": 2142549, "answer_date": "2010-01-26T20:52:18.097Z", "answer_score": 1597 }
Please answer the following Stack Overflow question: Title: master branch and 'origin/master' have diverged, how to 'undiverge' branches'? <p>Somehow my <code>master</code> and my <code>origin/master</code> branch have diverged.<br /> I actually don't want them to diverge.</p> <p>How can I view these differences and <strong>merge</strong> them?</p>
<p>You can <a href="https://stackoverflow.com/questions/53569/how-to-get-the-changes-on-a-branch-in-git">review the differences</a> with a:</p> <pre><code>git log HEAD..origin/main # old repositories git log HEAD..origin/master </code></pre> <p>before <a href="https://stackoverflow.com/questions/1484820/actually-pulling-with-git">pulling it</a> (fetch + merge) (see also <a href="https://stackoverflow.com/questions/658885/how-do-you-get-git-to-always-pull-from-a-specific-branch">&quot;How do you get git to always pull from a specific branch?&quot;</a>)</p> <p>Note: since <a href="https://stackoverflow.com/a/62983443/6309">Git 2.28 (Q3 2020)</a>, the default branch is configurable, and now (2021+) set to <code>main</code>, no longer <code>master</code>.<br /> The rest of the answer reflects that more recent convention.</p> <hr /> <p>When you have a message like:</p> <blockquote> <p>&quot;Your branch and 'origin/main' have diverged, # and have 1 and 1 different commit(s) each, respectively.&quot;</p> </blockquote> <p>Check if you <a href="https://stackoverflow.com/questions/2298556/branches-have-apparently-diverged-but-commit-history-is-identical">need to update <code>origin</code></a>.<br /> If <code>origin</code> is up-to-date, then some commits have been pushed to <code>origin</code> from another repo while you made your own commits locally.</p> <pre><code>... o ---- o ---- A ---- B origin/main (upstream work) \ C main(your work) </code></pre> <p>You based commit <code>C</code> on commit <code>A</code> because that was the latest work you had fetched from <code>upstream</code> at the time.</p> <p>However, before you tried to push back to <code>origin</code>, someone else pushed the commit <code>B</code>.<br /> Development history has diverged into separate paths.</p> <p>You can then merge or rebase. See <a href="http://git-scm.com/book/en/Git-Branching-Rebasing" rel="nofollow noreferrer">Pro Git: Git Branching - Rebasing</a> for details.</p> <h2>Merge</h2> <p>Use the <code>git merge</code> command:</p> <pre><code>$ git merge origin/main # old repositories $ git merge origin/master </code></pre> <p>This tells Git to integrate the changes from <code>origin/main</code> into your work and create a merge commit.<br /> The graph of history now looks like this:</p> <pre><code>... o ---- o ---- A ---- B origin/main (upstream work) \ \ C ---- M main (your work) </code></pre> <p>The new merge, commit <code>M</code>, has <em>two</em> parents, each representing one path of development that led to the content stored in that commit.</p> <p>Note that the history behind <code>M</code> is now non-linear.</p> <h2>Rebase</h2> <p>Use the <code>git rebase</code> command:</p> <pre><code>$ git rebase origin/main # old repositories $ git rebase origin/master </code></pre> <p>This tells Git to replay commit <code>C</code> (your work) as if you had based it on commit <code>B</code> instead of <code>A</code>.<br /> CVS and Subversion users routinely rebase their local changes on top of <code>upstream</code> work when they update before commit.<br /> Git just adds explicit separation between the commit and rebase steps.</p> <p>The graph of history now looks like this:</p> <pre><code>... o ---- o ---- A ---- B origin/main (upstream work) \ C' main (your work) </code></pre> <p>Commit <code>C'</code> is a new commit created by the <code>git rebase</code> command.<br /> It is different from <code>C</code> in two ways:</p> <ol> <li>It has a different history: <code>B</code> instead of <code>A</code>.</li> <li>Its content accounts for changes in both <code>B</code> and <code>C</code>; it is the same as <code>M</code> from the merge example.</li> </ol> <p>Note that the history behind <code>C'</code> is still linear.<br /> We have chosen (for now) to allow only linear history in <code>cmake.org/cmake.git</code>.<br /> This approach preserves the CVS-based workflow used previously and may ease the transition.<br /> An attempt to push <code>C'</code> into our repository will work (assuming you have permissions and no one has pushed while you were rebasing).</p> <p>The <code>git pull</code> command provides a shorthand way to <code>fetch</code> from <code>origin</code> and <code>rebase</code> local work on it:</p> <pre><code>$ git pull --rebase </code></pre> <p>This combines the above <code>fetch</code> and <code>rebase</code> steps into one command.</p>
{ "question_id": 2452226, "question_date": "2010-03-16T05:05:40.880Z", "question_score": 1211, "tags": "git|branch", "answer_id": 2452610, "answer_date": "2010-03-16T07:02:23.817Z", "answer_score": 1218 }
Please answer the following Stack Overflow question: Title: Does Django scale? <p>I'm building a web application with Django. The reasons I chose Django were:</p> <ul> <li>I wanted to work with free/open-source tools.</li> <li>I like Python and feel it's a <strong>long-term</strong> language, whereas regarding Ruby I wasn't sure, and PHP seemed like a huge hassle to learn.</li> <li>I'm building a prototype for an idea and wasn't thinking too much about the future. Development speed was the main factor, and I already knew Python.</li> <li>I knew the migration to Google App Engine would be easier should I choose to do so in the future.</li> <li>I heard Django was "nice".</li> </ul> <p>Now that I'm getting closer to thinking about publishing my work, I start being concerned about scale. The only information I found about the scaling capabilities of Django is provided by the Django team (I'm not saying anything to disregard them, but this is clearly not objective information...).</p> <p><strong>My questions:</strong></p> <ul> <li>What's the "largest" site that's built on Django today? (I measure size mostly by user traffic)</li> <li>Can Django deal with <em>100,000 users daily</em>, each visiting the site for a couple of hours?</li> <li>Could a site like Stack Overflow run on Django?</li> </ul>
<ol> <li><p><strong>"What are the largest sites built on Django today?"</strong></p> <p>There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of <a href="http://www.djangoproject.com/" rel="noreferrer">the main Django project page</a> and then a list of Django built sites at <a href="http://www.djangosites.org/" rel="noreferrer">djangosites.org</a>. Going through the lists and picking some that I know have decent traffic we see:</p> <ul> <li><p><strong><a href="http://instagram.com" rel="noreferrer">Instagram</a></strong>: <a href="http://instagram-engineering.tumblr.com/post/13649370142/what-powers-instagram-hundreds-of-instances" rel="noreferrer">What Powers Instagram: Hundreds of Instances, Dozens of Technologies</a>.</p></li> <li><p><strong><a href="http://pinterest.com/" rel="noreferrer">Pinterest</a></strong>: <a href="http://www.alexa.com/siteinfo/Pinterest.com" rel="noreferrer">Alexa rank 37 (21.4.2015)</a> and 70 Million users in 2013</p></li> <li><p><strong><a href="http://bitbucket.org/" rel="noreferrer">Bitbucket</a></strong>: <a href="https://blog.bitbucket.org/2015/02/05/bitbucket-2014-in-review/" rel="noreferrer">200TB of Code and 2.500.000 Users</a></p></li> <li><p><strong><a href="http://disqus.com" rel="noreferrer">Disqus</a></strong>: <a href="http://pyvideo.org/video/418/pycon-2011--disqus--serving-400-million-people-wi" rel="noreferrer">Serving 400 million people with Python</a>.</p></li> <li><p><strong><a href="http://curse.com/" rel="noreferrer">curse.com</a></strong>: <a href="http://www.quantcast.com/curse.com" rel="noreferrer">600k daily visits</a>.</p></li> <li><p><strong><a href="http://tabblo.com/" rel="noreferrer">tabblo.com</a></strong>: <a href="http://www.quantcast.com/tabblo.com" rel="noreferrer">44k daily visits</a>, see Ned Batchelder's posts <a href="http://nedbatchelder.com/blog/200902/infrastructure_for_modern_web_sites.html" rel="noreferrer">Infrastructure for modern web sites</a>.</p></li> <li><p><strong><a href="http://chesspark.com/" rel="noreferrer">chesspark.com</a></strong>: <a href="http://www.alexa.com/siteinfo/chesspark.com" rel="noreferrer">Alexa</a> rank about 179k.</p></li> <li><p><strong><a href="http://pownce.com/" rel="noreferrer">pownce.com</a></strong> (no longer active): <a href="http://www.alexa.com/siteinfo/pownce.com" rel="noreferrer">alexa</a> rank about 65k. Mike Malone of Pownce, in his EuroDjangoCon presentation on <strong><a href="http://www.slideshare.net/road76/scaling-django" rel="noreferrer">Scaling Django Web Apps</a></strong> says "hundreds of hits per second". This is a very good presentation on how to scale Django, and makes some good points including (current) shortcomings in Django scalability.</p></li> <li><p>HP had a site built with Django 1.5: <a href="http://www.eprintcenter.com" rel="noreferrer">ePrint center</a>. However, as for novemer/2015 the entire website was migrated and this link is just a redirect. This website was a world-wide service attending subscription to Instant Ink and related services HP offered (*).</p></li> </ul></li> <li><p><strong>"Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"</strong></p> <p>Yes, see above.</p></li> <li><p><strong>"Could a site like Stack Overflow run on Django?"</strong></p> <p>My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :)</p></li> </ol> <p>There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere!</p> <hr> <p>Blog post about <a href="http://web.archive.org/web/20130307032621/http://concentricsky.com/blog/2009/oct/michaelmoorecom" rel="noreferrer">Using Django to build high-traffic site michaelmoore.com</a> described as a <a href="http://www.alexa.com/siteinfo/http%3A%2F%2Fmichaelmoore.com" rel="noreferrer">top 10,000 website</a>. <a href="http://www.quantcast.com/michaelmoore.com" rel="noreferrer">Quantcast stats</a> and <a href="http://siteanalytics.compete.com/michaelmoore.com/" rel="noreferrer">compete.com stats</a>.</p> <hr> <p><sub>(*) The author of the edit, including such reference, used to work as outsourced developer in that project.</sub></p>
{ "question_id": 886221, "question_date": "2009-05-20T05:07:55.627Z", "question_score": 1210, "tags": "python|django|web-applications|scalability", "answer_id": 886645, "answer_date": "2009-05-20T07:41:16.597Z", "answer_score": 986 }
Please answer the following Stack Overflow question: Title: Convert ArrayList<String> to String[] array <p>I'm working in the android environment and have tried the following code, but it doesn't seem to be working.</p> <pre><code>String [] stockArr = (String[]) stock_list.toArray(); </code></pre> <p>If I define as follows:</p> <pre><code>String [] stockArr = {"hello", "world"}; </code></pre> <p>it works. Is there something that I'm missing?</p>
<p>Use like this.</p> <pre><code>List&lt;String&gt; stockList = new ArrayList&lt;String&gt;(); stockList.add("stock1"); stockList.add("stock2"); String[] stockArr = new String[stockList.size()]; stockArr = stockList.toArray(stockArr); for(String s : stockArr) System.out.println(s); </code></pre>
{ "question_id": 5374311, "question_date": "2011-03-21T05:57:59.193Z", "question_score": 1208, "tags": "java|arrays|arraylist", "answer_id": 5374359, "answer_date": "2011-03-21T06:07:00.027Z", "answer_score": 1824 }
Please answer the following Stack Overflow question: Title: How to create a generic array in Java? <p>Due to the implementation of Java generics, you can't have code like this: </p> <pre><code>public class GenSet&lt;E&gt; { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation } } </code></pre> <p>How can I implement this while maintaining type safety?</p> <p>I saw a solution on the Java forums that goes like this:</p> <pre><code>import java.lang.reflect.Array; class Stack&lt;T&gt; { public Stack(Class&lt;T&gt; clazz, int capacity) { array = (T[])Array.newInstance(clazz, capacity); } private final T[] array; } </code></pre> <p>But I really don't get what's going on.</p>
<p>I have to ask a question in return: is your <code>GenSet</code> "checked" or "unchecked"? What does that mean?</p> <ul> <li><p><strong>Checked</strong>: <em>strong typing</em>. <code>GenSet</code> knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a <code>Class&lt;E&gt;</code> argument, and methods will throw an exception when they are passed arguments that are not of type <code>E</code>. See <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29" rel="noreferrer"><code>Collections.checkedCollection</code></a>.</p> <p>-> in that case, you should write:</p> <pre><code>public class GenSet&lt;E&gt; { private E[] a; public GenSet(Class&lt;E&gt; c, int s) { // Use Array native method to create array // of a type only known at run time @SuppressWarnings("unchecked") final E[] a = (E[]) Array.newInstance(c, s); this.a = a; } E get(int i) { return a[i]; } } </code></pre></li> <li><p><strong>Unchecked</strong>: <em>weak typing</em>. No type checking is actually done on any of the objects passed as argument.</p> <p>-> in that case, you should write</p> <pre><code>public class GenSet&lt;E&gt; { private Object[] a; public GenSet(int s) { a = new Object[s]; } E get(int i) { @SuppressWarnings("unchecked") final E e = (E) a[i]; return e; } } </code></pre> <p>Note that the component type of the array should be the <a href="http://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer"><em>erasure</em></a> of the type parameter:</p> <pre><code>public class GenSet&lt;E extends Foo&gt; { // E has an upper bound of Foo private Foo[] a; // E erases to Foo, so use Foo[] public GenSet(int s) { a = new Foo[s]; } ... } </code></pre></li> </ul> <p>All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.</p>
{ "question_id": 529085, "question_date": "2009-02-09T17:30:44.417Z", "question_score": 1208, "tags": "java|arrays|generics|reflection|instantiation", "answer_id": 530289, "answer_date": "2009-02-09T22:19:31.197Z", "answer_score": 766 }
Please answer the following Stack Overflow question: Title: What do "branch", "tag" and "trunk" mean in Subversion repositories? <p>I've seen these words a lot around Subversion (and I guess general repository) discussions.<br> I have been using <strong>SVN</strong> for my projects for the last few years, but I've never grasped the complete concept of these directories.</p> <p>What do they mean?</p>
<p>Hmm, not sure I agree with Nick re tag being similar to a branch. A tag is just a marker</p> <ul> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.tour.importing.html#svn.tour.importing.layout" rel="noreferrer"><strong>Trunk</strong></a> would be the main body of development, originating from the start of the project until the present.</p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.whatis.html" rel="noreferrer"><strong>Branch</strong></a> will be a copy of code derived from a certain point in the trunk that is used for applying major changes to the code while preserving the integrity of the code in the trunk. If the major changes work according to plan, they are usually merged back into the trunk. </p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.tags.html" rel="noreferrer"><strong>Tag</strong></a> will be a point in time on the trunk or a branch that you wish to preserve. The two main reasons for preservation would be that either this is a major release of the software, whether alpha, beta, RC or RTM, or this is the most stable point of the software before major revisions on the trunk were applied.</p></li> </ul> <p>In open source projects, major branches that are not accepted into the trunk by the project stakeholders can become the bases for <em>forks</em> -- e.g., totally separate projects that share a common origin with other source code.</p> <p>The branch and tag subtrees are distinguished from the trunk in the following ways:</p> <p>Subversion allows sysadmins to create <em>hook scripts</em> which are triggered for execution when certain events occur; for instance, committing a change to the repository. It is very common for a typical Subversion repository implementation to treat any path containing "/tag/" to be write-protected after creation; the net result is that tags, once created, are immutable (at least to "ordinary" users). This is done via the hook scripts, which enforce the immutability by preventing further changes if <strong>tag</strong> is a parent node of the changed object.</p> <p>Subversion also has added features, since version 1.5, relating to "branch merge tracking" so that changes committed to a <strong>branch</strong> can be merged back into the trunk with support for incremental, "smart" merging.</p>
{ "question_id": 16142, "question_date": "2008-08-19T13:22:03.750Z", "question_score": 1208, "tags": "svn|branch|terminology|trunk", "answer_id": 16163, "answer_date": "2008-08-19T13:35:21.603Z", "answer_score": 921 }
Please answer the following Stack Overflow question: Title: How to exit git log or git diff <p>I'm trying to learn Git with the help of <a href="http://gitimmersion.com/" rel="noreferrer">Git Immersion</a>.<br> There's one thing that frustrates me whenever I use <code>git log</code> or <code>git diff</code>:</p> <p><img src="https://i.stack.imgur.com/yJ0Ms.png" alt="Git log shows (END) marker"></p> <p>I can't figure out what to do next when I encounter this <code>(END)</code> word.</p> <p>I can't type any commands, and I end up closing the current Bash window and open another. How do I type in the next command that I want to use?</p>
<p>You're in the <code>less</code> program, which makes the output of <code>git log</code> scrollable.</p> <p>Type <kbd>q</kbd> to exit this screen. Type <kbd>h</kbd> to get help.</p> <p>If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable <code>GIT_PAGER</code> to <code>cat</code> or set <code>core.pager</code> to <code>cat</code> (execute <code>git config --global core.pager cat</code>).</p>
{ "question_id": 9483757, "question_date": "2012-02-28T14:30:17.593Z", "question_score": 1205, "tags": "git|git-diff|git-log", "answer_id": 9483803, "answer_date": "2012-02-28T14:33:13.917Z", "answer_score": 1848 }
Please answer the following Stack Overflow question: Title: What is the best way to conditionally apply a class? <p>Lets say you have an array that is rendered in a <code>ul</code> with an <code>li</code> for each element and a property on the controller called <code>selectedIndex</code>. What would be the best way to add a class to the <code>li</code> with the index <code>selectedIndex</code> in AngularJS?</p> <p>I am currently duplicating (by hand) the <code>li</code> code and adding the class to one of the <code>li</code> tags and using <code>ng-show</code> and <code>ng-hide</code> to show only one <code>li</code> per index.</p>
<p>If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name <em>selected</em>, no custom directives are necessary:</p> <pre><code>ng:class="{true:'selected', false:''}[$index==selectedIndex]" </code></pre> <p><em>Please note the old syntax with colon.</em> </p> <p>There is also a new better way of applying classes conditionally, like:</p> <pre><code>ng-class="{selected: $index==selectedIndex}" </code></pre> <p>Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.</p> <p>However these ways are not functionally equal. Here is an example:</p> <pre><code>ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]" </code></pre> <p>We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.</p>
{ "question_id": 7792652, "question_date": "2011-10-17T10:49:52.990Z", "question_score": 1204, "tags": "css|angularjs", "answer_id": 8309832, "answer_date": "2011-11-29T11:17:36.663Z", "answer_score": 1387 }
Please answer the following Stack Overflow question: Title: When should you use a class vs a struct in C++? <p>In what scenarios is it better to use a <code>struct</code> vs a <code>class</code> in C++?</p>
<p>The differences between a <code>class</code> and a <code>struct</code> in C++ is:</p> <ul> <li><code>struct</code> members and base classes/structs are <code>public</code> by default.</li> <li><code>class</code> members and base classes/struts are <code>private</code> by default.</li> </ul> <p>Both classes and structs can have a mixture of <code>public</code>, <code>protected</code> and <code>private</code> members, can use inheritance and can have member functions.</p> <p>I would recommend you:</p> <ul> <li>use <code>struct</code> for plain-old-data structures without any class-like features;</li> <li>use <code>class</code> when you make use of features such as <code>private</code> or <code>protected</code> members, non-default constructors and operators, etc.</li> </ul>
{ "question_id": 54585, "question_date": "2008-09-10T16:29:54.217Z", "question_score": 1204, "tags": "c++|oop|class|struct|ooad", "answer_id": 54596, "answer_date": "2008-09-10T16:35:23.003Z", "answer_score": 1032 }
Please answer the following Stack Overflow question: Title: What is event bubbling and capturing? <p>What is the difference between event bubbling and capturing? When should one use bubbling vs capturing?</p>
<p>Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in <a href="http://www.quirksmode.org/js/events_order.html" rel="noreferrer">which order the elements receive the event</a>.</p> <p>With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.</p> <p>With capturing, the event is first captured by the outermost element and propagated to the inner elements.</p> <p>Capturing is also called "trickling", which helps remember the propagation order:</p> <blockquote> <p>trickle down, bubble up</p> </blockquote> <p>Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html" rel="noreferrer">Document Object Model Events</a> standard (2000).</p> <p>IE &lt; 9 uses <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener" rel="noreferrer">only event bubbling</a>, whereas IE9+ and all major browsers support both. On the other hand, the <a href="https://stackoverflow.com/a/10335117/1269037">performance of event bubbling may be slightly lower</a> for complex DOMs.</p> <p>We can use the <code>addEventListener(type, listener, useCapture)</code> to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as <code>true</code>.</p> <h2>Example</h2> <pre><code>&lt;div&gt; &lt;ul&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>In the structure above, assume that a click event occurred in the <code>li</code> element.</p> <p>In capturing model, the event will be handled by the <code>div</code> first (click event handlers in the <code>div</code> will fire first), then in the <code>ul</code>, then at the last in the target element, <code>li</code>.</p> <p>In the bubbling model, the opposite will happen: the event will be first handled by the <code>li</code>, then by the <code>ul</code>, and at last by the <code>div</code> element.</p> <p>For more information, see</p> <ul> <li><a href="http://www.quirksmode.org/js/events_order.html" rel="noreferrer">Event Order</a> on QuirksMode</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener" rel="noreferrer">addEventListener</a> on MDN</li> <li><a href="http://www.quirksmode.org/js/events_advanced.html" rel="noreferrer">Events Advanced</a> on QuirksMode</li> </ul> <p>In the example below, if you click on any of the highlighted elements, you can see that the capturing phase of the event propagation flow occurs first, followed by the bubbling phase.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var logElement = document.getElementById('log'); function log(msg) { logElement.innerHTML += ('&lt;p&gt;' + msg + '&lt;/p&gt;'); } function capture() { log('capture: ' + this.firstChild.nodeValue.trim()); } function bubble() { log('bubble: ' + this.firstChild.nodeValue.trim()); } function clearOutput() { logElement.innerHTML = ""; } var divs = document.getElementsByTagName('div'); for (var i = 0; i &lt; divs.length; i++) { divs[i].addEventListener('click', capture, true); divs[i].addEventListener('click', bubble, false); } var clearButton = document.getElementById('clear'); clearButton.addEventListener('click', clearOutput);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>p { line-height: 0; } div { display:inline-block; padding: 5px; background: #fff; border: 1px solid #aaa; cursor: pointer; } div:hover { border: 1px solid #faa; background: #fdd; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;1 &lt;div&gt;2 &lt;div&gt;3 &lt;div&gt;4 &lt;div&gt;5&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;button id="clear"&gt;clear output&lt;/button&gt; &lt;section id="log"&gt;&lt;/section&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/cwtuan/je1g3f29/16" rel="noreferrer">Another example at JSFiddle</a>.</p>
{ "question_id": 4616694, "question_date": "2011-01-06T15:44:43.057Z", "question_score": 1204, "tags": "javascript|dom-events|event-bubbling", "answer_id": 4616720, "answer_date": "2011-01-06T15:47:04.883Z", "answer_score": 1700 }
Please answer the following Stack Overflow question: Title: Can't bind to 'formGroup' since it isn't a known property of 'form' <h2>The situation</h2> <p>I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.</p> <h2>The Angular version</h2> <p>Angular 2.0.0 RC5</p> <h2>The error</h2> <blockquote> <p>Can't bind to 'formGroup' since it isn't a known property of 'form'</p> </blockquote> <p><a href="https://i.stack.imgur.com/7elmg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7elmg.png" alt="Enter image description here" /></a></p> <h2>The code</h2> <h3>The view</h3> <pre class="lang-html prettyprint-override"><code>&lt;form [formGroup]=&quot;newTaskForm&quot; (submit)=&quot;createNewTask()&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;name&quot; required&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-default&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <h3>The controller</h3> <pre><code>import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {FormsModule,ReactiveFormsModule} from '@angular/forms'; import { Task } from './task'; @Component({ selector: 'task-add', templateUrl: 'app/task-add.component.html' }) export class TaskAddComponent { newTaskForm: FormGroup; constructor(fb: FormBuilder) { this.newTaskForm = fb.group({ name: [&quot;&quot;, Validators.required] }); } createNewTask() { console.log(this.newTaskForm.value) } } </code></pre> <h3>The ngModule</h3> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { routing } from './app.routing'; import { AppComponent } from './app.component'; import { TaskService } from './task.service' @NgModule({ imports: [ BrowserModule, routing, FormsModule ], declarations: [ AppComponent ], providers: [ TaskService ], bootstrap: [ AppComponent ] }) export class AppModule { } </code></pre> <h2>The question</h2> <p>Why am I getting that error? Am I missing something?</p>
<p><strong>RC6/RC7/Final release FIX</strong></p> <p>To fix this error, you just need to import <code>ReactiveFormsModule</code> from <code>@angular/forms</code> in your module. Here's the example of a basic module with <code>ReactiveFormsModule</code> import:</p> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], declarations: [ AppComponent ], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p>To explain further, <code>formGroup</code> is a selector for directive named <code>FormGroupDirective</code> that is a part of <code>ReactiveFormsModule</code>, hence the need to import it. It is used to bind an existing <code>FormGroup</code> to a DOM element. You can read more about it on <a href="https://angular.io/docs/ts/latest/api/forms/index/FormGroupDirective-directive.html" rel="noreferrer">Angular's official docs page</a>.</p> <p><strong>RC5 FIX</strong></p> <p>You need to <code>import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'</code> in your controller and add it to <code>directives</code> in <code>@Component</code>. That will fix the problem.</p> <p>After you fix that, you will probably get another error because you didn't add <code>formControlName=&quot;name&quot;</code> to your input in form.</p>
{ "question_id": 39152071, "question_date": "2016-08-25T18:09:06.380Z", "question_score": 1203, "tags": "angular|typescript|angular2-forms", "answer_id": 39152110, "answer_date": "2016-08-25T18:11:27.123Z", "answer_score": 1997 }
Please answer the following Stack Overflow question: Title: How to check if a map contains a key in Go? <p>I know I can iterate over a map <code>m</code> by,</p> <pre><code>for k, v := range m { ... } </code></pre> <p>and look for a key but is there a more efficient way of testing a key's existence in a map? </p> <p>I couldn't find the answer in the <a href="http://golang.org/doc/go_spec.html" rel="noreferrer">language spec</a>.</p>
<p>One line answer:</p> <pre><code>if val, ok := dict["foo"]; ok { //do something here } </code></pre> <h3>Explanation:</h3> <p><code>if</code> statements in Go can include both a condition and an initialization statement. The example above uses both:</p> <ul> <li><p>initializes two variables - <code>val</code> will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and <code>ok</code> will receive a bool that will be set to <code>true</code> if "foo" was actually present in the map</p></li> <li><p>evaluates <code>ok</code>, which will be <code>true</code> if "foo" was in the map</p></li> </ul> <p>If "foo" is indeed present in the map, the body of the <code>if</code> statement will be executed and <code>val</code> will be local to that scope.</p>
{ "question_id": 2050391, "question_date": "2010-01-12T16:18:20.210Z", "question_score": 1203, "tags": "dictionary|go|go-map", "answer_id": 2050629, "answer_date": "2010-01-12T16:48:48.543Z", "answer_score": 2321 }
Please answer the following Stack Overflow question: Title: How do I get the path to the current script with Node.js? <p>How would I get the path to the script in Node.js?</p> <p>I know there's <code>process.cwd</code>, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in <code>/home/kyle/</code> and I run the following command:</p> <pre><code>node /home/kyle/some/dir/file.js </code></pre> <p>If I call <code>process.cwd()</code>, I get <code>/home/kyle/</code>, not <code>/home/kyle/some/dir/</code>. Is there a way to get that directory?</p>
<p>I found it after looking through the documentation again. What I was looking for were the <a href="https://nodejs.org/docs/latest/api/modules.html#modules_filename" rel="noreferrer"><code>__filename</code></a> and <a href="https://nodejs.org/docs/latest/api/modules.html#modules_dirname" rel="noreferrer"><code>__dirname</code></a> module-level variables.</p> <ul> <li><code>__filename</code> is the file name of the current module. This is the resolved absolute path of the current module file. (ex:<code>/home/kyle/some/dir/file.js</code>)</li> <li><code>__dirname</code> is the directory name of the current module. (ex:<code>/home/kyle/some/dir</code>)</li> </ul>
{ "question_id": 3133243, "question_date": "2010-06-28T14:31:01.823Z", "question_score": 1202, "tags": "node.js", "answer_id": 3133313, "answer_date": "2010-06-28T14:39:40.413Z", "answer_score": 1624 }
Please answer the following Stack Overflow question: Title: How do I print an exception in Python? <p>How do I print the error/exception in the <code>except:</code> block?</p> <pre><code>try: ... except: print(exception) </code></pre>
<p>For Python 2.6 and later and Python 3.x:</p> <pre><code>except Exception as e: print(e) </code></pre> <p>For Python 2.5 and earlier, use:</p> <pre><code>except Exception,e: print str(e) </code></pre>
{ "question_id": 1483429, "question_date": "2009-09-27T11:48:19.513Z", "question_score": 1201, "tags": "python|exception|error-handling", "answer_id": 1483488, "answer_date": "2009-09-27T12:19:27.260Z", "answer_score": 1651 }
Please answer the following Stack Overflow question: Title: How do you remove all the options of a select box and then add one option and select it with jQuery? <p>Using core jQuery, how do you remove all the options of a select box, then add one option and select it?</p> <p>My select box is the following.</p> <pre><code>&lt;Select id="mySelect" size="9"&gt; &lt;/Select&gt; </code></pre> <p>EDIT: The following code was helpful with chaining. However, (in Internet&nbsp;Explorer) <code>.val('whatever')</code> did not select the option that was added. (I did use the same 'value' in both <code>.append</code> and <code>.val</code>.)</p> <pre><code>$('#mySelect').find('option').remove().end() .append('&lt;option value="whatever"&gt;text&lt;/option&gt;').val('whatever'); </code></pre> <p>EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. <code>.focus()</code> was closer, but the option did not appear selected like it does with <code>.selected= "true"</code>. Nothing is wrong with my existing code - I am just trying to learn jQuery.</p> <pre><code>var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; </code></pre> <p>EDIT: selected answer was close to what I needed. This worked for me:</p> <pre><code>$('#mySelect').children().remove().end() .append('&lt;option selected value="whatever"&gt;text&lt;/option&gt;') ; </code></pre> <p>But both answers led me to my final solution..</p>
<pre><code>$('#mySelect') .find('option') .remove() .end() .append('&lt;option value="whatever"&gt;text&lt;/option&gt;') .val('whatever') ; </code></pre>
{ "question_id": 47824, "question_date": "2008-09-06T20:53:54.957Z", "question_score": 1200, "tags": "javascript|jquery|html-select|dynamic-html", "answer_id": 47829, "answer_date": "2008-09-06T21:01:36.750Z", "answer_score": 1826 }
Please answer the following Stack Overflow question: Title: How can I revert uncommitted changes including files and folders? <p>Is there a Git command to revert all uncommitted changes in a working tree and index and to also remove newly created files and folders?</p>
<p>You can run these two commands:</p> <pre><code># Revert changes to modified files. git reset --hard # Remove all untracked files and directories. # '-f' is force, '-d' is remove directories. git clean -fd </code></pre>
{ "question_id": 5807137, "question_date": "2011-04-27T16:06:09.860Z", "question_score": 1200, "tags": "git|git-commit|git-reset|git-revert|git-clean", "answer_id": 5812972, "answer_date": "2011-04-28T02:37:48.167Z", "answer_score": 1949 }
Please answer the following Stack Overflow question: Title: How to convert a string to lower or upper case in Ruby <p>How do I take a string and convert it to lower or upper case in Ruby?</p>
<p>Ruby has a few methods for changing the case of strings. To convert to lowercase, use <code>downcase</code>:</p> <pre><code>&quot;hello James!&quot;.downcase #=&gt; &quot;hello james!&quot; </code></pre> <p>Similarly, <code>upcase</code> capitalizes every letter and <code>capitalize</code> capitalizes the first letter of the string but lowercases the rest:</p> <pre><code>&quot;hello James!&quot;.upcase #=&gt; &quot;HELLO JAMES!&quot; &quot;hello James!&quot;.capitalize #=&gt; &quot;Hello james!&quot; &quot;hello James!&quot;.titleize #=&gt; &quot;Hello James!&quot; (Rails/ActiveSupport only) </code></pre> <p>If you want to modify a string in place, you can add an exclamation point to any of those methods:</p> <pre><code>string = &quot;hello James!&quot; string.downcase! string #=&gt; &quot;hello james!&quot; </code></pre> <p>Refer to the <a href="http://www.ruby-doc.org/core/String.html" rel="noreferrer">documentation for String</a> for more information.</p>
{ "question_id": 1020568, "question_date": "2009-06-20T00:16:00.743Z", "question_score": 1199, "tags": "ruby|string|uppercase|lowercase", "answer_id": 1020571, "answer_date": "2009-06-20T00:16:55.487Z", "answer_score": 1728 }
Please answer the following Stack Overflow question: Title: Count the number of occurrences of a character in a string <p>How do I count the number of occurrences of a character in a string?</p> <p>e.g. <code>'a'</code> appears in <code>'Mary had a little lamb'</code> 4 times.</p>
<blockquote> <p><a href="https://docs.python.org/3/library/stdtypes.html#str.count" rel="noreferrer"><code>str.count(sub[, start[, end]])</code></a></p> <p>Return the number of non-overlapping occurrences of substring <code>sub</code> in the range <code>[start, end]</code>. Optional arguments <code>start</code> and <code>end</code> are interpreted as in slice notation.</p> </blockquote> <pre><code>&gt;&gt;&gt; sentence = 'Mary had a little lamb' &gt;&gt;&gt; sentence.count('a') 4 </code></pre>
{ "question_id": 1155617, "question_date": "2009-07-20T20:00:36.297Z", "question_score": 1198, "tags": "python|string|count", "answer_id": 1155647, "answer_date": "2009-07-20T20:04:26.693Z", "answer_score": 1643 }
Please answer the following Stack Overflow question: Title: Could not find a part of the path ... bin\roslyn\csc.exe <p>I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added all assembly references and I am able to build and compile successfully without any error or warning.</p> <p>But I get the following error in the browser:</p> <blockquote> <p>Could not find a part of the path 'C:\B8akWorkspace\B8akProject\B8akSolution\B8AK.Portal\bin\roslyn\csc.exe'.</p> </blockquote> <p>Here is a full screenshot of the error page.</p> <p><a href="https://i.stack.imgur.com/lkxJP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lkxJP.png" alt="enter image description here" /></a></p> <p>After few days of research, I understood that <a href="https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/" rel="noreferrer">Roslyn</a> is a .NET compiler platform that offers advanced compiling features. However, I do not understand why my build is trying to find \bin\roslyn\csc.exe because I did not configure anything related to Roslyn. Nor did I intend to use Roslyn in my project.</p>
<p>The problem with the default VS2015 templates is that the compiler isn't actually copied to the <code>tfr\bin\roslyn\</code> directory, but rather the <code>{outdir}\roslyn\</code> directory</p> <p>Add this code in your .csproj file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Target Name=&quot;CopyRoslynFiles&quot; AfterTargets=&quot;AfterBuild&quot; Condition=&quot;!$(Disable_CopyWebApplication) And '$(OutDir)' != '$(OutputPath)'&quot;&gt; &lt;ItemGroup&gt; &lt;RoslynFiles Include=&quot;$(CscToolPath)\*&quot; /&gt; &lt;/ItemGroup&gt; &lt;MakeDir Directories=&quot;$(WebProjectOutputDir)\bin\roslyn&quot; /&gt; &lt;Copy SourceFiles=&quot;@(RoslynFiles)&quot; DestinationFolder=&quot;$(WebProjectOutputDir)\bin\roslyn&quot; SkipUnchangedFiles=&quot;true&quot; Retries=&quot;$(CopyRetryCount)&quot; RetryDelayMilliseconds=&quot;$(CopyRetryDelayMilliseconds)&quot; /&gt; &lt;/Target&gt; </code></pre>
{ "question_id": 32780315, "question_date": "2015-09-25T10:36:19.470Z", "question_score": 1198, "tags": "c#|asp.net|.net|visual-studio|roslyn", "answer_id": 32780433, "answer_date": "2015-09-25T10:44:18.213Z", "answer_score": 573 }
Please answer the following Stack Overflow question: Title: Returning IEnumerable<T> vs. IQueryable<T> <p>What is the difference between returning <code>IQueryable&lt;T&gt;</code> vs. <code>IEnumerable&lt;T&gt;</code>, when should one be preferred over the other?</p> <pre><code>IQueryable&lt;Customer&gt; custs = from c in db.Customers where c.City == &quot;&lt;City&gt;&quot; select c; IEnumerable&lt;Customer&gt; custs = from c in db.Customers where c.City == &quot;&lt;City&gt;&quot; select c; </code></pre> <p>Will both be deferred execution and when should one be preferred over the other?</p>
<p>Yes, both will give you <a href="https://msdn.microsoft.com/en-us/library/bb738633(v=vs.110).aspx#Anchor_0" rel="noreferrer">deferred execution</a>.</p> <p>The difference is that <a href="https://msdn.microsoft.com/en-us/library/bb351562.aspx" rel="noreferrer"><code>IQueryable&lt;T&gt;</code></a> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an <a href="https://msdn.microsoft.com/en-us/library/bb351562.aspx" rel="noreferrer"><code>IQueryable&lt;T&gt;</code></a>, that query will be executed in the database, if possible. </p> <p>For the <a href="https://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="noreferrer"><code>IEnumerable&lt;T&gt;</code></a> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.</p> <p>In code:</p> <pre><code>IQueryable&lt;Customer&gt; custs = ...; // Later on... var goldCustomers = custs.Where(c =&gt; c.IsGold); </code></pre> <p>That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:</p> <pre><code>IEnumerable&lt;Customer&gt; custs = ...; // Later on... var goldCustomers = custs.Where(c =&gt; c.IsGold); </code></pre> <p>This is quite an important difference, and working on <a href="https://msdn.microsoft.com/en-us/library/bb351562.aspx" rel="noreferrer"><code>IQueryable&lt;T&gt;</code></a> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use <a href="https://msdn.microsoft.com/en-us/library/bb300906.aspx" rel="noreferrer"><code>Take</code></a> and <a href="https://msdn.microsoft.com/en-us/library/bb357513.aspx" rel="noreferrer"><code>Skip</code></a> on <a href="https://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx" rel="noreferrer"><code>IQueryable</code></a>, you will only get the number of rows requested; doing that on an <a href="https://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="noreferrer"><code>IEnumerable&lt;T&gt;</code></a> will cause all of your rows to be loaded in memory.</p>
{ "question_id": 2876616, "question_date": "2010-05-20T18:13:59.820Z", "question_score": 1198, "tags": "c#|linq|linq-to-sql|ienumerable|iqueryable", "answer_id": 2876655, "answer_date": "2010-05-20T18:19:06.500Z", "answer_score": 1934 }
Please answer the following Stack Overflow question: Title: What does %~dp0 mean, and how does it work? <p>I find <code>%~dp0</code> very useful, and I use it a lot to make my batch files more portable.</p> <p>But the label itself seems very cryptic to me... What is the <code>~</code> doing? Does <code>dp</code> mean drive and path? Does the <code>0</code> refer to <code>%0</code>, the path to the batch file that includes the file name?</p> <p>Or it is just a weird label?</p> <p>I'd also like to know if it is a documented feature, or something prone to be deprecated.</p>
<p>Calling</p> <pre><code>for /? </code></pre> <p>in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).</p> <blockquote> <p>In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:</p> <pre><code>%~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a fully qualified path name %~dI - expands %I to a drive letter only %~pI - expands %I to a path only %~nI - expands %I to a file name only %~xI - expands %I to a file extension only %~sI - expanded path contains short names only %~aI - expands %I to file attributes of file %~tI - expands %I to date/time of file %~zI - expands %I to size of file %~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string </code></pre> <p>The modifiers can be combined to get compound results:</p> <pre><code>%~dpI - expands %I to a drive letter and path only %~nxI - expands %I to a file name and extension only %~fsI - expands %I to a full path name with short names only %~dp$PATH:I - searches the directories listed in the PATH environment variable for %I and expands to the drive letter and path of the first one found. %~ftzaI - expands %I to a DIR like output line </code></pre> <p>In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.</p> </blockquote> <p>There are different letters you can use like <code>f</code> for "full path name", <code>d</code> for drive letter, <code>p</code> for path, and they can be combined. <code>%~</code> is the beginning for each of those sequences and a number <code>I</code> denotes it works on the parameter <code>%I</code> (where <code>%0</code> is the complete name of the batch file, just like you assumed).</p>
{ "question_id": 5034076, "question_date": "2011-02-17T20:15:21.957Z", "question_score": 1196, "tags": "batch-file", "answer_id": 5034119, "answer_date": "2011-02-17T20:19:27.820Z", "answer_score": 914 }
Please answer the following Stack Overflow question: Title: How can I tell if a DOM element is visible in the current viewport? <p>Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the <strong>viewport</strong>)?</p> <p>(The question refers to Firefox.)</p>
<p><strong>Update:</strong> Time marches on and so have our browsers. <strong>This technique is no longer recommended</strong> and you should use <a href="https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433">Dan's solution</a> if you do not need to support version of Internet&nbsp;Explorer before 7.</p> <p><strong>Original solution (now outdated):</strong></p> <p>This will check if the element is entirely visible in the current viewport:</p> <pre><code>function elementInViewport(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top &gt;= window.pageYOffset &amp;&amp; left &gt;= window.pageXOffset &amp;&amp; (top + height) &lt;= (window.pageYOffset + window.innerHeight) &amp;&amp; (left + width) &lt;= (window.pageXOffset + window.innerWidth) ); } </code></pre> <p>You could modify this simply to determine if any part of the element is visible in the viewport:</p> <pre><code>function elementInViewport2(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top &lt; (window.pageYOffset + window.innerHeight) &amp;&amp; left &lt; (window.pageXOffset + window.innerWidth) &amp;&amp; (top + height) &gt; window.pageYOffset &amp;&amp; (left + width) &gt; window.pageXOffset ); } </code></pre>
{ "question_id": 123999, "question_date": "2008-09-23T21:24:56.057Z", "question_score": 1195, "tags": "javascript|html|firefox|dom|browser", "answer_id": 125106, "answer_date": "2008-09-24T02:40:09.047Z", "answer_score": 408 }
Please answer the following Stack Overflow question: Title: How do I collapse sections of code in Visual Studio Code for Windows? <p>How do I fold or collapse sections of code in Visual Studio Code?</p> <p>Is this feature supported?</p>
<p><a href="https://code.visualstudio.com/docs/editor/codebasics#_folding" rel="noreferrer">Folding</a> has been rolled out and is now implemented since Visual Studio Code <a href="https://code.visualstudio.com/updates/vFebruary" rel="noreferrer">version 0.10.11</a>. There are these keyboard shortcuts available:</p> <ul> <li><p><strong>Fold</strong> folds the innermost uncollapsed region at the cursor:</p> <ul> <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>[</kbd> on Windows and Linux</li> <li><kbd>⌥</kbd> + <kbd>⌘</kbd> + <kbd>[</kbd> on macOS</li> </ul> </li> <li><p><strong>Unfold</strong> unfolds the collapsed region at the cursor:</p> <ul> <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>]</kbd> on Windows and Linux</li> <li><kbd>⌥</kbd> + <kbd>⌘</kbd> + <kbd>]</kbd> on macOS</li> </ul> </li> <li><p><strong>Fold All</strong> folds all regions in the editor:</p> <ul> <li><kbd>Ctrl</kbd> + <kbd>K</kbd>, <kbd>Ctrl</kbd> + <kbd>0</kbd> (zero) on Windows and Linux</li> <li><kbd>⌘</kbd> + <kbd>K</kbd>, <kbd>⌘</kbd> +<kbd>0</kbd> (zero) on macOS</li> </ul> </li> <li><p><strong>Unfold All</strong> unfolds all regions in the editor:</p> <ul> <li><kbd>Ctrl</kbd> + <kbd>K</kbd>, <kbd>Ctrl</kbd> + <kbd>J</kbd> on Windows and Linux</li> <li><kbd>⌘</kbd> + <kbd>K</kbd>, <kbd>⌘</kbd> + <kbd>J</kbd> on macOS</li> </ul> </li> </ul> <hr /> <p><strong>References:</strong> <a href="https://code.visualstudio.com/docs/getstarted/keybindings" rel="noreferrer">https://code.visualstudio.com/docs/getstarted/keybindings</a></p>
{ "question_id": 30067767, "question_date": "2015-05-06T04:50:01.960Z", "question_score": 1195, "tags": "visual-studio-code", "answer_id": 30077543, "answer_date": "2015-05-06T13:00:15.787Z", "answer_score": 2039 }
Please answer the following Stack Overflow question: Title: How to effectively work with multiple files in Vim <p>I've started using Vim to develop Perl scripts and am starting to find it very powerful. </p> <p>One thing I like is to be able to open multiple files at once with:</p> <pre><code>vi main.pl maintenance.pl </code></pre> <p>and then hop between them with:</p> <pre><code>:n :prev </code></pre> <p>and see which file are open with:</p> <pre><code>:args </code></pre> <p>And to add a file, I can say: </p> <pre><code>:n test.pl </code></pre> <p>which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type <code>:args</code> I only have <code>test.pl</code> open.</p> <p>So how can I add and remove files in my args list?</p>
<p>Why not use tabs (introduced in Vim 7)? You can switch between tabs with <code>:tabn</code> and <code>:tabp</code>, With <code>:tabe &lt;filepath&gt;</code> you can add a new tab; and with a regular <code>:q</code> or <code>:wq</code> you close a tab. If you map <code>:tabn</code> and <code>:tabp</code> to your <kbd>F7</kbd>/<kbd>F8</kbd> keys you can easily switch between files.</p> <p>If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: <code>:sp &lt;filepath&gt;</code>. Then you can switch between splitscreens with <kbd>Ctrl</kbd>+<kbd>W</kbd> and then an arrow key in the direction you want to move (or instead of arrow keys, <kbd>w</kbd> for next and <kbd>W</kbd> for previous splitscreen)</p>
{ "question_id": 53664, "question_date": "2008-09-10T09:03:49.733Z", "question_score": 1195, "tags": "vim|vi", "answer_id": 53668, "answer_date": "2008-09-10T09:09:32.840Z", "answer_score": 1244 }
Please answer the following Stack Overflow question: Title: How to understand nil vs. empty vs. blank in Ruby <p>I find myself repeatedly looking for a clear definition of the differences of <code>nil?</code>, <code>blank?</code>, and <code>empty?</code> in Ruby on Rails. Here's the closest I've come:</p> <ul> <li><p><code>blank?</code> objects are false, empty, or a whitespace string. For example, <code>""</code>, <code>" "</code>, <code>nil</code>, <code>[]</code>, and <code>{}</code> are blank.</p></li> <li><p><code>nil?</code> objects are instances of NilClass.</p></li> <li><p><code>empty?</code> objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.</p></li> </ul> <p>Is there anything missing, or a tighter comparison that can be made?</p>
<p><code>.nil?</code> can be used on any object and is true if the object is nil.</p> <p><code>.empty?</code> can be used on strings, arrays and hashes and returns true if:</p> <ul> <li>String length == 0</li> <li>Array length == 0</li> <li>Hash length == 0</li> </ul> <p>Running <code>.empty?</code> on something that is nil will throw a <code>NoMethodError</code>.</p> <p>That is where <code>.blank?</code> comes in. It is <a href="http://apidock.com/rails/Object/blank%3F" rel="noreferrer">implemented by Rails</a> and will operate on any object as well as work like <code>.empty?</code> on strings, arrays and hashes.</p> <pre><code>nil.blank? == true false.blank? == true [].blank? == true {}.blank? == true "".blank? == true 5.blank? == false 0.blank? == false </code></pre> <p><code>.blank?</code> also evaluates true on strings which are non-empty but contain only whitespace:</p> <pre><code>" ".blank? == true " ".empty? == false </code></pre> <p><a href="http://apidock.com/rails/Object/presence" rel="noreferrer">Rails also provides</a> <code>.present?</code>, which returns the negation of <code>.blank?</code>.</p> <p>Array gotcha: <code>blank?</code> will return <code>false</code> even if all <em>elements</em> of an array are blank. To determine blankness in this case, use <code>all?</code> with <code>blank?</code>, for example:</p> <pre><code>[ nil, '' ].blank? == false [ nil, '' ].all? &amp;:blank? == true </code></pre>
{ "question_id": 885414, "question_date": "2009-05-19T22:51:36.560Z", "question_score": 1195, "tags": "ruby-on-rails|ruby", "answer_id": 888877, "answer_date": "2009-05-20T16:14:58.150Z", "answer_score": 1486 }
Please answer the following Stack Overflow question: Title: Listing only directories using ls in Bash? <p>This command lists directories in the current path:</p> <pre class="lang-bash prettyprint-override"><code>ls -d */ </code></pre> <p>What exactly does the pattern <code>*/</code> do?</p> <p>And how can we give the absolute path in the above command (e.g. <code>ls -d /home/alice/Documents</code>) for listing only directories in that path?</p>
<p><code>*/</code> is a pattern that matches all of the subdirectories in the current directory (<code>*</code> would match all files <em>and</em> subdirectories; the <code>/</code> restricts it to directories). Similarly, to list all subdirectories under /home/alice/Documents, use <code>ls -d /home/alice/Documents/*/</code></p>
{ "question_id": 14352290, "question_date": "2013-01-16T06:07:00.457Z", "question_score": 1194, "tags": "bash|directory|ls", "answer_id": 14352330, "answer_date": "2013-01-16T06:11:28.673Z", "answer_score": 1245 }
Please answer the following Stack Overflow question: Title: How to mark a method as obsolete or deprecated? <p>How do I mark a method as obsolete or deprecated using C#?</p>
<p>The shortest way is by adding the <a href="https://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="noreferrer"><code>ObsoleteAttribute</code></a> as an <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/index" rel="noreferrer">attribute to the method</a>. Make sure to include an appropriate explanation:</p> <pre><code>[Obsolete("Method1 is deprecated, please use Method2 instead.")] public void Method1() { … } </code></pre> <p>You can also cause the compilation to fail, treating the usage of the method as an <strong><em>error instead of warning</em></strong>, if the method is called from somewhere in code like this:</p> <pre><code>[Obsolete("Method1 is deprecated, please use Method2 instead.", true)] </code></pre>
{ "question_id": 1759352, "question_date": "2009-11-18T21:53:38.470Z", "question_score": 1194, "tags": "c#|.net|versioning|deprecated", "answer_id": 1759357, "answer_date": "2009-11-18T21:54:15.693Z", "answer_score": 1854 }
Please answer the following Stack Overflow question: Title: HTTP response code for POST when resource already exists <p>I'm building a server that allows clients to store objects. Those objects are fully constructed at client side, complete with object IDs that are permanent for the whole lifetime of the object.</p> <p>I have defined the API so that clients can create or modify objects using PUT:</p> <pre><code>PUT /objects/{id} HTTP/1.1 ... {json representation of the object} </code></pre> <p>The {id} is the object ID, so it is part of the Request-URI.</p> <p>Now, I'm also considering allowing clients to create the object using POST:</p> <pre><code>POST /objects/ HTTP/1.1 ... {json representation of the object, including ID} </code></pre> <p>Since POST is meant as "append" operation, I'm not sure what to do in case the object is already there. Should I treat the request as modification request or should I return some error code (which)?</p>
<p>My feeling is <code>409 Conflict</code> is the most appropriate, however, seldom seen in the wild of course:</p> <blockquote> <p>The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.</p> <p>Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.</p> </blockquote>
{ "question_id": 3825990, "question_date": "2010-09-29T21:26:13.473Z", "question_score": 1193, "tags": "rest|http|http-status-codes", "answer_id": 3826024, "answer_date": "2010-09-29T21:31:13.400Z", "answer_score": 1476 }
Please answer the following Stack Overflow question: Title: How can I pipe stderr, and not stdout? <p>I have a program that writes information to <code>stdout</code> and <code>stderr</code>, and I need to process the <code>stderr</code> with <code>grep</code>, leaving <code>stdout</code> aside.</p> <p>Using a temporary file, one could do it in two steps:</p> <pre><code>command &gt; /dev/null 2&gt; temp.file grep 'something' temp.file </code></pre> <p>But how can this be achieved without temp files, using one command and pipes?</p>
<p>First redirect stderr to stdout — the pipe; then redirect stdout to <code>/dev/null</code> (without changing where stderr is going):</p> <pre><code>command 2&gt;&amp;1 &gt;/dev/null | grep 'something' </code></pre> <p>For the details of I/O redirection in all its variety, see the chapter on <a href="http://www.gnu.org/software/bash/manual/bash.html#Redirections" rel="noreferrer">Redirections</a> in the Bash reference manual.</p> <p>Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation <code>2&gt;&amp;1</code> makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/dup2.html" rel="noreferrer"><code>dup2()</code></a> and <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html" rel="noreferrer"><code>open()</code></a>). The operation <code>&gt;/dev/null</code> then changes file descriptor 1 so that it refers to an open file description for <code>/dev/null</code>, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.</p>
{ "question_id": 2342826, "question_date": "2010-02-26T15:53:27.977Z", "question_score": 1193, "tags": "bash|grep|stdout|pipe|stderr", "answer_id": 2342841, "answer_date": "2010-02-26T15:55:18.973Z", "answer_score": 1455 }
Please answer the following Stack Overflow question: Title: What does <![CDATA[]]> in XML mean? <p>I often find this strange <code>CDATA</code> tag in <code>XML</code> files:</p> <pre><code>&lt;![CDATA[some stuff]]&gt; </code></pre> <p>I have observed that this <code>CDATA</code> tag always comes at the beginning, and then followed by some stuff.</p> <p>But sometimes it is used, sometimes it is not. I assume it is to mark that <code>some stuff</code> is the "data" that will be inserted after that. But what kind of data is <code>some stuff</code>? Isn't anything I write in XML tags some sort of data?</p>
<p><a href="http://www.w3.org/TR/REC-xml/#sec-cdata-sect" rel="noreferrer">CDATA</a> stands for <a href="http://www.w3.org/TR/REC-xml/#dt-chardata" rel="noreferrer">Character Data</a> and it means that the data in between these strings includes data that <em>could</em> be interpreted as XML markup, but should not be.</p> <p>The key differences between CDATA and comments are:</p> <ul> <li>As <a href="https://stackoverflow.com/a/2784294/135978">Richard points out</a>, CDATA is still part of the document, while a comment is not.</li> <li>In CDATA you cannot include the string <code>]]&gt;</code> (<a href="http://www.w3.org/TR/REC-xml/#NT-CDEnd" rel="noreferrer"><code>CDEnd</code></a>), while in a comment <a href="http://www.w3.org/TR/REC-xml/#sec-comments" rel="noreferrer"><code>--</code> is invalid</a>.</li> <li><a href="http://www.w3.org/TR/REC-xml/#dt-PERef" rel="noreferrer">Parameter Entity</a> references are not recognized inside of comments.</li> </ul> <p>This means given these four snippets of XML from one well-formed document:</p> <pre><code>&lt;!ENTITY MyParamEntity &quot;Has been expanded&quot;&gt; </code></pre> <hr /> <pre><code>&lt;!-- Within this comment I can use ]]&gt; and other reserved characters like &lt; &amp;, ', and &quot;, but %MyParamEntity; will not be expanded (if I retrieve the text of this node it will contain %MyParamEntity; and not &quot;Has been expanded&quot;) and I can't place two dashes next to each other. --&gt; </code></pre> <hr /> <pre><code>&lt;![CDATA[ Within this Character Data block I can use double dashes as much as I want (along with &lt;, &amp;, ', and &quot;) *and* %MyParamEntity; will be expanded to the text &quot;Has been expanded&quot; ... however, I can't use the CEND sequence. If I need to use CEND I must escape one of the brackets or the greater-than sign using concatenated CDATA sections. ]]&gt; </code></pre> <hr /> <pre><code>&lt;description&gt;An example of escaped CENDs&lt;/description&gt; &lt;!-- This text contains a CEND ]]&gt; --&gt; &lt;!-- In this first case we put the ]] at the end of the first CDATA block and the &gt; in the second CDATA block --&gt; &lt;data&gt;&lt;![CDATA[This text contains a CEND ]]]]&gt;&lt;![CDATA[&gt;]]&gt;&lt;/data&gt; &lt;!-- In this second case we put a ] at the end of the first CDATA block and the ]&gt; in the second CDATA block --&gt; &lt;alternative&gt;&lt;![CDATA[This text contains a CEND ]]]&gt;&lt;![CDATA[]&gt;]]&gt;&lt;/alternative&gt; </code></pre>
{ "question_id": 2784183, "question_date": "2010-05-06T20:20:50.813Z", "question_score": 1192, "tags": "xml|cdata", "answer_id": 2784200, "answer_date": "2010-05-06T20:23:37.230Z", "answer_score": 1135 }
Please answer the following Stack Overflow question: Title: Create a git patch from the uncommitted changes in the current working directory <p>Say I have uncommitted changes in my working directory. How can I make a patch from those without having to create a commit?</p>
<p><code>git diff</code> for unstaged changes.</p> <p><code>git diff --cached</code> for staged changes.</p> <p><code>git diff HEAD</code> for both staged and unstaged changes.</p>
{ "question_id": 5159185, "question_date": "2011-03-01T19:14:36.243Z", "question_score": 1192, "tags": "git|git-patch", "answer_id": 5159205, "answer_date": "2011-03-01T19:16:20.130Z", "answer_score": 541 }
Please answer the following Stack Overflow question: Title: How to overcome "datetime.datetime not JSON serializable"? <p>I have a basic dict as follows:</p> <pre class="lang-py prettyprint-override"><code>sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere </code></pre> <p>When I try to do <code>jsonify(sample)</code> I get:</p> <pre><code>TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable </code></pre> <p>What can I do such that my dictionary sample can overcome the error above?</p> <p><strong>Note:</strong> Though it may not be relevant, the dictionaries are generated from the retrieval of records out of <code>mongodb</code> where when I print out <code>str(sample['somedate'])</code>, the output is <code>2012-08-08 21:46:24.862000</code>.</p>
<h1>Updated for 2018</h1> <p>The original answer accommodated the way MongoDB "date" fields were represented as:</p> <p><code>{"$date": 1506816000000}</code></p> <p>If you want a generic Python solution for serializing <code>datetime</code> to json, check out <a href="https://stackoverflow.com/a/36142844/293064">@jjmontes' answer</a> for a quick solution which requires no dependencies.</p> <hr> <p>As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:<br> <a href="http://api.mongodb.org/python/1.10.1/api/bson/json_util.html" rel="noreferrer">http://api.mongodb.org/python/1.10.1/api/bson/json_util.html</a></p> <p>Example usage (serialization):</p> <pre><code>from bson import json_util import json json.dumps(anObject, default=json_util.default) </code></pre> <p>Example usage (deserialization):</p> <pre><code>json.loads(aJsonString, object_hook=json_util.object_hook) </code></pre> <hr> <h2>Django</h2> <p>Django provides a native <code>DjangoJSONEncoder</code> serializer that deals with this kind of properly.</p> <p>See <a href="https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder" rel="noreferrer">https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder</a></p> <pre><code>from django.core.serializers.json import DjangoJSONEncoder return json.dumps( item, sort_keys=True, indent=1, cls=DjangoJSONEncoder ) </code></pre> <p>One difference I've noticed between <code>DjangoJSONEncoder</code> and using a custom <code>default</code> like this:</p> <pre><code>import datetime import json def default(o): if isinstance(o, (datetime.date, datetime.datetime)): return o.isoformat() return json.dumps( item, sort_keys=True, indent=1, default=default ) </code></pre> <p>Is that Django strips a bit of the data:</p> <pre><code> "last_login": "2018-08-03T10:51:42.990", # DjangoJSONEncoder "last_login": "2018-08-03T10:51:42.990239", # default </code></pre> <p>So, you may need to be careful about that in some cases.</p>
{ "question_id": 11875770, "question_date": "2012-08-09T02:02:51.010Z", "question_score": 1191, "tags": "python|json", "answer_id": 11875813, "answer_date": "2012-08-09T02:07:57.893Z", "answer_score": 519 }
Please answer the following Stack Overflow question: Title: How do you get the index of the current iteration of a foreach loop? <p>Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?</p> <p>For instance, I currently do something like this depending on the circumstances:</p> <pre><code>int i = 0; foreach (Object o in collection) { // ... i++; } </code></pre>
<p>The <code>foreach</code> is for iterating over collections that implement <a href="http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx" rel="noreferrer"><code>IEnumerable</code></a>. It does this by calling <a href="http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx" rel="noreferrer"><code>GetEnumerator</code></a> on the collection, which will return an <a href="http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx" rel="noreferrer"><code>Enumerator</code></a>.</p> <p>This Enumerator has a method and a property:</p> <ul> <li><code>MoveNext()</code></li> <li><code>Current</code></li> </ul> <p><code>Current</code> returns the object that Enumerator is currently on, <code>MoveNext</code> updates <code>Current</code> to the next object.</p> <p>The concept of an index is foreign to the concept of enumeration, and cannot be done.</p> <p>Because of that, most collections are able to be traversed using an indexer and the for loop construct.</p> <p>I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.</p>
{ "question_id": 43021, "question_date": "2008-09-04T01:38:39.357Z", "question_score": 1190, "tags": "c#|foreach", "answer_id": 43029, "answer_date": "2008-09-04T01:46:08.323Z", "answer_score": 634 }
Please answer the following Stack Overflow question: Title: How do I trim whitespace? <p>Is there a Python function that will trim whitespace (spaces and tabs) from a string?</p> <p>So that given input <code>&quot; \t example string\t &quot;</code> becomes <code>&quot;example string&quot;</code>.</p>
<p>For whitespace on both sides, use <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="noreferrer"><code>str.strip</code></a>:</p> <pre><code>s = &quot; \t a string example\t &quot; s = s.strip() </code></pre> <p>For whitespace on the right side, use <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="noreferrer"><code>str.rstrip</code></a>:</p> <pre><code>s = s.rstrip() </code></pre> <p>For whitespace on the left side, use <a href="https://docs.python.org/3/library/stdtypes.html#str.lstrip" rel="noreferrer"><code>str.lstrip</code></a>:</p> <pre><code>s = s.lstrip() </code></pre> <p>You can provide an argument to strip arbitrary characters to any of these functions, like this:</p> <pre><code>s = s.strip(' \t\n\r') </code></pre> <p>This will strip any space, <code>\t</code>, <code>\n</code>, or <code>\r</code> characters from both sides of the string.</p> <p>The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try <a href="https://docs.python.org/3/library/re.html#re.sub" rel="noreferrer"><code>re.sub</code></a>:</p> <pre><code>import re print(re.sub('[\s+]', '', s)) </code></pre> <p>That should print out:</p> <pre><code>astringexample </code></pre>
{ "question_id": 1185524, "question_date": "2009-07-26T20:54:38.630Z", "question_score": 1190, "tags": "python|string|whitespace|trim|strip", "answer_id": 1185529, "answer_date": "2009-07-26T20:56:26.283Z", "answer_score": 1727 }
Please answer the following Stack Overflow question: Title: How does the SQL injection from the "Bobby Tables" XKCD comic work? <p>Just looking at:</p> <p><img src="https://i.stack.imgur.com/G0ifh.png" alt="XKCD Strip" title="Her daughter is named Help I&#39;m trapped in a driver&#39;s license factory."> <em>(Source: <a href="https://xkcd.com/327/" rel="noreferrer">https://xkcd.com/327/</a>)</em></p> <p>What does this SQL do:</p> <pre><code>Robert'); DROP TABLE STUDENTS; -- </code></pre> <p>I know both <code>'</code> and <code>--</code> are for comments, but doesn't the word <code>DROP</code> get commented as well since it is part of the same line?</p>
<p><strong>It drops the students table.</strong></p> <p>The original code in the school's program probably looks something like</p> <pre><code>q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')"; </code></pre> <p>This is the naive way to add text input into a query, and is <em>very bad</em>, as you will see.</p> <p>After the values from the first name, middle name textbox <em>FNMName.Text</em> (which is <code>Robert'); DROP TABLE STUDENTS; --</code>) and the last name textbox <em>LName.Text</em> (let's call it <code>Derper</code>) are concatenated with the rest of the query, the result is now actually <em>two queries</em> separated by the <a href="http://en.wikipedia.org/wiki/SQL#Language_elements" rel="noreferrer">statement terminator</a> (semicolon). The second query has been <strong>injected</strong> into the first. When the code executes this query against the database, it will look like this</p> <pre><code>INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper') </code></pre> <p>which, in plain English, roughly translates to the two queries:</p> <blockquote> <p>Add a new record to the Students table with a Name value of 'Robert'</p> </blockquote> <p>and</p> <blockquote> <p>Delete the Students table</p> </blockquote> <p>Everything past the second query is <a href="http://msdn.microsoft.com/en-us/library/ms181627.aspx" rel="noreferrer">marked as a comment</a>: <code>--', 'Derper')</code></p> <p>The <code>'</code> in the student's name is not a comment, it's the closing <a href="http://msdn.microsoft.com/en-us/library/ms179899.aspx" rel="noreferrer">string delimiter</a>. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work <em>when the SQL query they inject results in valid SQL</em>.</p> <p><sup><sup>Edited <strong><em>again</em></strong> as per <a href="https://stackoverflow.com/users/287586/dan04">dan04</a>'s astute comment</sup></sup></p>
{ "question_id": 332365, "question_date": "2008-12-01T21:50:10.220Z", "question_score": 1190, "tags": "security|validation|sql-injection", "answer_id": 332367, "answer_date": "2008-12-01T21:50:58.753Z", "answer_score": 1186 }
Please answer the following Stack Overflow question: Title: How can I undo pushed commits using git? <p>I have a project in a remote repository, synchronized with a local repository (development) and the server one (prod). I've been making some commited changes already pushed to remote and pulled from the server. Now, I want to undo those changes. So I could just <code>git checkout</code> to the commit before the changes and commit the new changes, but I'm guessing that there will be problems to push them again to remote. Any suggestion on how should I proceed? </p>
<p>You can revert individual commits with:</p> <pre class="lang-sh prettyprint-override"><code>git revert &lt;commit_hash&gt; </code></pre> <p>This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit, and not commits that come after that. If you want to revert a range of commits, you can do it like this:</p> <pre class="lang-sh prettyprint-override"><code>git revert &lt;oldest_commit_hash&gt;..&lt;latest_commit_hash&gt; </code></pre> <p>It reverts all the commits after <code>&lt;oldest_commit_hash&gt;</code> up to and including <code>&lt;latest_commit_hash&gt;</code>. On some versions of git it also reverts the <code>&lt;oldest_commit_hash&gt;</code>, so double check if that commit gets reverted or not. You can always drop the latest revert commit (which reverts the oldest commit) with <code>g reset --hard HEAD~</code>.</p> <p>To know the hash of the commit(s) you can use <code>git log</code>.</p> <p>Look at the <a href="https://git-scm.com/docs/git-revert" rel="noreferrer">git-revert man page</a> for more information about the <code>git revert</code> command. Also, look at <a href="https://stackoverflow.com/a/4114122/1248175">this answer</a> for more information about reverting commits.</p>
{ "question_id": 22682870, "question_date": "2014-03-27T09:11:42.877Z", "question_score": 1189, "tags": "git", "answer_id": 22683231, "answer_date": "2014-03-27T09:27:47.563Z", "answer_score": 1393 }
Please answer the following Stack Overflow question: Title: How to return dictionary keys as a list in Python? <p>With Python 2.7, I can get dictionary <em>keys</em>, <em>values</em>, or <em>items</em> as a <code>list</code>:</p> <pre><code>&gt;&gt;&gt; newdict = {1:0, 2:0, 3:0} &gt;&gt;&gt; newdict.keys() [1, 2, 3] </code></pre> <p>With Python &gt;= 3.3, I get:</p> <pre><code>&gt;&gt;&gt; newdict.keys() dict_keys([1, 2, 3]) </code></pre> <p>How do I get a plain <code>list</code> of keys with Python 3?</p>
<p>This will convert the <code>dict_keys</code> object to a <code>list</code>:</p> <pre><code>list(newdict.keys()) </code></pre> <hr /> <p>On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume <a href="https://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck typing</a> -- <em>if it looks like a duck and it quacks like a duck, it is a duck</em>. The <code>dict_keys</code> object can be <a href="https://stackoverflow.com/questions/9884132/what-exactly-are-iterator-iterable-and-iteration">iterated</a> over just like a <code>list</code>. For instance:</p> <pre><code>for key in newdict.keys(): print(key) </code></pre> <p>Note that <code>dict_keys</code> doesn't support insertion <code>newdict[k] = v</code>, though you may not need it.</p>
{ "question_id": 16819222, "question_date": "2013-05-29T16:24:16.313Z", "question_score": 1188, "tags": "python|python-3.x|list|dictionary|python-2.x", "answer_id": 16819250, "answer_date": "2013-05-29T16:25:40.847Z", "answer_score": 1467 }
Please answer the following Stack Overflow question: Title: Detecting a mobile browser <p>I'm looking for a function that returns a boolean value if the user is using a mobile browser or not.</p> <p>I know that I can use <code>navigator.userAgent</code> and write that function by using regex, but user-agents are too various for different platforms. I doubt that matching all possible devices would be easy, and I think this problem has been solved many times so there should be some kind of complete solution for such a task.</p> <p>I was looking at <a href="http://detectmobilebrowsers.com" rel="nofollow noreferrer">this site</a>, but sadly the script is so cryptic that I have no idea how to use it for my purpose, which is to create a function that returns true/false.</p>
<h2>Using Regex (from <a href="http://detectmobilebrowsers.com" rel="noreferrer">detectmobilebrowsers.com</a>):</h2> <p>Here's a function that uses an insanely long and comprehensive regex which returns a <code>true</code> or <code>false</code> value depending on whether or not the user is browsing with a mobile.</p> <pre><code>window.mobileCheck = function() { let check = false; (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera); return check; }; </code></pre> <p>For those wishing to include tablets in this test (though arguably, you shouldn't), you can use the following function:</p> <pre><code>window.mobileAndTabletCheck = function() { let check = false; (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera); return check; }; </code></pre> <hr /> <h2>Using navigator.userAgentData</h2> <p>You may also use <code>navigator.userAgentData.mobile</code>, but <code>userAgentData</code> is still experimental, so it is not recommended for use in production.</p> <pre class="lang-js prettyprint-override"><code>const isMobile = navigator.userAgentData.mobile; //resolves true/false </code></pre> <p><a href="https://caniuse.com/mdn-api_navigator_useragentdata" rel="noreferrer">Compatibility chart for userAgentData</a></p> <hr /> <h2>The Original Answer</h2> <p>You can do this by simply running through a list of devices and checking if the <code>useragent</code> matches anything like so:</p> <pre><code> function detectMob() { const toMatch = [ /Android/i, /webOS/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i ]; return toMatch.some((toMatchItem) =&gt; { return navigator.userAgent.match(toMatchItem); }); } </code></pre> <p>However since you believe that this method is unreliable, You could assume that any device that had a resolution of <em>800x600</em> or less was a mobile device too, narrowing your target even more (although these days many mobile devices have much greater resolutions than this)</p> <p>i.e</p> <pre><code> function detectMob() { return ( ( window.innerWidth &lt;= 800 ) &amp;&amp; ( window.innerHeight &lt;= 600 ) ); } </code></pre> <p><strong>Reference:</strong></p> <ul> <li><a href="http://www.quirksmode.org/js/detect.html" rel="noreferrer">Detecting Browser and Devices with javascript</a></li> </ul>
{ "question_id": 11381673, "question_date": "2012-07-08T08:13:21.883Z", "question_score": 1188, "tags": "javascript|browser-detection|mobile-browser|platform-detection", "answer_id": 11381730, "answer_date": "2012-07-08T08:24:22.633Z", "answer_score": 1677 }
Please answer the following Stack Overflow question: Title: How to get the difference between two arrays in JavaScript? <p>Is there a way to return the difference between two arrays in JavaScript?</p> <p>For example:</p> <pre class="lang-js prettyprint-override"><code>var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd']; // need ["c", "d"] </code></pre>
<p>This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be</p> <pre><code>let difference = arr1.filter(x =&gt; !arr2.includes(x)); </code></pre> <p>(credits to other author here)</p> <p>I assume you are comparing a normal array. If not, you need to change the <em>for</em> loop to a <em>for .. in</em> loop.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function arr_diff (a1, a2) { var a = [], diff = []; for (var i = 0; i &lt; a1.length; i++) { a[a1[i]] = true; } for (var i = 0; i &lt; a2.length; i++) { if (a[a2[i]]) { delete a[a2[i]]; } else { a[a2[i]] = true; } } for (var k in a) { diff.push(k); } return diff; } console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd'])); console.log(arr_diff("abcd", "abcde")); console.log(arr_diff("zxc", "zxc"));</code></pre> </div> </div> </p>
{ "question_id": 1187518, "question_date": "2009-07-27T10:38:50.100Z", "question_score": 1185, "tags": "javascript|arrays|array-difference", "answer_id": 1187628, "answer_date": "2009-07-27T11:20:33.540Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: Git: Create a branch from unstaged/uncommitted changes on master <p>Context: I'm working on master adding a simple feature. After a few minutes I realize it was not so simple and it should have been better to work into a new branch.</p> <p>This always happens to me and I have no idea how to switch to another branch and take all these uncommited changes with me leaving the master branch clean. I supposed <code>git stash &amp;&amp; git stash branch new_branch</code> would simply accomplish that but this is what I get:</p> <pre><code>~/test $ git status # On branch master nothing to commit (working directory clean) ~/test $ echo "hello!" &gt; testing ~/test $ git status # On branch master # Changed but not updated: # (use "git add &lt;file&gt;..." to update what will be committed) # (use "git checkout -- &lt;file&gt;..." to discard changes in working directory) # # modified: testing # no changes added to commit (use "git add" and/or "git commit -a") ~/test $ git stash Saved working directory and index state WIP on master: 4402b8c testing HEAD is now at 4402b8c testing ~/test $ git status # On branch master nothing to commit (working directory clean) ~/test $ git stash branch new_branch Switched to a new branch 'new_branch' # On branch new_branch # Changed but not updated: # (use "git add &lt;file&gt;..." to update what will be committed) # (use "git checkout -- &lt;file&gt;..." to discard changes in working directory) # # modified: testing # no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (db1b9a3391a82d86c9fdd26dab095ba9b820e35b) ~/test $ git s # On branch new_branch # Changed but not updated: # (use "git add &lt;file&gt;..." to update what will be committed) # (use "git checkout -- &lt;file&gt;..." to discard changes in working directory) # # modified: testing # no changes added to commit (use "git add" and/or "git commit -a") ~/test $ git checkout master M testing Switched to branch 'master' ~/test $ git status # On branch master # Changed but not updated: # (use "git add &lt;file&gt;..." to update what will be committed) # (use "git checkout -- &lt;file&gt;..." to discard changes in working directory) # # modified: testing # no changes added to commit (use "git add" and/or "git commit -a") </code></pre> <p>Do you know if there is any way of accomplishing this?</p>
<p>No need to stash.</p> <h1>Update 2020 / Git 2.23</h1> <hr /> <p>Git 2.23 adds the new <code>switch</code> subcommand, in an attempt to clear some of the confusion caused by the overloaded usage of <code>checkout</code> (switching branches, restoring files, detaching HEAD, etc.)</p> <p>Starting with this version of Git, replace the <code>git checkout</code> command below with:</p> <pre><code>git switch -c &lt;new-branch&gt; </code></pre> <p>The behavior remains unchanged.</p> <h1>Before Update 2020 / Git 2.23</h1> <hr /> <pre><code>git checkout -b new_branch_name </code></pre> <p>does not touch your local changes. It just creates the branch from the current HEAD and sets the HEAD there. So I guess that's what you want.</p> <p><strong>--- Edit to explain the result of checkout master ---</strong></p> <p>Are you confused because <code>checkout master</code> does not discard your changes?</p> <p>Since the changes are only local, git does not want you to lose them too easily. Upon changing branch, git does not overwrite your local changes. The result of your <code>checkout master</code> is:</p> <pre><code>M testing </code></pre> <p>, which means that your working files are not clean. git did change the HEAD, but did not overwrite your local files. That is why your last status still show your local changes, although you are on <code>master</code>.</p> <p>If you really want to discard the local changes, you have to force the checkout with <code>-f</code>.</p> <pre><code>git checkout master -f </code></pre> <p>Since your changes were never committed, you'd lose them.</p> <p>Try to get back to your branch, commit your changes, then checkout the master again.</p> <pre><code>git checkout new_branch git commit -a -m&quot;edited&quot; git checkout master git status </code></pre> <p>You should get a <code>M</code> message after the first checkout, but then not anymore after the <code>checkout master</code>, and <code>git status</code> should show no modified files.</p> <p><strong>--- Edit to clear up confusion about working directory (local files)---</strong></p> <p>In answer to your first comment, local changes are just... well, local. Git does not save them automatically, you must tell it to save them for later. If you make changes and do not explicitly commit or stash them, git will not version them. If you change HEAD (<code>checkout master</code>), the local changes are not overwritten since unsaved.</p>
{ "question_id": 2569459, "question_date": "2010-04-02T22:09:59.533Z", "question_score": 1183, "tags": "git|git-stash", "answer_id": 2569513, "answer_date": "2010-04-02T22:25:50.050Z", "answer_score": 1433 }
Please answer the following Stack Overflow question: Title: What is the difference between a Docker image and a container? <p>When using Docker, we start with a base image. We boot it up, create changes and those changes are saved in layers forming another image.</p> <p>So eventually I have an image for my PostgreSQL instance and an image for my web application, changes to which keep on being persisted.</p> <p>What is a container?</p>
<p>An instance of an image is called a container. You have an image, which is a set of layers as you describe. If you start this image, you have a running container of this image. You can have many running containers of the same image.</p> <p>You can see all your images with <code>docker images</code> whereas you can see your running containers with <code>docker ps</code> (and you can see all containers with <code>docker ps -a</code>).</p> <p>So a running instance of an image is a container.</p>
{ "question_id": 23735149, "question_date": "2014-05-19T10:15:27.250Z", "question_score": 1182, "tags": "docker|docker-container|docker-image", "answer_id": 23736802, "answer_date": "2014-05-19T11:40:01.333Z", "answer_score": 1562 }
Please answer the following Stack Overflow question: Title: What is the difference between public, private, and protected inheritance in C++? <p>What is the difference between <code>public</code>, <code>private</code>, and <code>protected</code> inheritance in C++?</p> <p>All of the questions I've found on SO deal with specific cases.</p>
<p>To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".</p> <p>There are three accessors that I'm aware of: <code>public</code>, <code>protected</code> and <code>private</code>. </p> <p>Let:</p> <pre><code>class Base { public: int publicMember; protected: int protectedMember; private: int privateMember; }; </code></pre> <ul> <li>Everything that is aware of <code>Base</code> is also aware that <code>Base</code> contains <code>publicMember</code>.</li> <li>Only the children (and their children) are aware that <code>Base</code> contains <code>protectedMember</code>.</li> <li>No one but <code>Base</code> is aware of <code>privateMember</code>.</li> </ul> <p>By "is aware of", I mean "acknowledge the existence of, and thus be able to access".</p> <h2>next:</h2> <p>The same happens with public, private and protected inheritance. Let's consider a class <code>Base</code> and a class <code>Child</code> that inherits from <code>Base</code>.</p> <ul> <li>If the inheritance is <code>public</code>, everything that is aware of <code>Base</code> and <code>Child</code> is also aware that <code>Child</code> inherits from <code>Base</code>.</li> <li>If the inheritance is <code>protected</code>, only <code>Child</code>, and its children, are aware that they inherit from <code>Base</code>.</li> <li>If the inheritance is <code>private</code>, no one other than <code>Child</code> is aware of the inheritance.</li> </ul>
{ "question_id": 860339, "question_date": "2009-05-13T20:47:07.410Z", "question_score": 1180, "tags": "c++|inheritance|encapsulation|access-specifier|c++-faq", "answer_id": 860353, "answer_date": "2009-05-13T20:49:37.733Z", "answer_score": 1169 }
Please answer the following Stack Overflow question: Title: How to pass command line arguments to a rake task <p>I have a rake task that needs to insert a value into multiple databases. </p> <p>I'd like to pass this value into the rake task from the command line, or from <em>another</em> rake task.</p> <p>How can I do this?</p>
<p>Options and dependencies need to be inside arrays:</p> <pre><code>namespace :thing do desc &quot;it does a thing&quot; task :work, [:option, :foo, :bar] do |task, args| puts &quot;work&quot;, args end task :another, [:option, :foo, :bar] do |task, args| puts &quot;another #{args}&quot; Rake::Task[&quot;thing:work&quot;].invoke(args[:option], args[:foo], args[:bar]) # or splat the args # Rake::Task[&quot;thing:work&quot;].invoke(*args) end end </code></pre> <p>Then</p> <pre><code>rake thing:work[1,2,3] =&gt; work: {:option=&gt;&quot;1&quot;, :foo=&gt;&quot;2&quot;, :bar=&gt;&quot;3&quot;} rake thing:another[1,2,3] =&gt; another {:option=&gt;&quot;1&quot;, :foo=&gt;&quot;2&quot;, :bar=&gt;&quot;3&quot;} =&gt; work: {:option=&gt;&quot;1&quot;, :foo=&gt;&quot;2&quot;, :bar=&gt;&quot;3&quot;} </code></pre> <blockquote> <p>NOTE: variable <code>task</code> is the task object, not very helpful unless you know/care about Rake internals.</p> </blockquote> <p><strong>RAILS NOTE:</strong></p> <blockquote> <p>If running the task from Rails, it's best to preload the environment by adding <code>=&gt; [:environment]</code> which is a way to setup <em>dependent</em> tasks.</p> </blockquote> <pre><code> task :work, [:option, :foo, :bar] =&gt; [:environment] do |task, args| puts &quot;work&quot;, args end </code></pre>
{ "question_id": 825748, "question_date": "2009-05-05T16:27:50.517Z", "question_score": 1180, "tags": "ruby|command-line|rake|command-line-arguments", "answer_id": 29502094, "answer_date": "2015-04-07T21:56:36.850Z", "answer_score": 448 }
Please answer the following Stack Overflow question: Title: How do I use 'git reset --hard HEAD' to revert to a previous commit? <p>I know that Git tracks changes I make to my application, and holds on to them until I commit the changes.</p> <p>To revert to a previous commit, I used:</p> <pre><code>$ git reset --hard HEAD HEAD is now at 820f417 micro </code></pre> <p>How do I then revert the files on my hard drive back to that previous commit?</p> <p>My next steps were:</p> <pre><code>git add . git commit -m &quot;revert&quot; </code></pre> <p>But none of the files have changed on my hard drive...</p>
<p>First, it's always worth noting that <code>git reset --hard</code> is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of <code>git status</code> is clean (that is, empty) before using it.</p> <p>Initially you say the following:</p> <blockquote> <p>So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:</p> </blockquote> <p>That's incorrect. Git only records the state of the files when you stage them (with <code>git add</code>) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do <code>git add</code> to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)</p> <p>In your question you then go on to ask the following:</p> <blockquote> <p>When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro</p> <p>How do I then revert the files on my hard drive back to that previous commit?</p> </blockquote> <p>If you do <code>git reset --hard &lt;SOME-COMMIT&gt;</code> then Git will:</p> <ul> <li>Make your current branch (typically <code>master</code>) back to point at <code>&lt;SOME-COMMIT&gt;</code>.</li> <li>Then make the files in your working tree and the index ("staging area") the same as the versions committed in <code>&lt;SOME-COMMIT&gt;</code>.</li> </ul> <p><code>HEAD</code> points to your current branch (or current commit), so all that <code>git reset --hard HEAD</code> will do is to throw away any uncommitted changes you have.</p> <p>So, suppose the good commit that you want to go back to is <code>f414f31</code>. (You can find that via <code>git log</code> or any history browser.) You then have a few different options depending on exactly what you want to do:</p> <ul> <li>Change your current branch to point to the older commit instead. You could do that with <code>git reset --hard f414f31</code>. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after <code>f414f31</code> will no longer be in the history of your <code>master</code> branch.</li> <li><p>Create a new commit that represents exactly the same state of the project as <code>f414f31</code>, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in <a href="https://stackoverflow.com/a/1895095/223092">this answer</a> - something like:</p> <pre><code>git reset --hard f414f31 git reset --soft HEAD@{1} git commit -m "Reverting to the state of the project at f414f31" </code></pre></li> </ul>
{ "question_id": 9529078, "question_date": "2012-03-02T06:36:06.677Z", "question_score": 1179, "tags": "git|head|git-reset|git-revert", "answer_id": 9530204, "answer_date": "2012-03-02T08:32:00.687Z", "answer_score": 1355 }
Please answer the following Stack Overflow question: Title: How do I provide a username and password when running "git clone [email protected]"? <p>I know how to provide a username and password to an HTTPS request like this:</p> <pre><code>git clone https://username:password@remote </code></pre> <p>But I'd like to know how to provide a username and password to the remote like this:</p> <pre><code>git clone [email protected] </code></pre> <p>I've tried like this:</p> <pre><code>git clone username:password@[email protected] git clone git@username:[email protected] git clone [email protected]@username:password </code></pre> <p>But they haven't worked.</p>
<p>Based on Michael Scharf's comment:</p> <p>You can leave out the password so that it won't be logged in your Bash history file:</p> <pre><code>git clone https://[email protected]/username/repository.git </code></pre> <p>It will prompt you for your password.</p> <p>Alternatively, you may use:</p> <pre><code>git clone https://username:[email protected]/username/repository.git </code></pre> <p>This way worked for me from a GitHub repository.</p>
{ "question_id": 10054318, "question_date": "2012-04-07T12:05:22.687Z", "question_score": 1179, "tags": "git", "answer_id": 10054470, "answer_date": "2012-04-07T12:25:00.737Z", "answer_score": 1775 }
Please answer the following Stack Overflow question: Title: Get list of all tables in Oracle? <p>How do I query an Oracle database to display the names of all tables in it?</p>
<pre><code>SELECT owner, table_name FROM dba_tables </code></pre> <p>This is assuming that you have access to the <code>DBA_TABLES</code> data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the <code>SELECT ANY DICTIONARY</code> privilege or the <code>SELECT_CATALOG_ROLE</code> role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like <code>SYS</code> and <code>SYSTEM</code> which have large numbers of Oracle tables that you probably don't care about.</p> <p>Alternatively, if you do not have access to <code>DBA_TABLES</code>, you can see all the tables that your account has access to through the <code>ALL_TABLES</code> view:</p> <pre><code>SELECT owner, table_name FROM all_tables </code></pre> <p>Although, that may be a subset of the tables available in the database (<code>ALL_TABLES</code> shows you the information for all the tables that your user has been granted access to). </p> <p>If you are only concerned with the tables that you own, not those that you have access to, you could use <code>USER_TABLES</code>:</p> <pre><code>SELECT table_name FROM user_tables </code></pre> <p>Since <code>USER_TABLES</code> only has information about the tables that you own, it does not have an <code>OWNER</code> column – the owner, by definition, is you.</p> <p>Oracle also has a number of legacy data dictionary views-- <code>TAB</code>, <code>DICT</code>, <code>TABS</code>, and <code>CAT</code> for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the <code>TAB</code> and <code>CAT</code> views both show information about tables that are in the user's recycle bin while the <code>[DBA|ALL|USER]_TABLES</code> views all filter those out. <code>CAT</code> also shows information about materialized view logs with a <code>TABLE_TYPE</code> of "TABLE" which is unlikely to be what you really want. <code>DICT</code> combines tables and synonyms and doesn't tell you who owns the object.</p>
{ "question_id": 205736, "question_date": "2008-10-15T17:54:49.387Z", "question_score": 1178, "tags": "sql|oracle", "answer_id": 205746, "answer_date": "2008-10-15T17:56:47.607Z", "answer_score": 1436 }
Please answer the following Stack Overflow question: Title: Parsing JSON with Unix tools <p>I'm trying to parse JSON returned from a curl request, like so:</p> <pre><code>curl 'http://twitter.com/users/username.json' | sed -e 's/[{}]/''/g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i&lt;=n; i++) print a[i]}' </code></pre> <p>The above splits the JSON into fields, for example:</p> <pre><code>% ... "geo_enabled":false "friends_count":245 "profile_text_color":"000000" "status":"in_reply_to_screen_name":null "source":"web" "truncated":false "text":"My status" "favorited":false % ... </code></pre> <p>How do I print a specific field (denoted by the <code>-v k=text</code>)?</p>
<p>There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as <a href="https://stedolan.github.io/jq/" rel="noreferrer"><code>jq</code></a>:</p> <pre><code>curl -s 'https://api.github.com/users/lambda' | jq -r '.name' </code></pre> <p>You can also do this with tools that are likely already installed on your system, like Python using the <a href="https://docs.python.org/2/library/json.html" rel="noreferrer"><code>json</code> module</a>, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:</p> <p>Python 3:</p> <pre><code>curl -s 'https://api.github.com/users/lambda' | \ python3 -c &quot;import sys, json; print(json.load(sys.stdin)['name'])&quot; </code></pre> <p>Python 2:</p> <pre><code>export PYTHONIOENCODING=utf8 curl -s 'https://api.github.com/users/lambda' | \ python2 -c &quot;import sys, json; print json.load(sys.stdin)['name']&quot; </code></pre> <h2>Frequently Asked Questions</h2> <h3>Why not a pure shell solution?</h3> <p>The standard <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html" rel="noreferrer">POSIX/Single Unix Specification shell</a> is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are <a href="https://stackoverflow.com/questions/688849/associative-arrays-in-shell-scripts">somewhat hacky ways to do it</a>, but many of them can break if keys or values contain certain special characters.</p> <p>Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.</p> <p>Finally, writing a full fledged JSON parser in shell would be a significant enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.</p> <h3>Why not use awk, sed, or grep?</h3> <p>It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.</p> <p>However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.</p> <p>So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on <code>jq</code> or Python.</p> <p>I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.</p> <h2>Historical notes</h2> <p>This answer originally recommended <a href="http://github.com/micha/jsawk" rel="noreferrer">jsawk</a>, which should still work, but is a little more cumbersome to use than <code>jq</code>, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:</p> <pre><code>curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name' </code></pre> <p>This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:</p> <pre><code>curl 'http://twitter.com/users/username.json' | jq -r '.text' </code></pre>
{ "question_id": 1955505, "question_date": "2009-12-23T21:46:58.987Z", "question_score": 1178, "tags": "json|bash|parsing", "answer_id": 1955555, "answer_date": "2009-12-23T21:59:30.743Z", "answer_score": 1582 }