input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Updating address bar with new URL without hash or reloading the page <p>I either dreamt about chrome (dev channel) implementing a way to update the address bar via javascript (the path, not domain) without reloading the page or they really have done this.</p> <p>However, I can't find the article I <em>think</em> I read.</p> <p>Am I crazy or is there a way to do this (in Chrome)?</p> <p>p.s. I'm not talking about window.location.hash, et al. If the above exists <a href="https://stackoverflow.com/a/824356/160173">the answer to this question</a> will be untrue.</p>
<p><strong>You can now do this in most "modern" browsers!</strong></p> <p>Here is the original article I read (posted July 10, 2010): <a href="http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/" rel="noreferrer">HTML5: Changing the browser-URL without refreshing page</a>.</p> <p>For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API" rel="noreferrer">see the MDN docs</a>.</p> <p>TL;DR, you can do this:</p> <pre><code>window.history.pushState("object or string", "Title", "/new-url"); </code></pre> <p>See my answer to <a href="https://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page/3354511#3354511">Modify the URL without reloading the page</a> for a basic how-to.</p>
{ "question_id": 3338642, "question_date": "2010-07-26T20:18:20.853Z", "question_score": 724, "tags": "javascript|ajax|google-chrome", "answer_id": 3340186, "answer_date": "2010-07-27T01:34:41.593Z", "answer_score": 971 }
Please answer the following Stack Overflow question: Title: Are PDO prepared statements sufficient to prevent SQL injection? <p>Let's say I have code like this:</p> <pre><code>$dbh = new PDO("blahblah"); $stmt = $dbh-&gt;prepare('SELECT * FROM users where username = :username'); $stmt-&gt;execute( array(':username' =&gt; $_REQUEST['username']) ); </code></pre> <p>The PDO documentation says:</p> <blockquote> <p>The parameters to prepared statements don't need to be quoted; the driver handles it for you.</p> </blockquote> <p><strong>Is that truly all I need to do to avoid SQL injections? Is it really that easy?</strong></p> <p>You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.</p>
<p>The short answer is <strong>NO</strong>, PDO prepares will not defend you from all possible SQL-Injection attacks. For certain obscure edge-cases.</p> <p>I'm adapting <a href="https://stackoverflow.com/a/12118602/338665">this answer</a> to talk about PDO...</p> <p>The long answer isn't so easy. It's based off an attack <a href="http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string" rel="noreferrer">demonstrated here</a>.</p> <h1>The Attack</h1> <p>So, let's start off by showing the attack...</p> <pre><code>$pdo-&gt;query('SET NAMES gbk'); $var = "\xbf\x27 OR 1=1 /*"; $query = 'SELECT * FROM test WHERE name = ? LIMIT 1'; $stmt = $pdo-&gt;prepare($query); $stmt-&gt;execute(array($var)); </code></pre> <p>In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:</p> <ol> <li><p><strong>Selecting a Character Set</strong></p> <pre><code>$pdo-&gt;query('SET NAMES gbk'); </code></pre> <p>For this attack to work, we need the encoding that the server's expecting on the connection both to encode <code>'</code> as in ASCII i.e. <code>0x27</code> <em>and</em> to have some character whose final byte is an ASCII <code>\</code> i.e. <code>0x5c</code>. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: <code>big5</code>, <code>cp932</code>, <code>gb2312</code>, <code>gbk</code> and <code>sjis</code>. We'll select <code>gbk</code> here.</p> <p>Now, it's very important to note the use of <code>SET NAMES</code> here. This sets the character set <strong>ON THE SERVER</strong>. There is another way of doing it, but we'll get there soon enough.</p></li> <li><p><strong>The Payload</strong></p> <p>The payload we're going to use for this injection starts with the byte sequence <code>0xbf27</code>. In <code>gbk</code>, that's an invalid multibyte character; in <code>latin1</code>, it's the string <code>¿'</code>. Note that in <code>latin1</code> <strong>and</strong> <code>gbk</code>, <code>0x27</code> on its own is a literal <code>'</code> character. </p> <p>We have chosen this payload because, if we called <code>addslashes()</code> on it, we'd insert an ASCII <code>\</code> i.e. <code>0x5c</code>, before the <code>'</code> character. So we'd wind up with <code>0xbf5c27</code>, which in <code>gbk</code> is a two character sequence: <code>0xbf5c</code> followed by <code>0x27</code>. Or in other words, a <em>valid</em> character followed by an unescaped <code>'</code>. But we're not using <code>addslashes()</code>. So on to the next step...</p></li> <li><p><strong>$stmt->execute()</strong></p> <p>The important thing to realize here is that PDO by default does <strong>NOT</strong> do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling <code>mysql_real_escape_string()</code> (the MySQL C API function) on each bound string value.</p> <p>The C API call to <code>mysql_real_escape_string()</code> differs from <code>addslashes()</code> in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using <code>latin1</code> for the connection, because we never told it otherwise. We did tell the <em>server</em> we're using <code>gbk</code>, but the <em>client</em> still thinks it's <code>latin1</code>.</p> <p>Therefore the call to <code>mysql_real_escape_string()</code> inserts the backslash, and we have a free hanging <code>'</code> character in our "escaped" content! In fact, if we were to look at <code>$var</code> in the <code>gbk</code> character set, we'd see:</p> <pre>縗' OR 1=1 /*</pre> <p>Which is exactly what the attack requires.</p></li> <li><p><strong>The Query</strong></p> <p>This part is just a formality, but here's the rendered query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1 </code></pre></li> </ol> <p>Congratulations, you just successfully attacked a program using PDO Prepared Statements...</p> <h1>The Simple Fix</h1> <p>Now, it's worth noting that you can prevent this by disabling emulated prepared statements:</p> <pre><code>$pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); </code></pre> <p>This will <em>usually</em> result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently <a href="https://github.com/php/php-src/blob/master/ext/pdo_mysql/mysql_driver.c#L210" rel="noreferrer">fallback</a> to emulating statements that MySQL can't prepare natively: those that it can are <a href="http://dev.mysql.com/doc/en/sql-syntax-prepared-statements.html" rel="noreferrer">listed</a> in the manual, but beware to select the appropriate server version).</p> <h1>The Correct Fix</h1> <p>The problem here is that we didn't call the C API's <code>mysql_set_charset()</code> instead of <code>SET NAMES</code>. If we did, we'd be fine provided we are using a MySQL release since 2006.</p> <p>If you're using an earlier MySQL release, then a <a href="http://bugs.mysql.com/bug.php?id=8378" rel="noreferrer">bug</a> in <code>mysql_real_escape_string()</code> meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes <em>even if the client had been correctly informed of the connection encoding</em> and so this attack would still succeed. The bug was fixed in MySQL <a href="http://dev.mysql.com/doc/refman/4.1/en/news-4-1-20.html" rel="noreferrer">4.1.20</a>, <a href="http://dev.mysql.com/doc/relnotes/mysql/5.0/en/news-5-0-22.html" rel="noreferrer">5.0.22</a> and <a href="http://dev.mysql.com/doc/relnotes/mysql/5.1/en/news-5-1-11.html" rel="noreferrer">5.1.11</a>.</p> <p>But the worst part is that <code>PDO</code> didn't expose the C API for <code>mysql_set_charset()</code> until 5.3.6, so in prior versions it <strong>cannot</strong> prevent this attack for every possible command! It's now exposed as a <a href="http://www.php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">DSN parameter</a>, which should be used <strong>instead of</strong> <code>SET NAMES</code>...</p> <h1>The Saving Grace</h1> <p>As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. <a href="http://dev.mysql.com/doc/en/charset-unicode-utf8mb4.html" rel="noreferrer"><code>utf8mb4</code></a> is <em>not vulnerable</em> and yet can support <em>every</em> Unicode character: so you could elect to use that instead&mdash;but it has only been available since MySQL 5.5.3. An alternative is <a href="http://dev.mysql.com/doc/en/charset-unicode-utf8.html" rel="noreferrer"><code>utf8</code></a>, which is also <em>not vulnerable</em> and can support the whole of the Unicode <a href="http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane" rel="noreferrer">Basic Multilingual Plane</a>.</p> <p>Alternatively, you can enable the <a href="http://dev.mysql.com/doc/en/sql-mode.html#sqlmode_no_backslash_escapes" rel="noreferrer"><code>NO_BACKSLASH_ESCAPES</code></a> SQL mode, which (amongst other things) alters the operation of <code>mysql_real_escape_string()</code>. With this mode enabled, <code>0x27</code> will be replaced with <code>0x2727</code> rather than <code>0x5c27</code> and thus the escaping process <em>cannot</em> create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. <code>0xbf27</code> is still <code>0xbf27</code> etc.)&mdash;so the server will still reject the string as invalid. However, see <a href="https://stackoverflow.com/a/23277864/623041">@eggyal's answer</a> for a different vulnerability that can arise from using this SQL mode (albeit not with PDO).</p> <h1>Safe Examples</h1> <p>The following examples are safe:</p> <pre><code>mysql_query('SET NAMES utf8'); $var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*"); mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); </code></pre> <p>Because the server's expecting <code>utf8</code>...</p> <pre><code>mysql_set_charset('gbk'); $var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*"); mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); </code></pre> <p>Because we've properly set the character set so the client and the server match.</p> <pre><code>$pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo-&gt;query('SET NAMES gbk'); $stmt = $pdo-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt-&gt;execute(array("\xbf\x27 OR 1=1 /*")); </code></pre> <p>Because we've turned off emulated prepared statements.</p> <pre><code>$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password); $stmt = $pdo-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt-&gt;execute(array("\xbf\x27 OR 1=1 /*")); </code></pre> <p>Because we've set the character set properly.</p> <pre><code>$mysqli-&gt;query('SET NAMES gbk'); $stmt = $mysqli-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $param = "\xbf\x27 OR 1=1 /*"; $stmt-&gt;bind_param('s', $param); $stmt-&gt;execute(); </code></pre> <p>Because MySQLi does true prepared statements all the time.</p> <h1>Wrapping Up</h1> <p>If you:</p> <ul> <li>Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) <strong>AND</strong> PDO's DSN charset parameter (in PHP ≥ 5.3.6)</li> </ul> <p><strong>OR</strong></p> <ul> <li>Don't use a vulnerable character set for connection encoding (you only use <code>utf8</code> / <code>latin1</code> / <code>ascii</code> / etc)</li> </ul> <p><strong>OR</strong></p> <ul> <li>Enable <code>NO_BACKSLASH_ESCAPES</code> SQL mode</li> </ul> <p>You're 100% safe.</p> <p>Otherwise, you're vulnerable <strong>even though you're using PDO Prepared Statements...</strong></p> <h1>Addendum</h1> <p>I've been slowly working on a patch to change the default to not emulate prepares for a future version of PHP. The problem that I'm running into is that a LOT of tests break when I do that. One problem is that emulated prepares will only throw syntax errors on execute, but true prepares will throw errors on prepare. So that can cause issues (and is part of the reason tests are borking).</p>
{ "question_id": 134099, "question_date": "2008-09-25T15:43:35.270Z", "question_score": 724, "tags": "php|security|pdo|sql-injection", "answer_id": 12202218, "answer_date": "2012-08-30T17:22:04.327Z", "answer_score": 905 }
Please answer the following Stack Overflow question: Title: How do I compare strings in Java? <p>I've been using the <code>==</code> operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into <code>.equals()</code> instead, and it fixed the bug.</p> <p>Is <code>==</code> bad? When should it and should it not be used? What's the difference?</p>
<p><code>==</code> tests for reference equality (whether they are the same object).</p> <p><code>.equals()</code> tests for value equality (whether they are logically &quot;equal&quot;).</p> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)" rel="noreferrer">Objects.equals()</a> checks for <code>null</code> before calling <code>.equals()</code> so you don't have to (available as of JDK7, also available in <a href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#equals" rel="noreferrer">Guava</a>).</p> <p>Consequently, if you want to test whether two strings have the same value you will probably want to use <code>Objects.equals()</code>.</p> <pre><code>// These two have the same value new String(&quot;test&quot;).equals(&quot;test&quot;) // --&gt; true // ... but they are not the same object new String(&quot;test&quot;) == &quot;test&quot; // --&gt; false // ... neither are these new String(&quot;test&quot;) == new String(&quot;test&quot;) // --&gt; false // ... but these are because literals are interned by // the compiler and thus refer to the same object &quot;test&quot; == &quot;test&quot; // --&gt; true // ... string literals are concatenated by the compiler // and the results are interned. &quot;test&quot; == &quot;te&quot; + &quot;st&quot; // --&gt; true // ... but you should really just call Objects.equals() Objects.equals(&quot;test&quot;, new String(&quot;test&quot;)) // --&gt; true Objects.equals(null, &quot;test&quot;) // --&gt; false Objects.equals(null, null) // --&gt; true </code></pre> <p>You almost <strong>always</strong> want to use <code>Objects.equals()</code>. In the <strong>rare</strong> situation where you <strong>know</strong> you're dealing with <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--" rel="noreferrer">interned</a> strings, you <em>can</em> use <code>==</code>.</p> <p>From <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5" rel="noreferrer">JLS 3.10.5. <em>String Literals</em></a>:</p> <blockquote> <p>Moreover, a string literal always refers to the <em>same</em> instance of class <code>String</code>. This is because string literals - or, more generally, strings that are the values of constant expressions (<a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28" rel="noreferrer">§15.28</a>) - are &quot;interned&quot; so as to share unique instances, using the method <code>String.intern</code>.</p> </blockquote> <p>Similar examples can also be found in <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634" rel="noreferrer">JLS 3.10.5-1</a>.</p> <h3>Other Methods To Consider</h3> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-" rel="noreferrer">String.equalsIgnoreCase()</a> value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see <a href="https://stackoverflow.com/questions/44238749/equalsignorecase-not-working-as-intended">this question</a>.</p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contentEquals-java.lang.CharSequence-" rel="noreferrer">String.contentEquals()</a> compares the content of the <code>String</code> with the content of any <code>CharSequence</code> (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.</p>
{ "question_id": 513832, "question_date": "2009-02-04T23:17:07.873Z", "question_score": 723, "tags": "java|string|equality", "answer_id": 513839, "answer_date": "2009-02-04T23:19:49.770Z", "answer_score": 5963 }
Please answer the following Stack Overflow question: Title: Copy all the lines to clipboard <p>Is there any way to copy all lines from open file to clipboard in VI editor. I tried <kbd>y</kbd><kbd>G</kbd> but it's not using clipboard to store those lines. </p> <p>So is it possible?</p>
<p>You should yank the text to the <code>*</code> or <code>+</code> <a href="http://3.bp.blogspot.com/-Mp8uW2YRtsQ/TyVC1_JDanI/AAAAAAAAASI/hDfS9m7E3iY/s1600/vim_regs_p1.png" rel="noreferrer">registers</a>:</p> <p><kbd>g</kbd><kbd>g</kbd><kbd>"</kbd><kbd>*</kbd><kbd>y</kbd><kbd>G</kbd></p> <p>Explanation: </p> <ul> <li><code>gg</code> to get the cursor to the first character of the file</li> <li><code>"*y</code> to start a yank command to the register <code>*</code> from the first line, until...</li> <li><code>G</code> to go the end of the file</li> </ul>
{ "question_id": 1620018, "question_date": "2009-10-25T04:33:45.933Z", "question_score": 723, "tags": "vim|editor|keyboard-shortcuts|vi", "answer_id": 1620029, "answer_date": "2009-10-25T04:37:57.720Z", "answer_score": 772 }
Please answer the following Stack Overflow question: Title: How to get size of mysql database? <p>How to get size of a mysql database?<br> Suppose the target database is called "v3".</p>
<p>Run this query and you'll probably get what you're looking for:</p> <pre><code>SELECT table_schema "DB Name", ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables GROUP BY table_schema; </code></pre> <p>This query comes from <a href="http://forums.mysql.com/read.php?108,201578,201578" rel="noreferrer">the mysql forums</a>, where there are more comprehensive instructions available.</p>
{ "question_id": 1733507, "question_date": "2009-11-14T06:40:21.020Z", "question_score": 723, "tags": "mysql|database", "answer_id": 1733523, "answer_date": "2009-11-14T06:46:08.777Z", "answer_score": 1563 }
Please answer the following Stack Overflow question: Title: How to make a timezone aware datetime object <p><strong>What I need to do</strong></p> <p>I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.</p> <p><strong>What I've Tried</strong></p> <p>First, to demonstrate the problem:</p> <pre><code>Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import datetime &gt;&gt;&gt; import pytz &gt;&gt;&gt; unaware = datetime.datetime(2011,8,15,8,15,12,0) &gt;&gt;&gt; unaware datetime.datetime(2011, 8, 15, 8, 15, 12) &gt;&gt;&gt; aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC) &gt;&gt;&gt; aware datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; aware == unaware Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: can't compare offset-naive and offset-aware datetimes </code></pre> <p>First, I tried astimezone:</p> <pre><code>&gt;&gt;&gt; unaware.astimezone(pytz.UTC) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: astimezone() cannot be applied to a naive datetime &gt;&gt;&gt; </code></pre> <p>It's not terribly surprising this failed, since it's actually trying to do a conversion. Replace seemed like a better choice (as per <a href="https://stackoverflow.com/questions/4530069/python-how-to-get-a-value-of-datetime-today-that-is-timezone-aware">How do I get a value of datetime.today() in Python that is &quot;timezone aware&quot;?</a>):</p> <pre><code>&gt;&gt;&gt; unaware.replace(tzinfo=pytz.UTC) datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; unaware == aware Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: can't compare offset-naive and offset-aware datetimes &gt;&gt;&gt; </code></pre> <p>But as you can see, replace seems to set the tzinfo, but not make the object aware. I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.</p> <p>Also, I've tried this in both Python 2.6 and Python 2.7, with the same results.</p> <p><strong>Context</strong></p> <p>I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.</p>
<p>In general, to make a naive datetime timezone-aware, use the <a href="http://pytz.sourceforge.net/#localized-times-and-date-arithmetic" rel="noreferrer">localize method</a>:</p> <pre><code>import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware </code></pre> <p>For the UTC timezone, it is not really necessary to use <code>localize</code> since there is no daylight savings time calculation to handle:</p> <pre><code>now_aware = unaware.replace(tzinfo=pytz.UTC) </code></pre> <p>works. (<code>.replace</code> returns a new datetime; it does not modify <code>unaware</code>.)</p>
{ "question_id": 7065164, "question_date": "2011-08-15T12:55:44.583Z", "question_score": 723, "tags": "python|datetime|timezone|python-datetime|pytz", "answer_id": 7065242, "answer_date": "2011-08-15T13:03:52.747Z", "answer_score": 802 }
Please answer the following Stack Overflow question: Title: MetadataException: Unable to load the specified metadata resource <p>All of a sudden I keep getting a <code>MetadataException</code> on instantiating my generated <code>ObjectContext</code> class. The connection string in App.Config looks correct - hasn't changed since last it worked - and I've tried regenerating a new model (edmx-file) from the underlying database with no change.</p> <p>Anyone have any ideas?</p> <p>Further details: I haven't changed any properties, I haven't changed the name of any output assemblies, I haven't tried to embed the EDMX in the assembly. I've merely waited 10 hours from leaving work until I got back. And then it wasn't working anymore.</p> <p>I've tried recreating the EDMX. I've tried recreating the project. I've even tried recreating the database, from scratch. No luck, whatsoever.</p>
<p>This means that the application is unable to load the EDMX. There are several things which can cause this.</p> <ul> <li>You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory.</li> <li>The connection string could be wrong. I know you say you haven't changed it, but if you have changed other things (say, the name of an assembly), it could still be wrong.</li> <li>You might be using a post-compile task to embed the EDMX in the assembly, which is no longer working for some reason.</li> </ul> <p>In short, there is not really enough detail in your question to give an accurate answer, but hopefully these ideas should get you on the right track.</p> <p><strong>Update:</strong> I've written <a href="http://www.craigstuntz.com/posts/2010-08-13-troubleshooting-entity-framework-connection-strings.html" rel="noreferrer">a blog post with more complete steps for troubleshooting</a>.</p>
{ "question_id": 689355, "question_date": "2009-03-27T11:15:08.300Z", "question_score": 723, "tags": "c#|.net|entity-framework|ado.net", "answer_id": 689505, "answer_date": "2009-03-27T12:02:19.623Z", "answer_score": 878 }
Please answer the following Stack Overflow question: Title: How do you create a dropdownlist from an enum in ASP.NET MVC? <p>I'm trying to use the <code>Html.DropDownList</code> extension method but can't figure out how to use it with an enumeration.</p> <p>Let's say I have an enumeration like this:</p> <pre><code>public enum ItemTypes { Movie = 1, Game = 2, Book = 3 } </code></pre> <p>How do I go about creating a dropdown with these values using the <code>Html.DropDownList</code> extension method?</p> <p>Or is my best bet to simply create a for loop and create the Html elements manually?</p>
<h2>For MVC v5.1 use Html.EnumDropDownListFor</h2> <pre><code>@Html.EnumDropDownListFor( x =&gt; x.YourEnumField, "Select My Type", new { @class = "form-control" }) </code></pre> <hr> <h2>For MVC v5 use EnumHelper</h2> <pre><code>@Html.DropDownList("MyType", EnumHelper.GetSelectList(typeof(MyType)) , "Select My Type", new { @class = "form-control" }) </code></pre> <hr> <h2>For MVC 5 and lower</h2> <p>I rolled Rune's answer into an extension method:</p> <pre><code>namespace MyApp.Common { public static class MyExtensions{ public static SelectList ToSelectList&lt;TEnum&gt;(this TEnum enumObj) where TEnum : struct, IComparable, IFormattable, IConvertible { var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { Id = e, Name = e.ToString() }; return new SelectList(values, "Id", "Name", enumObj); } } } </code></pre> <p>This allows you to write:</p> <pre><code>ViewData["taskStatus"] = task.Status.ToSelectList(); </code></pre> <p>by <code>using MyApp.Common</code></p>
{ "question_id": 388483, "question_date": "2008-12-23T09:25:43.313Z", "question_score": 723, "tags": "c#|asp.net|asp.net-mvc", "answer_id": 694361, "answer_date": "2009-03-29T09:11:16.723Z", "answer_score": 893 }
Please answer the following Stack Overflow question: Title: How to identify if a webpage is being loaded inside an iframe or directly into the browser window? <p>I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?</p>
<p>Browsers can block access to <code>window.top</code> due to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript" rel="noreferrer">same origin policy</a>. IE bugs also take place. Here's the working code:</p> <pre><code>function inIframe () { try { return window.self !== window.top; } catch (e) { return true; } } </code></pre> <p><code>top</code> and <code>self</code> are both <code>window</code> objects (along with <code>parent</code>), so you're seeing if your window is the top window.</p>
{ "question_id": 326069, "question_date": "2008-11-28T15:45:25.497Z", "question_score": 723, "tags": "javascript|facebook|iframe", "answer_id": 326076, "answer_date": "2008-11-28T15:47:56.630Z", "answer_score": 1327 }
Please answer the following Stack Overflow question: Title: Array versus List<T>: When to use which? <pre><code>MyClass[] array; List&lt;MyClass&gt; list; </code></pre> <p>What are the scenarios when one is preferable over the other? And why?</p>
<p>It is rare, in reality, that you would want to use an array. Definitely use a <code>List&lt;T&gt;</code> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some <strong>very specific</strong> reason (after benchmarking), then an array may be useful.</p> <p><code>List&lt;T&gt;</code> offers a <em>lot</em> more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except for <code>params</code> arguments, of course. ;-p</p> <p>As a counter - <code>List&lt;T&gt;</code> is one-dimensional; where-as you have have rectangular (etc) arrays like <code>int[,]</code> or <code>string[,,]</code> - but there are other ways of modelling such data (if you need) in an object model.</p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/questions/75976/how-when-to-abandon-the-use-of-arrays-in-c-net">How/When to abandon the use of Arrays in c#.net?</a></li> <li><a href="https://stackoverflow.com/questions/392397/arrays-whats-the-point">Arrays, What's the point?</a></li> </ul> <p>That said, I make a <strong>lot</strong> of use of arrays in my <a href="https://github.com/mgravell/protobuf-net" rel="noreferrer">protobuf-net</a> project; entirely for performance:</p> <ul> <li>it does a lot of bit-shifting, so a <code>byte[]</code> is pretty much essential for encoding;</li> <li>I use a local rolling <code>byte[]</code> buffer which I fill before sending down to the underlying stream (and v.v.); quicker than <code>BufferedStream</code> etc;</li> <li>it internally uses an array-based model of objects (<code>Foo[]</code> rather than <code>List&lt;Foo&gt;</code>), since the size is fixed once built, and needs to be very fast.</li> </ul> <p>But this is definitely an exception; for general line-of-business processing, a <code>List&lt;T&gt;</code> wins every time.</p>
{ "question_id": 434761, "question_date": "2009-01-12T08:08:33.237Z", "question_score": 723, "tags": ".net|arrays|list", "answer_id": 434765, "answer_date": "2009-01-12T08:10:58.427Z", "answer_score": 706 }
Please answer the following Stack Overflow question: Title: nvm keeps "forgetting" node in new terminal session <h2>Upon using a new terminal session in OS X, <code>nvm</code> forgets the node version and defaults to nothing:</h2> <p><code>$ nvm ls</code>:</p> <pre><code> .nvm v0.11.12 v0.11.13 </code></pre> <p>I have to keep hitting <code>nvm use v.0.11.13</code> in every session:</p> <pre><code> .nvm v0.11.12 -&gt; v0.11.13 </code></pre> <p>I've tried both the <code>brew</code> install, as well as the official installation script.</p> <p>My <strong><code>.profile</code></strong> for the brew version:</p> <pre><code>#nvm export NVM_DIR=~/.nvm source $(brew --prefix nvm)/nvm.sh </code></pre> <p>And for the install.sh script:</p> <p><code>$ curl https://raw.githubusercontent.com/creationix/nvm/v0.10.0/install.sh | bash</code></p> <pre><code>#nvm export NVM_DIR="/Users/farhad/.nvm" [ -s "$NVM_DIR/nvm.sh" ] &amp;&amp; . "$NVM_DIR/nvm.sh" # This loads nvm </code></pre> <h2>Any clue to what I'm doing wrong?</h2>
<p>Try <code>nvm alias default</code>. For example:</p> <p><code>$ nvm alias default 0.12.7</code></p> <p>This sets the default node version in your shell. Then verify that the change persists by closing the shell window, opening a new one, then: <code>node --version</code> </p>
{ "question_id": 24585261, "question_date": "2014-07-05T10:05:25.937Z", "question_score": 723, "tags": "node.js|macos|npm|homebrew|nvm", "answer_id": 24587177, "answer_date": "2014-07-05T14:00:19.807Z", "answer_score": 1440 }
Please answer the following Stack Overflow question: Title: How does Zalgo text work? <p>I've seen weirdly formatted text called Zalgo like below written on various forums. It's kind of annoying to look at, but it really bothers me because it undermines my notion of what a character is supposed to be. My understanding is that a character is supposed to move horizontally across a line and stay within a certain "container". Obviously the Zalgo text is moving vertically and doesn't seem to be restricted to any space. </p> <p>Is this a bug/flaw/exploit/hack in Unicode? Are these individual characters with weird properties? "What" is happening here?</p> <blockquote> <p><br></p> <p>H̡̫̤̤̣͉̤ͭ̓̓̇͗̎̀ơ̯̗̱̘̮͒̄̀̈ͤ̀͡w͓̲͙͖̥͉̹͋ͬ̊ͦ̂̀̚ ͎͉͖̌ͯͅͅd̳̘̿̃̔̏ͣ͂̉̕ŏ̖̙͋ͤ̊͗̓͟͜e͈͕̯̮̙̣͓͌ͭ̍̐̃͒s͙͔̺͇̗̱̿̊̇͞ ̸̤͓̞̱̫ͩͩ͑̋̀ͮͥͦ̊Z̆̊͊҉҉̠̱̦̩͕ą̟̹͈̺̹̋̅ͯĺ̡̘̹̻̩̩͋͘g̪͚͗ͬ͒o̢̖͇̬͍͇͓̔͋͊̓ ̢͈͙͂ͣ̏̿͐͂ͯ͠t̛͓̖̻̲ͤ̈ͣ͝e͋̄ͬ̽͜҉͚̭͇ͅx͎̬̠͇̌ͤ̓̂̓͐͐́͋͡ț̗̹̝̄̌̀ͧͩ̕͢ ̮̗̩̳̱̾w͎̭̤͍͇̰̄͗ͭ̃͗ͮ̐o̢̯̻̰̼͕̾ͣͬ̽̔̍͟ͅr̢̪͙͍̠̀ͅǩ̵̶̗̮̮ͪ́?̙͉̥̬͙̟̮͕ͤ̌͗ͩ̕͡ <br> <br> <br></p> </blockquote>
<p>The text uses combining characters, also known as combining marks. See section 2.11 of <a href="http://www.unicode.org/versions/Unicode6.2.0/ch02.pdf#page=36" rel="noreferrer"><em>Combining Characters in the Unicode Standard</em></a> (PDF).</p> <p>In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character</p> <p>So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).</p> <p>And you can mix “combining above” and “combining below” marks.</p> <p>The sample text in the question starts with:</p> <ul> <li><a href="http://www.fileformat.info/info/unicode/char/0048/index.htm" rel="noreferrer">LATIN CAPITAL LETTER H</a> - <code>&amp;#x48;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/036d/index.htm" rel="noreferrer">COMBINING LATIN SMALL LETTER T</a> - <code>&amp;#x36d;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0343/index.htm" rel="noreferrer">COMBINING GREEK KORONIS</a> - <code>&amp;#x343;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0313/index.htm" rel="noreferrer">COMBINING COMMA ABOVE</a> - <code>&amp;#x313;</code></li> <li><a href="http://www.fileformat.info/info/unicode/char/0307/index.htm" rel="noreferrer">COMBINING DOT ABOVE</a> - <code>&amp;#x307;</code></li> </ul>
{ "question_id": 6579844, "question_date": "2011-07-05T08:30:37.943Z", "question_score": 723, "tags": "html|unicode|zalgo", "answer_id": 20310289, "answer_date": "2013-12-01T08:34:31.997Z", "answer_score": 450 }
Please answer the following Stack Overflow question: Title: How do I append one string to another in Python? <p>How do I efficiently append one string to another? Are there any faster alternatives to:</p> <pre><code>var1 = &quot;foo&quot; var2 = &quot;bar&quot; var3 = var1 + var2 </code></pre> <hr /> <p><sub>For handling multiple strings in a list, see <a href="https://stackoverflow.com/questions/12453580/">How to concatenate (join) items in a list to a single string</a>.</sub></p>
<p>If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.</p> <p>The end result is that the operation is amortized O(n).</p> <p>e.g.</p> <pre><code>s = "" for i in range(n): s+=str(i) </code></pre> <p>used to be O(n^2), but now it is O(n).</p> <p>From the source (bytesobject.c):</p> <pre class="lang-c prettyprint-override"><code>void PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w) { PyBytes_Concat(pv, w); Py_XDECREF(w); } /* The following function breaks the notion that strings are immutable: it changes the size of a string. We get away with this only if there is only one module referencing the object. You can also think of it as creating a new string object and destroying the old one, only more efficiently. In any case, don't use this if the string may already be known to some other part of the code... Note that if there's not enough memory to resize the string, the original string object at *pv is deallocated, *pv is set to NULL, an "out of memory" exception is set, and -1 is returned. Else (on success) 0 is returned, and the value in *pv may or may not be the same as on input. As always, an extra byte is allocated for a trailing \0 byte (newsize does *not* include that), and a trailing \0 byte is stored. */ int _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) { register PyObject *v; register PyBytesObject *sv; v = *pv; if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize &lt; 0) { *pv = 0; Py_DECREF(v); PyErr_BadInternalCall(); return -1; } /* XXX UNREF/NEWREF interface should be more symmetrical */ _Py_DEC_REFTOTAL; _Py_ForgetReference(v); *pv = (PyObject *) PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize); if (*pv == NULL) { PyObject_Del(v); PyErr_NoMemory(); return -1; } _Py_NewReference(*pv); sv = (PyBytesObject *) *pv; Py_SIZE(sv) = newsize; sv-&gt;ob_sval[newsize] = '\0'; sv-&gt;ob_shash = -1; /* invalidate cached hash value */ return 0; } </code></pre> <p>It's easy enough to verify empirically.</p> <pre> $ python -m timeit -s"s=''" "for i in xrange(10):s+='a'" 1000000 loops, best of 3: 1.85 usec per loop $ python -m timeit -s"s=''" "for i in xrange(100):s+='a'" 10000 loops, best of 3: 16.8 usec per loop $ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 10000 loops, best of 3: 158 usec per loop $ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 1000 loops, best of 3: 1.71 msec per loop $ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 14.6 msec per loop $ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'" 10 loops, best of 3: 173 msec per loop </pre> <p><strong>It's important</strong> however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .</p> <pre> $ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'" 10000 loops, best of 3: 90.8 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'" 1000 loops, best of 3: 896 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 100 loops, best of 3: 9.03 msec per loop $ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 10 loops, best of 3: 89.5 msec per loop </pre> <p>So far so good, but then,</p> <pre> $ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 12.8 sec per loop </pre> <p>ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.</p>
{ "question_id": 4435169, "question_date": "2010-12-14T01:41:29.340Z", "question_score": 722, "tags": "python|string|append", "answer_id": 4435752, "answer_date": "2010-12-14T04:01:52.497Z", "answer_score": 747 }
Please answer the following Stack Overflow question: Title: Updating a local repository with changes from a GitHub repository <p>I've got a project checked locally from GitHub, and that remote repository has since had changes made to it. What's the correct command to update my local copy with the latest changes?</p>
<p>Probably:</p> <p>was: git pull origin master</p> <p>now: git pull origin main</p>
{ "question_id": 1443210, "question_date": "2009-09-18T08:26:52.917Z", "question_score": 722, "tags": "git|github", "answer_id": 1443232, "answer_date": "2009-09-18T08:31:54.980Z", "answer_score": 1010 }
Please answer the following Stack Overflow question: Title: Count the number of occurrences of a character in a string in Javascript <p>I need to count the number of occurrences of a character in a string.</p> <p>For example, suppose my string contains:</p> <pre><code>var mainStr = "str1,str2,str3,str4"; </code></pre> <p>I want to find the count of comma <code>,</code> character, which is 3. And the count of individual strings after the split along comma, which is 4.</p> <p>I also need to validate that each of the strings i.e str1 or str2 or str3 or str4 should not exceed, say, 15 characters.</p>
<p>I have updated this answer. I like the idea of using a match better, but it is slower:</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>console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3 console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4</code></pre> </div> </div> </p> <p>Use a regular expression literal if you know what you are searching for beforehand, if not you can use the <code>RegExp</code> constructor, and pass in the <code>g</code> flag as an argument.</p> <p><code>match</code> returns <code>null</code> with no results thus the <code>|| []</code></p> <p>The original answer I made in 2009 is below. It creates an array unnecessarily, but <strong>using a split is faster</strong> (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.</p> <p>Old answer (from 2009):</p> <p>If you're looking for the commas:</p> <pre><code>(mainStr.split(&quot;,&quot;).length - 1) //3 </code></pre> <p>If you're looking for the str</p> <pre><code>(mainStr.split(&quot;str&quot;).length - 1) //4 </code></pre> <p>Both in @Lo's answer and in my own silly <a href="https://parsebox.io/dthree/fgrsjqmknxzs" rel="noreferrer">performance test</a> split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.</p>
{ "question_id": 881085, "question_date": "2009-05-19T05:24:24.643Z", "question_score": 722, "tags": "javascript|string", "answer_id": 881111, "answer_date": "2009-05-19T05:33:20.237Z", "answer_score": 1001 }
Please answer the following Stack Overflow question: Title: Get class list for element with jQuery <p>Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?</p> <p>ex.</p> <pre><code>&lt;div class="Lorem ipsum dolor_spec sit amet"&gt;Hello World!&lt;/div&gt; </code></pre> <p>I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.</p>
<p>You can use <code>document.getElementById('divId').className.split(/\s+/);</code> to get you an array of class names.</p> <p>Then you can iterate and find the one you want.</p> <pre><code>var classList = document.getElementById('divId').className.split(/\s+/); for (var i = 0; i &lt; classList.length; i++) { if (classList[i] === 'someClass') { //do something } } </code></pre> <p>jQuery does not really help you here...</p> <pre><code>var classList = $('#divId').attr('class').split(/\s+/); $.each(classList, function(index, item) { if (item === 'someClass') { //do something } }); </code></pre>
{ "question_id": 1227286, "question_date": "2009-08-04T12:41:04.663Z", "question_score": 722, "tags": "javascript|jquery|html", "answer_id": 1227309, "answer_date": "2009-08-04T12:44:02.103Z", "answer_score": 776 }
Please answer the following Stack Overflow question: Title: Wildcards in jQuery selectors <p>I'm trying to use a wildcard to get the id of all the elements whose id begin with "jander". I tried <code>$('#jander*')</code>, <code>$('#jander%')</code> but it doesn't work..</p> <p>I know I can use classes of the elements to solve it, but it is also possible using wildcards??</p> <pre><code>&lt;script type="text/javascript"&gt; var prueba = []; $('#jander').each(function () { prueba.push($(this).attr('id')); }); alert(prueba); }); &lt;/script&gt; &lt;div id="jander1"&gt;&lt;/div&gt; &lt;div id="jander2"&gt;&lt;/div&gt; </code></pre>
<p>To get all the elements starting with "jander" you should use:</p> <pre><code>$("[id^=jander]") </code></pre> <p>To get those that end with "jander"</p> <pre><code>$("[id$=jander]") </code></pre> <p>See also the <a href="http://api.jquery.com/category/selectors/" rel="noreferrer">JQuery documentation</a></p>
{ "question_id": 5376431, "question_date": "2011-03-21T10:34:08.003Z", "question_score": 722, "tags": "jquery|jquery-selectors|sizzle", "answer_id": 5376445, "answer_date": "2011-03-21T10:35:16.850Z", "answer_score": 1374 }
Please answer the following Stack Overflow question: Title: How can I avoid concurrency problems when using SQLite on Android? <p>What would be considered the best practices when executing queries on an SQLite database within an Android app?</p> <p>Is it safe to run inserts, deletes and select queries from an AsyncTask's doInBackground? Or should I use the UI Thread? I suppose that database queries can be "heavy" and should not use the UI thread as it can lock up the app - resulting in an <a href="https://developer.android.com/intl/in/training/articles/perf-anr.html" rel="noreferrer">Application Not Responding</a> (ANR).</p> <p>If I have several AsyncTasks, should they share a connection or should they open a connection each?</p> <p>Are there any best practices for these scenarios?</p>
<p>Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's <a href="https://stackoverflow.com/a/2493839/2759862">answer</a> is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.</p> <p><strong>The basic answer.</strong></p> <p>The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.</p> <p>So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.</p> <p>So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).</p> <p>If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.</p> <p>So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.</p> <p>Here's a blog post with far more detail and an example app.</p> <ul> <li><a href="http://touchlabblog.tumblr.com/post/24474398246/android-sqlite-locking" rel="noreferrer">Android Sqlite Locking</a> (Updated link 6/18/2012)</li> <li><a href="https://github.com/touchlab/Android-Database-Locking-Collisions-Example" rel="noreferrer">Android-Database-Locking-Collisions-Example by touchlab</a> on GitHub</li> </ul> <p>Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.</p> <hr> <p>In the meantime, there is a follow up blog post:</p> <ul> <li><a href="http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection" rel="noreferrer">Single SQLite connection</a></li> </ul> <p>Also checkout the fork by <em>2point0</em> of the previously mentioned locking example:</p> <ul> <li><a href="https://github.com/2point0/Android-Database-Locking-Collisions-Example" rel="noreferrer">Android-Database-Locking-Collisions-Example by 2point0</a> on GitHub</li> </ul>
{ "question_id": 2493331, "question_date": "2010-03-22T15:13:32.573Z", "question_score": 722, "tags": "android|database|sqlite", "answer_id": 3689883, "answer_date": "2010-09-11T05:11:57.620Z", "answer_score": 644 }
Please answer the following Stack Overflow question: Title: Git remote branch deleted, but still it appears in 'branch -a' <p>Let's say I had a branch named <code>coolbranch</code> in my repository.</p> <p>Now, I decided to delete it (both remotely and locally) with:</p> <pre><code>git push origin :coolbranch git branch -D coolbranch </code></pre> <p>Great! Now the branch is really deleted.</p> <p>But when I run</p> <pre><code>git branch -a </code></pre> <p>I still get:</p> <pre><code>remotes/origin/coolbranch </code></pre> <p>Something to notice, is that when I clone a new repository, everything is fine and <code>git branch -a</code> doesn't show the branch.</p> <p>I want to know - is there a way to delete the branch from the <code>branch -a</code> list without cloning a new instance?</p>
<p><code>git remote prune origin</code>, as suggested in the other answer, will remove all such stale branches. That's probably what you'd want in most cases, but if you want to just remove that particular remote-tracking branch, you should do:</p> <pre><code>git branch -d -r origin/coolbranch </code></pre> <p>(The <code>-r</code> is easy to forget...)</p> <p><code>-r</code> in this case will "List or delete (if used with <code>-d</code>) the remote-tracking branches." according to the Git documentation found here: <a href="https://git-scm.com/docs/git-branch" rel="noreferrer">https://git-scm.com/docs/git-branch</a></p>
{ "question_id": 5094293, "question_date": "2011-02-23T17:10:57.700Z", "question_score": 722, "tags": "git|git-branch", "answer_id": 5096739, "answer_date": "2011-02-23T20:32:35.833Z", "answer_score": 869 }
Please answer the following Stack Overflow question: Title: How to check if function exists in JavaScript? <p>My code is</p> <pre><code>function getID( swfID ){ if(navigator.appName.indexOf("Microsoft") != -1){ me = window[swfID]; }else{ me = document[swfID]; } } function js_to_as( str ){ me.onChange(str); } </code></pre> <p>However, sometimes my <code>onChange</code> does not load. Firebug errors with</p> <blockquote> <p>me.onChange is not a function</p> </blockquote> <p>I want to degrade gracefully because this is not the most important feature in my program. <code>typeof</code> gives the same error.</p> <p>Any suggestions on how to make sure that it exists and then only execute <code>onChange</code>?</p> <p>(None of the methods below except try catch one work)</p>
<p>Try something like this:</p> <pre><code>if (typeof me.onChange !== "undefined") { // safe to use the function } </code></pre> <p>or better yet (as per UpTheCreek upvoted comment)</p> <pre><code>if (typeof me.onChange === "function") { // safe to use the function } </code></pre>
{ "question_id": 1042138, "question_date": "2009-06-25T04:10:54.463Z", "question_score": 721, "tags": "javascript", "answer_id": 1042154, "answer_date": "2009-06-25T04:14:24.743Z", "answer_score": 1513 }
Please answer the following Stack Overflow question: Title: Check if pull needed in Git <p>How do I check whether the remote repository has changed and I need to pull?</p> <p>Now I use this simple script:</p> <pre><code>git pull --dry-run | grep -q -v 'Already up-to-date.' &amp;&amp; changed=1 </code></pre> <p>But it is rather heavy.</p> <p>Is there a better way? The ideal solution would check all the remote branches, and return names of the changed branches and the number of new commits in each one.</p>
<p>First use <a href="https://git-scm.com/docs/git-remote" rel="noreferrer"><code>git remote update</code></a>, to bring your remote refs up to date. Then you can do one of several things, such as:</p> <ol> <li><p><code>git status -uno</code> will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.</p> </li> <li><p><code>git show-branch *master</code> will show you the commits in all of the branches whose names end in 'master' (eg <em>master</em> and <em>origin/master</em>).</p> </li> </ol> <p>If you use <code>-v</code> with <code>git remote update</code> (<code>git remote -v update</code>) you can see which branches got updated, so you don't really need any further commands.</p> <p>However, it looks like you want to do this in a script or program and end up with a true/false value. If so, there are ways to check the relationship between your current <em>HEAD</em> commit and the head of the branch you're tracking, although since there are four possible outcomes you can't reduce it to a yes/no answer. However, if you're prepared to do a <code>pull --rebase</code> then you can treat &quot;local is behind&quot; and &quot;local has diverged&quot; as &quot;need to pull&quot;, and the other two (&quot;local is ahead&quot; and &quot;same&quot;) as &quot;don't need to pull&quot;.</p> <p>You can get the commit id of any ref using <code>git rev-parse &lt;ref&gt;</code>, so you can do this for <em>master</em> and <em>origin/master</em> and compare them. If they're equal, the branches are the same. If they're unequal, you want to know which is ahead of the other. Using <code>git merge-base master origin/master</code> will tell you the common ancestor of both branches, and if they haven't diverged this will be the same as one or the other. If you get three different ids, the branches have diverged.</p> <p>To do this properly, eg in a script, you need to be able to refer to the current branch, and the remote branch it's tracking. The bash prompt-setting function in <code>/etc/bash_completion.d</code> has some useful code for getting branch names. However, you probably don't actually need to get the names. Git has some neat shorthands for referring to branches and commits (as documented in <code>git rev-parse --help</code>). In particular, you can use <code>@</code> for the current branch (assuming you're not in a detached-head state) and <code>@{u}</code> for its upstream branch (eg <code>origin/master</code>). So <code>git merge-base @ @{u}</code> will return the (hash of the) commit at which the current branch and its upstream diverge and <code>git rev-parse @</code> and <code>git rev-parse @{u}</code> will give you the hashes of the two tips. This can be summarized in the following script:</p> <pre><code>#!/bin/sh UPSTREAM=${1:-'@{u}'} LOCAL=$(git rev-parse @) REMOTE=$(git rev-parse &quot;$UPSTREAM&quot;) BASE=$(git merge-base @ &quot;$UPSTREAM&quot;) if [ $LOCAL = $REMOTE ]; then echo &quot;Up-to-date&quot; elif [ $LOCAL = $BASE ]; then echo &quot;Need to pull&quot; elif [ $REMOTE = $BASE ]; then echo &quot;Need to push&quot; else echo &quot;Diverged&quot; fi </code></pre> <p><em>Note:</em> older versions of git didn't allow <code>@</code> on its own, so you may have to use <code>@{0}</code> instead.</p> <p>The line <code>UPSTREAM=${1:-'@{u}'}</code> allows you optionally to pass an upstream branch explicitly, in case you want to check against a different remote branch than the one configured for the current branch. This would typically be of the form <em>remotename/branchname</em>. If no parameter is given, the value defaults to <code>@{u}</code>.</p> <p>The script assumes that you've done a <code>git fetch</code> or <code>git remote update</code> first, to bring the tracking branches up to date. I didn't build this into the script because it's more flexible to be able to do the fetching and the comparing as separate operations, for example if you want to compare without fetching because you already fetched recently.</p>
{ "question_id": 3258243, "question_date": "2010-07-15T17:32:27.573Z", "question_score": 721, "tags": "git|bash|shell", "answer_id": 3278427, "answer_date": "2010-07-19T04:18:54.587Z", "answer_score": 986 }
Please answer the following Stack Overflow question: Title: How do I do redo (i.e. "undo undo") in Vim? <p>In Vim, I did too much undo. How do I undo this (that is, redo)?</p>
<p><kbd>Ctrl</kbd>+<kbd>r</kbd></p>
{ "question_id": 1555779, "question_date": "2009-10-12T17:10:52.567Z", "question_score": 721, "tags": "vim|undo|redo", "answer_id": 1555788, "answer_date": "2009-10-12T17:12:27.867Z", "answer_score": 933 }
Please answer the following Stack Overflow question: Title: if else statement in AngularJS templates <p>I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.</p> <p>I want to make a condition like this:</p> <pre><code>if video.yt$aspectRatio equals widescreen then element's attr height="270px" else element's attr height="360px" </code></pre> <p>I'm iterating the videos using <code>ng-repeat</code>. Have no idea what should I do for this condition:</p> <ul> <li>Add a function in the scope? </li> <li>Do it in template?</li> </ul>
<p>Angularjs (versions below 1.1.5) does not provide the <code>if/else</code> functionality . Following are a few options to consider for what you want to achieve:</p> <p>(<strong><em>Jump to the update below (#5) if you are using version 1.1.5 or greater</em></strong>)</p> <h3>1. Ternary operator:</h3> <p>As suggested by @Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:</p> <pre><code>&lt;span&gt;{{isLarge ? 'video.large' : 'video.small'}}&lt;/span&gt; </code></pre> <h3>2. <a href="https://docs.angularjs.org/api/ng/directive/ngSwitch" rel="noreferrer"><code>ng-switch</code></a> directive:</h3> <p>can be used something like the following.</p> <pre><code>&lt;div ng-switch on="video"&gt; &lt;div ng-switch-when="video.large"&gt; &lt;!-- code to render a large video block--&gt; &lt;/div&gt; &lt;div ng-switch-default&gt; &lt;!-- code to render the regular video block --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h3>3. <a href="https://docs.angularjs.org/api/ng/directive/ngHide" rel="noreferrer"><code>ng-hide</code></a> / <a href="https://docs.angularjs.org/api/ng/directive/ngShow" rel="noreferrer"><code>ng-show</code></a> directives</h3> <p>Alternatively, you might also use <code>ng-show/ng-hide</code> but using this will actually render both a large video and a small video element and then hide the one that meets the <code>ng-hide</code> condition and shows the one that meets <code>ng-show</code> condition. So on each page you'll actually be rendering two different elements.</p> <h3>4. Another option to consider is <a href="https://docs.angularjs.org/api/ng/directive/ngClass" rel="noreferrer"><code>ng-class</code></a> directive.</h3> <p>This can be used as follows.</p> <pre><code>&lt;div ng-class="{large-video: video.large}"&gt; &lt;!-- video block goes here --&gt; &lt;/div&gt; </code></pre> <p>The above basically will add a <code>large-video</code> css class to the div element if <code>video.large</code> is truthy.</p> <h3>UPDATE: <a href="http://code.angularjs.org/1.1.5/docs/" rel="noreferrer">Angular 1.1.5</a> introduced the <a href="https://docs.angularjs.org/api/ng/directive/ngIf" rel="noreferrer"><code>ngIf directive</code></a></h3> <h3>5. <a href="https://docs.angularjs.org/api/ng/directive/ngIf" rel="noreferrer"><code>ng-if</code></a> directive:</h3> <p>In the versions above <code>1.1.5</code> you can use the <code>ng-if</code> directive. This would remove the element if the expression provided returns <code>false</code> and re-inserts the <code>element</code> in the DOM if the expression returns <code>true</code>. Can be used as follows.</p> <pre><code>&lt;div ng-if="video == video.large"&gt; &lt;!-- code to render a large video block--&gt; &lt;/div&gt; &lt;div ng-if="video != video.large"&gt; &lt;!-- code to render the regular video block --&gt; &lt;/div&gt; </code></pre>
{ "question_id": 15810278, "question_date": "2013-04-04T11:50:13.800Z", "question_score": 720, "tags": "if-statement|angularjs", "answer_id": 15810462, "answer_date": "2013-04-04T11:58:29.237Z", "answer_score": 1321 }
Please answer the following Stack Overflow question: Title: How to delete the contents of a folder? <p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows, but I would like to see *nix also.</p>
<pre><code>import os, shutil folder = '/path/to/folder' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) </code></pre>
{ "question_id": 185936, "question_date": "2008-10-09T04:22:33.817Z", "question_score": 720, "tags": "python|file", "answer_id": 185941, "answer_date": "2008-10-09T04:27:21.357Z", "answer_score": 628 }
Please answer the following Stack Overflow question: Title: What is the equivalent of ngShow and ngHide in Angular 2+? <p>I have a number of elements that I want to be visible under certain conditions.</p> <p>In AngularJS I would write</p> <pre class="lang-html prettyprint-override"><code>&lt;div ng-show=&quot;myVar&quot;&gt;stuff&lt;/div&gt; </code></pre> <p>How can I do this in Angular 2+?</p>
<p>The <code>hidden</code> property can be used for that</p> <pre class="lang-dart prettyprint-override"><code>[hidden]=&quot;!myVar&quot; </code></pre> <p>See also</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden</a></li> </ul> <p><strong>issues</strong></p> <p><code>hidden</code> has some issues though because it can conflict with CSS for the <code>display</code> property.</p> <p>See how <code>some</code> in <a href="https://plnkr.co/edit/SO3c3UUT3LBvhNAeriCz?p=preview" rel="noreferrer"><strong>Plunker example</strong></a> doesn't get hidden because it has a style</p> <pre class="lang-dart prettyprint-override"><code>:host {display: block;} </code></pre> <p>set. (This might behave differently in other browsers - I tested with Chrome 50)</p> <p><strong>workaround</strong></p> <p>You can fix it by adding</p> <pre class="lang-dart prettyprint-override"><code>[hidden] { display: none !important;} </code></pre> <p>To a global style in <code>index.html</code>.</p> <p><strong>another pitfall</strong></p> <pre class="lang-dart prettyprint-override"><code>hidden=&quot;false&quot; hidden=&quot;{{false}}&quot; hidden=&quot;{{isHidden}}&quot; // isHidden = false; </code></pre> <p>are the same as</p> <pre class="lang-dart prettyprint-override"><code>hidden=&quot;true&quot; </code></pre> <p>and will not show the element.</p> <p><code>hidden=&quot;false&quot;</code> will assign the string <code>&quot;false&quot;</code> which is considered truthy.<br /> Only the value <code>false</code> or removing the attribute will actually make the element visible.</p> <p>Using <code>{{}}</code> also converts the expression to a string and won't work as expected.</p> <p>Only binding with <code>[]</code> will work as expected because this <code>false</code> is assigned as <code>false</code> instead of <code>&quot;false&quot;</code>.</p> <p><strong><code>*ngIf</code> vs <code>[hidden]</code></strong></p> <p><code>*ngIf</code> effectively removes its content from the DOM while <code>[hidden]</code> modifies the <code>display</code> property and only instructs the browser to not show the content but the DOM still contains it.</p>
{ "question_id": 35578083, "question_date": "2016-02-23T12:50:27.560Z", "question_score": 720, "tags": "angular|angular-components|angular-template", "answer_id": 35578093, "answer_date": "2016-02-23T12:51:10.230Z", "answer_score": 1170 }
Please answer the following Stack Overflow question: Title: How do I get my program to sleep for 50 milliseconds? <p>How do I get my Python program to sleep for 50 milliseconds?</p>
<p>Use <a href="https://docs.python.org/library/time.html#time.sleep" rel="noreferrer"><code>time.sleep()</code></a></p> <pre><code>from time import sleep sleep(0.05) </code></pre>
{ "question_id": 377454, "question_date": "2008-12-18T10:20:24.270Z", "question_score": 720, "tags": "python|timer|sleep", "answer_id": 377463, "answer_date": "2008-12-18T10:23:50.113Z", "answer_score": 1093 }
Please answer the following Stack Overflow question: Title: How can I clear or empty a StringBuilder? <p>I'm using a <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html" rel="noreferrer">StringBuilder</a> in a loop and every x iterations I want to empty it and start with an empty <code>StringBuilder</code>, but I can't see any method similar to the .NET <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.clear.aspx" rel="noreferrer">StringBuilder.Clear</a> in the documentation, just the <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#delete%28int,%20int%29" rel="noreferrer">delete</a> method which seems overly complicated.</p> <p>So what is the best way to clean out a <code>StringBuilder</code> in Java?</p>
<p>Two ways that work:</p> <ol> <li>Use <code>stringBuilderObj.setLength(0)</code>.</li> <li>Allocate a new one with <code>new StringBuilder()</code> instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than the <code>setLength</code>-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).</li> </ol>
{ "question_id": 5192512, "question_date": "2011-03-04T10:26:19.063Z", "question_score": 720, "tags": "java|stringbuilder", "answer_id": 5192545, "answer_date": "2011-03-04T10:29:04.863Z", "answer_score": 917 }
Please answer the following Stack Overflow question: Title: Why is my Spring @Autowired field null? <p><em>Note: This is intended to be a canonical answer for a common problem.</em></p> <p>I have a Spring <code>@Service</code> class (<code>MileageFeeCalculator</code>) that has an <code>@Autowired</code> field (<code>rateService</code>), but the field is <code>null</code> when I try to use it. The logs show that both the <code>MileageFeeCalculator</code> bean and the <code>MileageRateService</code> bean are being created, but I get a <code>NullPointerException</code> whenever I try to call the <code>mileageCharge</code> method on my service bean. Why isn't Spring autowiring the field?</p> <p>Controller class:</p> <pre><code>@Controller public class MileageFeeController { @RequestMapping("/mileage/{miles}") @ResponseBody public float mileageFee(@PathVariable int miles) { MileageFeeCalculator calc = new MileageFeeCalculator(); return calc.mileageCharge(miles); } } </code></pre> <p>Service class:</p> <pre><code>@Service public class MileageFeeCalculator { @Autowired private MileageRateService rateService; // &lt;--- should be autowired, is null public float mileageCharge(final int miles) { return (miles * rateService.ratePerMile()); // &lt;--- throws NPE } } </code></pre> <p>Service bean that should be autowired in <code>MileageFeeCalculator</code> but it isn't:</p> <pre><code>@Service public class MileageRateService { public float ratePerMile() { return 0.565f; } } </code></pre> <p>When I try to <code>GET /mileage/3</code>, I get this exception:</p> <pre><code>java.lang.NullPointerException: null at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13) at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14) ... </code></pre>
<p>The field annotated <code>@Autowired</code> is <code>null</code> because Spring doesn't know about the copy of <code>MileageFeeCalculator</code> that you created with <code>new</code> and didn't know to autowire it.</p> <p><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html">The Spring Inversion of Control (IoC) container</a> has three main logical components: a registry (called the <code>ApplicationContext</code>) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.</p> <p>The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call <code>new</code>, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.</p> <p>I have posted all of this code, using Spring Boot to launch, at <a href="https://github.com/chrylis/spring_autowired_npe_example">this GitHub project</a>; you can look at a full running project for each approach to see everything you need to make it work. <strong>Tag with the <code>NullPointerException</code>: <a href="https://github.com/chrylis/spring_autowired_npe_example/tree/nonworking"><code>nonworking</code></a></strong></p> <h2>Inject your beans</h2> <p>The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the <code>MileageFeeCalculator</code> like this:</p> <pre><code>@Controller public class MileageFeeController { @Autowired private MileageFeeCalculator calc; @RequestMapping("/mileage/{miles}") @ResponseBody public float mileageFee(@PathVariable int miles) { return calc.mileageCharge(miles); } } </code></pre> <p>If you need to create a new instance of your service object for different requests, you can still use injection by using <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes">the Spring bean scopes</a>.</p> <p><strong>Tag that works by injecting the <code>@MileageFeeCalculator</code> service object: <a href="https://github.com/chrylis/spring_autowired_npe_example/tree/working-inject-bean"><code>working-inject-bean</code></a></strong></p> <h2>Use @Configurable</h2> <p>If you really need objects created with <code>new</code> to be autowired, you can <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-atconfigurable">use the Spring <code>@Configurable</code> annotation along with AspectJ compile-time weaving</a> to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with <code>ajc</code>) and turning on Spring's runtime configuration handlers (<code>@EnableSpringConfigured</code> with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow <code>new</code> instances of your entities to get the necessary persistence information injected.</p> <pre><code>@Service @Configurable public class MileageFeeCalculator { @Autowired private MileageRateService rateService; public float mileageCharge(final int miles) { return (miles * rateService.ratePerMile()); } } </code></pre> <p><strong>Tag that works by using <code>@Configurable</code> on the service object: <a href="https://github.com/chrylis/spring_autowired_npe_example/tree/working-configurable"><code>working-configurable</code></a></strong></p> <h2>Manual bean lookup: not recommended</h2> <p>This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.</p> <p>To do this, you need a class to which Spring can give a reference to the <code>ApplicationContext</code> object:</p> <pre><code>@Component public class ApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getContext() { return context; } } </code></pre> <p>Then your legacy code can call <code>getContext()</code> and retrieve the beans it needs:</p> <pre><code>@Controller public class MileageFeeController { @RequestMapping("/mileage/{miles}") @ResponseBody public float mileageFee(@PathVariable int miles) { MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class); return calc.mileageCharge(miles); } } </code></pre> <p><strong>Tag that works by manually looking up the service object in the Spring context: <a href="https://github.com/chrylis/spring_autowired_npe_example/tree/working-manual-lookup"><code>working-manual-lookup</code></a></strong></p>
{ "question_id": 19896870, "question_date": "2013-11-11T00:05:03.803Z", "question_score": 720, "tags": "java|spring|null|nullpointerexception|autowired", "answer_id": 19896871, "answer_date": "2013-11-11T00:05:03.803Z", "answer_score": 747 }
Please answer the following Stack Overflow question: Title: Is there a foreach loop in Go? <p>Is there a <code>foreach</code> construct in the Go language? Can I iterate over a slice or array using a <code>for</code>?</p>
<p>From <em><a href="https://golang.org/ref/spec#For_range" rel="noreferrer">For statements with range clause</a></em>:</p> <blockquote> <p>A &quot;for&quot; statement with a &quot;range&quot; clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.</p> </blockquote> <p>As an example:</p> <pre class="lang-golang prettyprint-override"><code>for index, element := range someSlice { // index is the index where we are // element is the element from someSlice for where we are } </code></pre> <p>If you don't care about the index, you can use <code>_</code>:</p> <pre class="lang-golang prettyprint-override"><code>for _, element := range someSlice { // element is the element from someSlice for where we are } </code></pre> <p>The underscore, <code>_</code>, is the <a href="https://golang.org/ref/spec#Blank_identifier" rel="noreferrer"><em>blank identifier</em></a>, an anonymous placeholder.</p>
{ "question_id": 7782411, "question_date": "2011-10-16T04:47:32.690Z", "question_score": 720, "tags": "go|foreach|slice", "answer_id": 7782507, "answer_date": "2011-10-16T05:13:45.920Z", "answer_score": 1052 }
Please answer the following Stack Overflow question: Title: C++ code file extension? What is the difference between .cc and .cpp <p>I have seen C++ code saved as both <code>.cc</code> and <code>.cpp</code> files. Is there a difference between the two?</p> <p>The <a href="https://google.github.io/styleguide/cppguide.html" rel="noreferrer">Google style guide</a> seems to suggest <code>.cc</code>, but provides no explanation.</p> <p>I am mainly concerned with programs on Linux systems.</p>
<p>At the end of the day it doesn't matter because C++ compilers can deal with the files in either format. If it's a real issue within your team, flip a coin and move on to the actual work. </p>
{ "question_id": 1545080, "question_date": "2009-10-09T17:23:18.340Z", "question_score": 720, "tags": "c++|filenames", "answer_id": 1545085, "answer_date": "2009-10-09T17:25:07.880Z", "answer_score": 868 }
Please answer the following Stack Overflow question: Title: How do you copy and paste into Git Bash <p>I'm using <a href="http://code.google.com/p/msysgit/" rel="noreferrer">msysgit</a> running on Windows XP.</p> <p>Tried <kbd>Ctrl</kbd>+<kbd>V</kbd>, Right click, Middle click, google... no luck.</p>
<p>Press <kbd>Insert</kbd>.</p> <p>Also, to copy <em>from</em> the window, try clicking the console's window icon (topleft) and choosing Edit -> Mark, then drag a box on the text, then press Enter. (You can also paste via the window icon menu, but the key is faster.)</p> <p><strong>UPDATE</strong></p> <p>Starting from Windows 10 the <kbd>CTRL</kbd> + <kbd>C</kbd>, <kbd>CTRL</kbd> + <kbd>V</kbd> and a lot of other feature are implemented in conhost.exe so they should work with every console utility on Windows. (You have to enable Properties -> Option tab -> Quick Edit Mode)</p> <p>Ref: <a href="http://blogs.windows.com/buildingapps/2014/10/07/console-improvements-in-the-windows-10-technical-preview/" rel="noreferrer">http://blogs.windows.com/buildingapps/2014/10/07/console-improvements-in-the-windows-10-technical-preview/</a></p>
{ "question_id": 2304372, "question_date": "2010-02-21T00:54:56.297Z", "question_score": 720, "tags": "git|windows-xp|copy-paste|msysgit", "answer_id": 2304382, "answer_date": "2010-02-21T00:59:56.070Z", "answer_score": 1063 }
Please answer the following Stack Overflow question: Title: Push local Git repo to new remote including all branches and tags <p>I have a local Git repo that I would like to push to a new remote repo (brand new repo set up on Beanstalk, if that matters).<br> My local repo has a few branches and tags, and I would like to keep all of my history. </p> <p>It looks like I basically just need to do a <code>git push</code>, but that only uploads the <code>master</code> branch. </p> <p>How do I push everything so I get a full replica of my local repo on the remote?</p>
<p>To push <a href="https://git-scm.com/docs/git-push#git-push---all" rel="noreferrer">all your branches</a>, use either (replace REMOTE with the name of the remote, for example "origin"):</p> <pre><code>git push REMOTE '*:*' git push REMOTE --all </code></pre> <p>To push <a href="https://git-scm.com/docs/git-push#git-push---tags" rel="noreferrer">all your tags</a>:</p> <pre><code>git push REMOTE --tags </code></pre> <p>Finally, I think you can do this all in one command with:</p> <pre><code>git push REMOTE --mirror </code></pre> <p>However, in addition <a href="https://git-scm.com/docs/git-push#git-push---mirror" rel="noreferrer"><code>--mirror</code></a>, will also push your remotes, so this might not be exactly what you want.</p>
{ "question_id": 6865302, "question_date": "2011-07-28T20:33:35.847Z", "question_score": 720, "tags": "git", "answer_id": 6865367, "answer_date": "2011-07-28T20:38:52.660Z", "answer_score": 1162 }
Please answer the following Stack Overflow question: Title: What is an application binary interface (ABI)? <p>I never clearly understood what an ABI is. Please don't point me to a Wikipedia article. If I could understand it, I wouldn't be here posting such a lengthy post.</p> <p>This is my mindset about different interfaces:</p> <p>A TV remote is an interface between the user and the TV. It is an existing entity, but useless (doesn't provide any functionality) by itself. All the functionality for each of those buttons on the remote is implemented in the television set.</p> <blockquote> <p><strong>Interface:</strong> It is an "existing entity" layer between the <code>functionality</code> and <code>consumer</code> of that functionality. An interface by itself doesn't do anything. It just invokes the functionality lying behind.</p> <p>Now depending on who the user is there are different type of interfaces.</p> <p><strong>Command Line Interface (CLI)</strong> commands are the existing entities, the consumer is the user and functionality lies behind.</p> <p><code>functionality:</code> my software functionality which solves some purpose to which we are describing this interface.</p> <p><code>existing entities:</code> commands</p> <p><code>consumer:</code> user</p> <p><strong>Graphical User Interface(GUI)</strong> window, buttons, etc. are the existing entities, and again the consumer is the user and functionality lies behind.</p> <p><code>functionality:</code> my software functionality which solves some problem to which we are describing this interface.</p> <p><code>existing entities:</code> window, buttons etc..</p> <p><code>consumer:</code> user</p> <p><strong>Application Programming Interface(API)</strong> functions (or to be more correct) interfaces (in interfaced based programming) are the existing entities, consumer here is another program not a user, and again functionality lies behind this layer.</p> <p><code>functionality:</code> my software functionality which solves some problem to which we are describing this interface.</p> <p><code>existing entities:</code> functions, Interfaces (array of functions).</p> <p><code>consumer:</code> another program/application.</p> <p><strong>Application Binary Interface (ABI)</strong> Here is where my problem starts.</p> <p><code>functionality:</code> ???</p> <p><code>existing entities:</code> ???</p> <p><code>consumer:</code> ???</p> </blockquote> <ul> <li>I've written software in different languages and provided different kinds of interfaces (CLI, GUI, and API), but I'm not sure if I have ever provided any ABI.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Application_binary_interface" rel="noreferrer">Wikipedia says:</a></p> <blockquote> <p>ABIs cover details such as</p> <ul> <li>data type, size, and alignment;</li> <li>the calling convention, which controls how functions' arguments are passed and return values retrieved;</li> <li>the system call numbers and how an application should make system calls to the operating system;</li> </ul> <p>Other ABIs standardize details such as</p> <ul> <li>the C++ name mangling,</li> <li>exception propagation, and</li> <li>calling convention between compilers on the same platform, but do not require cross-platform compatibility.</li> </ul> </blockquote> <ul> <li><p>Who needs these details? Please don't say the OS. I know assembly programming. I know how linking &amp; loading works. I know exactly what happens inside.</p></li> <li><p>Why did C++ name mangling come in? I thought we are talking at the binary level. Why do languages come in?</p></li> </ul> <p>Anyway, I've downloaded the <a href="http://www.sco.com/developers/devspecs/gabi41.pdf" rel="noreferrer">[PDF] System V Application Binary Interface <em>Edition 4.1 (1997-03-18)</em></a> to see what exactly it contains. Well, most of it didn't make any sense.</p> <ul> <li><p>Why does it contain two chapters (4th &amp; 5th) to describe the <a href="http://en.wikipedia.org/wiki/Executable_and_Linkable_Format" rel="noreferrer">ELF</a> file format? In fact, these are the only two significant chapters of that specification. The rest of the chapters are "processor specific". Anyway, I though that it is a completely different topic. Please don't say that ELF file format specifications <em>are</em> the ABI. It doesn't qualify to be an <em>interface</em> according to the definition.</p></li> <li><p>I know, since we are talking at such a low level it must be very specific. But I'm not sure how is it "instruction set architecture (ISA)" specific?</p></li> <li><p>Where can I find Microsoft Windows' ABI?</p></li> </ul> <p>So, these are the major queries that are bugging me.</p>
<p>One easy way to understand "ABI" is to compare it to "API".</p> <p>You are already familiar with the concept of an API. If you want to use the features of, say, some library or your OS, you will program against an API. The API consists of data types/structures, constants, functions, etc that you can use in your code to access the functionality of that external component.</p> <p>An ABI is very similar. Think of it as the compiled version of an API (or as an API on the machine-language level). When you write source code, you access the library through an API. Once the code is compiled, your application accesses the binary data in the library through the ABI. The ABI defines the structures and methods that your compiled application will use to access the external library (just like the API did), only on a lower level. Your API defines the order in which you pass arguments to a function. Your ABI defines the mechanics of <em>how</em> these arguments are passed (registers, stack, etc.). Your API defines which functions are part of your library. Your ABI defines how your code is stored inside the library file, so that any program using your library can locate the desired function and execute it.</p> <p>ABIs are important when it comes to applications that use external libraries. Libraries are full of code and other resources, but your program has to know how to locate what it needs inside the library file. Your ABI defines how the contents of a library are stored inside the file, and your program uses the ABI to search through the file and find what it needs. If everything in your system conforms to the same ABI, then any program is able to work with any library file, no matter who created them. Linux and Windows use different ABIs, so a Windows program won't know how to access a library compiled for Linux.</p> <p>Sometimes, ABI changes are unavoidable. When this happens, any programs that use that library will not work unless they are re-compiled to use the new version of the library. If the ABI changes but the API does not, then the old and new library versions are sometimes called "source compatible". This implies that while a program compiled for one library version will not work with the other, source code written for one will work for the other if re-compiled.</p> <p>For this reason, developers tend to try to keep their ABI stable (to minimize disruption). Keeping an ABI stable means not changing function interfaces (return type and number, types, and order of arguments), definitions of data types or data structures, defined constants, etc. New functions and data types can be added, but existing ones must stay the same. If, for instance, your library uses 32-bit integers to indicate the offset of a function and you switch to 64-bit integers, then already-compiled code that uses that library will not be accessing that field (or any following it) correctly. Accessing data structure members gets converted into memory addresses and offsets during compilation and if the data structure changes, then these offsets will not point to what the code is expecting them to point to and the results are unpredictable at best.</p> <p>An ABI isn't necessarily something you will explicitly provide unless you are doing very low-level systems design work. It isn't language-specific either, since (for example) a C application and a Pascal application can use the same ABI after they are compiled.</p> <p><strong>Edit:</strong> Regarding your question about the chapters regarding the ELF file format in the SysV ABI docs: The reason this information is included is because the ELF format defines the interface between operating system and application. When you tell the OS to run a program, it expects the program to be formatted in a certain way and (for example) expects the first section of the binary to be an ELF header containing certain information at specific memory offsets. This is how the application communicates important information about itself to the operating system. If you build a program in a non-ELF binary format (such as a.out or PE), then an OS that expects ELF-formatted applications will not be able to interpret the binary file or run the application. This is one big reason why Windows apps cannot be run directly on a Linux machine (or vice versa) without being either re-compiled or run inside some type of emulation layer that can translate from one binary format to another.</p> <p>IIRC, Windows currently uses the <a href="http://en.wikipedia.org/wiki/Portable_Executable" rel="noreferrer">Portable Executable</a> (or, PE) format. There are links in the "external links" section of that Wikipedia page with more information about the PE format.</p> <p>Also, regarding your note about C++ name mangling: When locating a function in a library file, the function is typically looked up by name. C++ allows you to overload function names, so name alone is not sufficient to identify a function. C++ compilers have their own ways of dealing with this internally, called <em>name mangling</em>. An ABI can define a standard way of encoding the name of a function so that programs built with a different language or compiler can locate what they need. When you use <a href="https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c"><code>extern "c"</code></a> in a C++ program, you're instructing the compiler to use a standardized way of recording names that's understandable by other software.</p>
{ "question_id": 2171177, "question_date": "2010-01-31T09:30:24.200Z", "question_score": 720, "tags": "compiler-construction|abi", "answer_id": 2456882, "answer_date": "2010-03-16T18:04:28.433Z", "answer_score": 776 }
Please answer the following Stack Overflow question: Title: Generate an integer that is not among four billion given ones <p>I have been given this interview question:</p> <blockquote> <p>Given an input file with four billion integers, provide an algorithm to generate an integer which is not contained in the file. Assume you have 1&nbsp;GB memory. Follow up with what you would do if you have only 10&nbsp;MB of memory.</p> </blockquote> <h3>My analysis:</h3> <p>The size of the file is 4×10<sup>9</sup>×4 bytes = 16&nbsp;GB.</p> <p>We can do external sorting, thus letting us know the range of the integers.</p> <p>My question is what is the best way to detect the missing integer in the sorted big integer sets?</p> <h3>My understanding (after reading all the answers):</h3> <p>Assuming we are talking about 32-bit integers, there are 2<sup>32</sup> = 4*10<sup>9</sup> distinct integers.</p> <h1>Case 1: we have 1&nbsp;GB = 1 * 10<sup>9</sup> * 8 bits = 8 billion bits memory.</h1> <h3>Solution:</h3> <p>If we use one bit representing one distinct integer, it is enough. we don't need sort.</p> <h3>Implementation:</h3> <pre class="lang-cs prettyprint-override"><code>int radix = 8; byte[] bitfield = new byte[0xffffffff/radix]; void F() throws FileNotFoundException{ Scanner in = new Scanner(new FileReader("a.txt")); while(in.hasNextInt()){ int n = in.nextInt(); bitfield[n/radix] |= (1 &lt;&lt; (n%radix)); } for(int i = 0; i&lt; bitfield.lenght; i++){ for(int j =0; j&lt;radix; j++){ if( (bitfield[i] &amp; (1&lt;&lt;j)) == 0) System.out.print(i*radix+j); } } } </code></pre> <h1>Case 2: 10&nbsp;MB memory = 10 * 10<sup>6</sup> * 8 bits = 80 million bits</h1> <blockquote> <h3>Solution:</h3> <p>For all possible 16-bit prefixes, there are 2<sup>16</sup> number of integers = 65536, we need 2<sup>16</sup> * 4 * 8 = 2 million bits. We need build 65536 buckets. For each bucket, we need 4 bytes holding all possibilities because the worst case is all the 4 billion integers belong to the same bucket.</p> <ol> <li>Build the counter of each bucket through the first pass through the file.</li> <li>Scan the buckets, find the first one who has less than 65536 hit.</li> <li>Build new buckets whose high 16-bit prefixes are we found in step2 through second pass of the file</li> <li>Scan the buckets built in step3, find the first bucket which doesnt have a hit.</li> </ol> <p>The code is very similar to above one.</p> </blockquote> <p>Conclusion: We decrease memory through increasing file pass.</p> <hr> <p><sup> A clarification for those arriving late: The question, as asked, does not say that there is exactly one integer that is not contained in the file&mdash;at least that's not how most people interpret it. Many comments in the comment thread <strong>are</strong> about that variation of the task, though. Unfortunately the comment that <strong>introduced</strong> it to the comment thread was later deleted by its author, so now it looks like the orphaned replies to it just misunderstood everything. It's very confusing, sorry. </sup></p>
<p><strong>Assuming that "integer" means 32 bits</strong>: 10 MB of space is more than enough for you to count how many numbers there are in the input file with any given 16-bit prefix, for all possible 16-bit prefixes in one pass through the input file. At least one of the buckets will have be hit less than 2<sup>16</sup> times. Do a second pass to find of which of the possible numbers in that bucket are used already.</p> <p><strong>If it means more than 32 bits, but still of bounded size</strong>: Do as above, ignoring all input numbers that happen to fall outside the (signed or unsigned; your choice) 32-bit range.</p> <p><strong>If "integer" means mathematical integer</strong>: Read through the input once and keep track of the <strike>largest number</strike> length of the longest number you've ever seen. When you're done, output <strike>the maximum plus one</strike> a random number that has one more digit. (One of the numbers in the file may be a bignum that takes more than 10 MB to represent exactly, but if the input is a file, then you can at least represent the <em>length</em> of anything that fits in it).</p>
{ "question_id": 7153659, "question_date": "2011-08-22T21:11:47.960Z", "question_score": 720, "tags": "algorithm|file|search|out-of-memory|memory-limit", "answer_id": 7153822, "answer_date": "2011-08-22T21:28:00.790Z", "answer_score": 542 }
Please answer the following Stack Overflow question: Title: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops <p>How can I use regular expressions in Excel and take advantage of Excel's powerful grid-like setup for data manipulation?</p> <ul> <li>In-cell function to return a matched pattern or replaced value in a string.</li> <li>Sub to loop through a column of data and extract matches to adjacent cells.</li> <li>What setup is necessary?</li> <li>What are Excel's special characters for Regular expressions?</li> </ul> <hr> <p>I understand Regex is not ideal for many situations (<a href="https://stackoverflow.com/a/4098123/2521004">To use or not to use regular expressions?</a>) since excel can use <code>Left</code>, <code>Mid</code>, <code>Right</code>, <code>Instr</code> type commands for similar manipulations. </p>
<p><a href="http://en.wikipedia.org/wiki/Regular_expressions" rel="noreferrer">Regular expressions</a> are used for Pattern Matching.</p> <p>To use in Excel follow these steps:</p> <p><strong>Step 1</strong>: Add VBA reference to &quot;Microsoft VBScript Regular Expressions 5.5&quot;</p> <ul> <li>Select &quot;Developer&quot; tab (<a href="http://msdn.microsoft.com/en-us/library/bb608625.aspx" rel="noreferrer">I don't have this tab what do I do?</a>)</li> <li>Select &quot;Visual Basic&quot; icon from 'Code' ribbon section</li> <li>In &quot;Microsoft Visual Basic for Applications&quot; window select &quot;Tools&quot; from the top menu.</li> <li>Select &quot;References&quot;</li> <li>Check the box next to &quot;Microsoft VBScript Regular Expressions 5.5&quot; to include in your workbook.</li> <li>Click &quot;OK&quot;</li> </ul> <p><strong>Step 2</strong>: Define your pattern</p> <p><em>Basic definitions:</em></p> <p><code>-</code> Range.</p> <ul> <li>E.g. <code>a-z</code> matches an lower case letters from a to z</li> <li>E.g. <code>0-5</code> matches any number from 0 to 5</li> </ul> <p><code>[]</code> Match exactly one of the objects inside these brackets.</p> <ul> <li>E.g. <code>[a]</code> matches the letter a</li> <li>E.g. <code>[abc]</code> matches a single letter which can be a, b or c</li> <li>E.g. <code>[a-z]</code> matches any single lower case letter of the alphabet.</li> </ul> <p><code>()</code> Groups different matches for return purposes. See examples below.</p> <p><code>{}</code> Multiplier for repeated copies of pattern defined before it.</p> <ul> <li>E.g. <code>[a]{2}</code> matches two consecutive lower case letter a: <code>aa</code></li> <li>E.g. <code>[a]{1,3}</code> matches at least one and up to three lower case letter <code>a</code>, <code>aa</code>, <code>aaa</code></li> </ul> <p><code>+</code> Match at least one, or more, of the pattern defined before it.</p> <ul> <li>E.g. <code>a+</code> will match consecutive a's <code>a</code>, <code>aa</code>, <code>aaa</code>, and so on</li> </ul> <p><code>?</code> Match zero or one of the pattern defined before it.</p> <ul> <li>E.g. Pattern may or may not be present but can only be matched one time.</li> <li>E.g. <code>[a-z]?</code> matches empty string or any single lower case letter.</li> </ul> <p><code>*</code> Match zero or more of the pattern defined before it.</p> <ul> <li>E.g. Wildcard for pattern that may or may not be present.</li> <li>E.g. <code>[a-z]*</code> matches empty string or string of lower case letters.</li> </ul> <p><code>.</code> Matches any character except newline <code>\n</code></p> <ul> <li>E.g. <code>a.</code> Matches a two character string starting with a and ending with anything except <code>\n</code></li> </ul> <p><code>|</code> OR operator</p> <ul> <li>E.g. <code>a|b</code> means either <code>a</code> or <code>b</code> can be matched.</li> <li>E.g. <code>red|white|orange</code> matches exactly one of the colors.</li> </ul> <p><code>^</code> NOT operator</p> <ul> <li>E.g. <code>[^0-9]</code> character can not contain a number</li> <li>E.g. <code>[^aA]</code> character can not be lower case <code>a</code> or upper case <code>A</code></li> </ul> <p><code>\</code> Escapes special character that follows (overrides above behavior)</p> <ul> <li>E.g. <code>\.</code>, <code>\\</code>, <code>\(</code>, <code>\?</code>, <code>\$</code>, <code>\^</code></li> </ul> <hr /> <p><em>Anchoring Patterns:</em></p> <p><code>^</code> Match must occur at start of string</p> <ul> <li>E.g. <code>^a</code> First character must be lower case letter <code>a</code></li> <li>E.g. <code>^[0-9]</code> First character must be a number.</li> </ul> <p><code>$</code> Match must occur at end of string</p> <ul> <li>E.g. <code>a$</code> Last character must be lower case letter <code>a</code></li> </ul> <hr /> <p><em>Precedence table:</em></p> <pre><code>Order Name Representation 1 Parentheses ( ) 2 Multipliers ? + * {m,n} {m, n}? 3 Sequence &amp; Anchors abc ^ $ 4 Alternation | </code></pre> <hr /> <p><em>Predefined Character Abbreviations:</em></p> <pre><code>abr same as meaning \d [0-9] Any single digit \D [^0-9] Any single character that's not a digit \w [a-zA-Z0-9_] Any word character \W [^a-zA-Z0-9_] Any non-word character \s [ \r\t\n\f] Any space character \S [^ \r\t\n\f] Any non-space character \n [\n] New line </code></pre> <hr /> <p><strong>Example 1</strong>: <em>Run as macro</em></p> <p>The following example macro looks at the value in cell <code>A1</code> to see if the first 1 or 2 characters are digits. If so, they are removed and the rest of the string is displayed. If not, then a box appears telling you that no match is found. Cell <code>A1</code> values of <code>12abc</code> will return <code>abc</code>, value of <code>1abc</code> will return <code>abc</code>, value of <code>abc123</code> will return &quot;Not Matched&quot; because the digits were not at the start of the string.</p> <pre><code>Private Sub simpleRegex() Dim strPattern As String: strPattern = &quot;^[0-9]{1,2}&quot; Dim strReplace As String: strReplace = &quot;&quot; Dim regEx As New RegExp Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range(&quot;A1&quot;) If strPattern &lt;&gt; &quot;&quot; Then strInput = Myrange.Value With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.Test(strInput) Then MsgBox (regEx.Replace(strInput, strReplace)) Else MsgBox (&quot;Not matched&quot;) End If End If End Sub </code></pre> <hr /> <p><strong>Example 2</strong>: <em>Run as an in-cell function</em></p> <p>This example is the same as example 1 but is setup to run as an in-cell function. To use, change the code to this:</p> <pre><code>Function simpleCellRegex(Myrange As Range) As String Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim strReplace As String Dim strOutput As String strPattern = &quot;^[0-9]{1,3}&quot; If strPattern &lt;&gt; &quot;&quot; Then strInput = Myrange.Value strReplace = &quot;&quot; With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then simpleCellRegex = regEx.Replace(strInput, strReplace) Else simpleCellRegex = &quot;Not matched&quot; End If End If End Function </code></pre> <p>Place your strings (&quot;12abc&quot;) in cell <code>A1</code>. Enter this formula <code>=simpleCellRegex(A1)</code> in cell <code>B1</code> and the result will be &quot;abc&quot;.</p> <p><img src="https://i.stack.imgur.com/q3RRC.png" alt="results image" /></p> <hr /> <p><strong>Example 3</strong>: <em>Loop Through Range</em></p> <p>This example is the same as example 1 but loops through a range of cells.</p> <pre><code>Private Sub simpleRegex() Dim strPattern As String: strPattern = &quot;^[0-9]{1,2}&quot; Dim strReplace As String: strReplace = &quot;&quot; Dim regEx As New RegExp Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range(&quot;A1:A5&quot;) For Each cell In Myrange If strPattern &lt;&gt; &quot;&quot; Then strInput = cell.Value With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.Test(strInput) Then MsgBox (regEx.Replace(strInput, strReplace)) Else MsgBox (&quot;Not matched&quot;) End If End If Next End Sub </code></pre> <hr /> <p><strong>Example 4</strong>: Splitting apart different patterns</p> <p>This example loops through a range (<code>A1</code>, <code>A2</code> &amp; <code>A3</code>) and looks for a string starting with three digits followed by a single alpha character and then 4 numeric digits. The output splits apart the pattern matches into adjacent cells by using the <code>()</code>. <code>$1</code> represents the first pattern matched within the first set of <code>()</code>.</p> <pre><code>Private Sub splitUpRegexPattern() Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim Myrange As Range Set Myrange = ActiveSheet.Range(&quot;A1:A3&quot;) For Each C In Myrange strPattern = &quot;(^[0-9]{3})([a-zA-Z])([0-9]{4})&quot; If strPattern &lt;&gt; &quot;&quot; Then strInput = C.Value With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then C.Offset(0, 1) = regEx.Replace(strInput, &quot;$1&quot;) C.Offset(0, 2) = regEx.Replace(strInput, &quot;$2&quot;) C.Offset(0, 3) = regEx.Replace(strInput, &quot;$3&quot;) Else C.Offset(0, 1) = &quot;(Not matched)&quot; End If End If Next End Sub </code></pre> <p>Results:</p> <p><img src="https://i.stack.imgur.com/9eCZ5.png" alt="results image" /></p> <hr /> <p><strong>Additional Pattern Examples</strong></p> <pre class="lang-none prettyprint-override"><code>String Regex Pattern Explanation a1aaa [a-zA-Z][0-9][a-zA-Z]{3} Single alpha, single digit, three alpha characters a1aaa [a-zA-Z]?[0-9][a-zA-Z]{3} May or may not have preceding alpha character a1aaa [a-zA-Z][0-9][a-zA-Z]{0,3} Single alpha, single digit, 0 to 3 alpha characters a1aaa [a-zA-Z][0-9][a-zA-Z]* Single alpha, single digit, followed by any number of alpha characters &lt;/i8&gt; \&lt;\/[a-zA-Z][0-9]\&gt; Exact non-word character except any single alpha followed by any single digit </code></pre>
{ "question_id": 22542834, "question_date": "2014-03-20T19:09:13.197Z", "question_score": 719, "tags": "regex|excel|vba", "answer_id": 22542835, "answer_date": "2014-03-20T19:09:13.197Z", "answer_score": 1100 }
Please answer the following Stack Overflow question: Title: How to export JavaScript array info to csv (on client side)? <p>I know there are lot of questions of this nature but I need to do this using JavaScript. I am using <code>Dojo 1.8</code> and have all the attribute info in array, which looks like this:</p> <pre><code>[["name1", "city_name1", ...]["name2", "city_name2", ...]] </code></pre> <p>Any idea how I can export this to <code>CSV</code> on the client side?</p>
<p>You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):</p> <pre><code>const rows = [ ["name1", "city1", "some other info"], ["name2", "city2", "more info"] ]; let csvContent = "data:text/csv;charset=utf-8,"; rows.forEach(function(rowArray) { let row = rowArray.join(","); csvContent += row + "\r\n"; }); </code></pre> <p>or the shorter way (using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a>):</p> <pre><code>const rows = [ ["name1", "city1", "some other info"], ["name2", "city2", "more info"] ]; let csvContent = "data:text/csv;charset=utf-8," + rows.map(e =&gt; e.join(",")).join("\n"); </code></pre> <p>Then you can use JavaScript's <code>window.open</code> and <code>encodeURI</code> functions to download the CSV file like so:</p> <pre><code>var encodedUri = encodeURI(csvContent); window.open(encodedUri); </code></pre> <p><h3>Edit:</h3> If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using the <code>window.open</code> method. In order to achieve this, you can create a hidden <code>&lt;a&gt;</code> DOM node and set its <code>download</code> attribute as follows:</p> <pre><code>var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "my_data.csv"); document.body.appendChild(link); // Required for FF link.click(); // This will download the data file named "my_data.csv". </code></pre>
{ "question_id": 14964035, "question_date": "2013-02-19T16:49:24.263Z", "question_score": 719, "tags": "javascript|csv|export|client-side|dojo-1.8", "answer_id": 14966131, "answer_date": "2013-02-19T19:51:13.533Z", "answer_score": 1183 }
Please answer the following Stack Overflow question: Title: How do I enumerate the properties of a JavaScript object? <p>How do I enumerate the properties of a JavaScript object?</p> <p>I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.</p>
<p>Simple enough:</p> <pre><code>for(var propertyName in myObject) { // propertyName is what you want // you can get the value like this: myObject[propertyName] } </code></pre> <p>Now, you will not get private variables this way because they are not available.</p> <hr> <p>EDIT: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> is correct that unless you use the <code>hasOwnProperty()</code> method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.</p> <p>Now, that said, <code>hasOwnProperty()</code> <em>is</em> useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.</p> <p>EDIT 2: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use <code>hasOwnProperty()</code>. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via <code>jQuery.extend</code> and <code>jQuery.fn.extend</code>).</p>
{ "question_id": 85992, "question_date": "2008-09-17T18:10:18.380Z", "question_score": 719, "tags": "javascript|properties", "answer_id": 86014, "answer_date": "2008-09-17T18:12:21.650Z", "answer_score": 884 }
Please answer the following Stack Overflow question: Title: Remove accents/diacritics in a string in JavaScript <p>How do I remove accentuated characters from a string? Especially in IE6, I had something like this:</p> <pre><code>accentsTidy = function(s){ var r=s.toLowerCase(); r = r.replace(new RegExp(/\s/g),""); r = r.replace(new RegExp(/[àáâãäå]/g),"a"); r = r.replace(new RegExp(/æ/g),"ae"); r = r.replace(new RegExp(/ç/g),"c"); r = r.replace(new RegExp(/[èéêë]/g),"e"); r = r.replace(new RegExp(/[ìíîï]/g),"i"); r = r.replace(new RegExp(/ñ/g),"n"); r = r.replace(new RegExp(/[òóôõö]/g),"o"); r = r.replace(new RegExp(/œ/g),"oe"); r = r.replace(new RegExp(/[ùúûü]/g),"u"); r = r.replace(new RegExp(/[ýÿ]/g),"y"); r = r.replace(new RegExp(/\W/g),""); return r; }; </code></pre> <p>but IE6 bugs me, seems it doesn't like my regular expression.</p>
<p>With ES2015/ES6 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize" rel="noreferrer">String.prototype.normalize()</a>,</p> <pre><code>const str = &quot;Crème Brulée&quot; str.normalize(&quot;NFD&quot;).replace(/[\u0300-\u036f]/g, &quot;&quot;) &gt; &quot;Creme Brulee&quot; </code></pre> <p>Note: use <code>NFKD</code> if you want things like <code>\uFB01</code>(<code>fi</code>) normalized (to <code>fi</code>).</p> <p>Two things are happening here:</p> <ol> <li><code>normalize()</code>ing to <code>NFD</code> Unicode normal form decomposes combined graphemes into the combination of simple ones. The <code>è</code> of <code>Crème</code> ends up expressed as <code>e</code> + <code> ̀</code>.</li> <li>Using a regex <a href="http://www.regular-expressions.info/charclass.html" rel="noreferrer">character class</a> to match the U+0300 → U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the <a href="https://en.wikipedia.org/wiki/Combining_Diacritical_Marks" rel="noreferrer">Combining Diacritical Marks</a> Unicode block.</li> </ol> <p>As of 2021, one can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes" rel="noreferrer">Unicode property escapes</a>:</p> <pre><code>str.normalize(&quot;NFD&quot;).replace(/\p{Diacritic}/gu, &quot;&quot;) </code></pre> <p>See comment for performance testing.</p> <p><strong>Alternatively, if you just want sorting</strong></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator" rel="noreferrer">Intl.Collator</a> has sufficient support <a href="https://caniuse.com/#search=intl.collator" rel="noreferrer">~95% right now</a>, a polyfill is also available <a href="https://github.com/andyearnshaw/Intl.js/" rel="noreferrer">here</a> but I haven't tested it.</p> <pre><code>const c = new Intl.Collator(); [&quot;creme brulee&quot;, &quot;crème brulée&quot;, &quot;crame brulai&quot;, &quot;crome brouillé&quot;, &quot;creme brulay&quot;, &quot;creme brulfé&quot;, &quot;creme bruléa&quot;].sort(c.compare) [&quot;crame brulai&quot;, &quot;creme brulay&quot;, &quot;creme bruléa&quot;, &quot;creme brulee&quot;, &quot;crème brulée&quot;, &quot;creme brulfé&quot;, &quot;crome brouillé&quot;] [&quot;creme brulee&quot;, &quot;crème brulée&quot;, &quot;crame brulai&quot;, &quot;crome brouillé&quot;].sort((a,b) =&gt; a&gt;b) [&quot;crame brulai&quot;, &quot;creme brulee&quot;, &quot;crome brouillé&quot;, &quot;crème brulée&quot;] </code></pre>
{ "question_id": 990904, "question_date": "2009-06-13T15:49:01.490Z", "question_score": 719, "tags": "javascript|diacritics", "answer_id": 37511463, "answer_date": "2016-05-29T15:06:27.167Z", "answer_score": 1705 }
Please answer the following Stack Overflow question: Title: Set value for particular cell in pandas DataFrame using index <p>I have created a Pandas DataFrame</p> <pre><code>df = DataFrame(index=['A','B','C'], columns=['x','y']) </code></pre> <p>and have got this</p> <pre> x y A NaN NaN B NaN NaN C NaN NaN </pre> <p>Now, I would like to assign a value to particular cell, for example to row <code>C</code> and column <code>x</code>. I would expect to get this result:</p> <pre> x y A NaN NaN B NaN NaN C 10 NaN </pre> <p>with this code:</p> <pre><code>df.xs('C')['x'] = 10 </code></pre> <p>However, the contents of <code>df</code> has not changed. The dataframe contains yet again only <code>NaN</code>s.</p> <p>Any suggestions?</p>
<p><a href="https://stackoverflow.com/a/24517695/190597">RukTech's answer</a>, <code>df.set_value('C', 'x', 10)</code>, is far and away faster than the options I've suggested below. However, it has been <a href="https://github.com/pandas-dev/pandas/issues/15269" rel="noreferrer"><strong>slated for deprecation</strong></a>.</p> <p>Going forward, the <a href="https://github.com/pandas-dev/pandas/issues/15269#issuecomment-276382712" rel="noreferrer">recommended method is <code>.iat/.at</code></a>.</p> <hr> <p><strong>Why <code>df.xs('C')['x']=10</code> does not work:</strong></p> <p><code>df.xs('C')</code> by default, returns a new dataframe <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html#pandas.DataFrame.xsY" rel="noreferrer">with a copy</a> of the data, so </p> <pre><code>df.xs('C')['x']=10 </code></pre> <p>modifies this new dataframe only.</p> <p><code>df['x']</code> returns a view of the <code>df</code> dataframe, so </p> <pre><code>df['x']['C'] = 10 </code></pre> <p>modifies <code>df</code> itself.</p> <p><strong>Warning</strong>: It is sometimes difficult to predict if an operation returns a copy or a view. For this reason the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy" rel="noreferrer">docs recommend avoiding assignments with "chained indexing"</a>. </p> <hr> <p>So the recommended alternative is</p> <pre><code>df.at['C', 'x'] = 10 </code></pre> <p>which <em>does</em> modify <code>df</code>.</p> <hr> <pre><code>In [18]: %timeit df.set_value('C', 'x', 10) 100000 loops, best of 3: 2.9 µs per loop In [20]: %timeit df['x']['C'] = 10 100000 loops, best of 3: 6.31 µs per loop In [81]: %timeit df.at['C', 'x'] = 10 100000 loops, best of 3: 9.2 µs per loop </code></pre>
{ "question_id": 13842088, "question_date": "2012-12-12T14:40:45.683Z", "question_score": 718, "tags": "python|pandas|dataframe|cell|nan", "answer_id": 13842286, "answer_date": "2012-12-12T14:51:02.073Z", "answer_score": 875 }
Please answer the following Stack Overflow question: Title: How to find if an array contains a specific string in JavaScript/jQuery? <p>Can someone tell me how to detect if <code>"specialword"</code> appears in an array? Example:</p> <pre><code>categories: [ "specialword" "word1" "word2" ] </code></pre>
<p>You really don't need jQuery for this.</p> <pre><code>var myarr = ["I", "like", "turtles"]; var arraycontainsturtles = (myarr.indexOf("turtles") &gt; -1); </code></pre> <blockquote> <p><strong>Hint</strong>: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs</p> </blockquote> <p>or</p> <pre><code>function arrayContains(needle, arrhaystack) { return (arrhaystack.indexOf(needle) &gt; -1); } </code></pre> <p>It's worth noting that <code>array.indexOf(..)</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility" rel="noreferrer">not supported in IE &lt; 9</a>, but jQuery's <code>indexOf(...)</code> function will work even for those older versions. </p>
{ "question_id": 6116474, "question_date": "2011-05-24T20:31:35.483Z", "question_score": 718, "tags": "javascript|jquery|arrays|string", "answer_id": 15276975, "answer_date": "2013-03-07T16:50:25.120Z", "answer_score": 1121 }
Please answer the following Stack Overflow question: Title: Writing to output window of Visual Studio <p>I am trying to write a message to the output window for debugging purposes. I searched for a function like Java's <code>system.out.println("")</code>. I tried <code>Debug.Write</code>, <code>Console.Write</code>, and <code>Trace.Write</code>. It does not give an error, but it does not print anything either.</p> <p>"Define DEBUG constant" and "Define TRACE constant" options are checked.</p> <p>Menu <em>Tools</em> → <em>Options</em> → <em>Debugging</em> → <em>"Redirect all Output Window text to the Immediate Window"</em> option is not checked.</p> <p>Configuration: Active (Debug)</p> <p>Note: I created a project with the wizard as "Windows Forms Application" if relevant. I have no idea where to look.</p>
<p>Add the <code>System.Diagnostics</code> namespace, and then you can use <code>Debug.WriteLine()</code> to quickly print a message to the output window of the IDE. For more details, please refer to these:</p> <ul> <li><em><a href="http://support.microsoft.com/kb/815788" rel="noreferrer">How to trace and debug in Visual C#</a></em></li> <li><em><a href="http://www.codeproject.com/Articles/3008/A-Treatise-on-Using-Debug-and-Trace-classes-includ" rel="noreferrer">A Treatise on Using Debug and Trace classes, including Exception Handling</a></em></li> </ul>
{ "question_id": 9466838, "question_date": "2012-02-27T14:40:12.453Z", "question_score": 718, "tags": "c#|visual-studio-2010|visual-studio|debugging", "answer_id": 9466908, "answer_date": "2012-02-27T14:43:31.203Z", "answer_score": 872 }
Please answer the following Stack Overflow question: Title: How do I replace a character at a particular index in JavaScript? <p>I have a string, let's say <code>Hello world</code> and I need to replace the char at index 3. How can I replace a char by specifying a index?</p> <pre><code>var str = "hello world"; </code></pre> <p>I need something like</p> <pre><code>str.replaceAt(0,"h"); </code></pre>
<p>In JavaScript, strings are <strong>immutable</strong>, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.</p> <p>You'll need to define the <code>replaceAt()</code> function yourself:</p> <pre><code>String.prototype.replaceAt = function(index, replacement) { return this.substring(0, index) + replacement + this.substring(index + replacement.length); } </code></pre> <p>And use it like this:</p> <pre><code>var hello = &quot;Hello World&quot;; alert(hello.replaceAt(2, &quot;!!&quot;)); // He!!o World </code></pre>
{ "question_id": 1431094, "question_date": "2009-09-16T05:21:22.573Z", "question_score": 718, "tags": "javascript|string|replace|character-replacement", "answer_id": 1431113, "answer_date": "2009-09-16T05:29:21.560Z", "answer_score": 784 }
Please answer the following Stack Overflow question: Title: Single quotes vs. double quotes in Python <p>According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?</p>
<p>I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.</p> <p>For example:</p> <pre><code>LIGHT_MESSAGES = { 'English': "There are %(number_of_lights)s lights.", 'Pirate': "Arr! Thar be %(number_of_lights)s lights." } def lights_message(language, number_of_lights): """Return a language-appropriate string reporting the light count.""" return LIGHT_MESSAGES[language] % locals() def is_pirate(message): """Return True if the given message sounds piratical.""" return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None </code></pre>
{ "question_id": 56011, "question_date": "2008-09-11T08:18:55.293Z", "question_score": 718, "tags": "python|coding-style", "answer_id": 56190, "answer_date": "2008-09-11T10:06:49.557Z", "answer_score": 525 }
Please answer the following Stack Overflow question: Title: What is the best way to auto-generate INSERT statements for a SQL Server table? <p>We are writing a new application, and while testing, we will need a bunch of dummy data. I've added that data by using MS Access to dump excel files into the relevant tables.</p> <p>Every so often, we want to "refresh" the relevant tables, which means dropping them all, re-creating them, and running a saved MS Access append query.</p> <p>The first part (dropping &amp; re-creating) is an easy sql script, but the last part makes me cringe. I want a single setup script that has a bunch of INSERTs to regenerate the dummy data.</p> <p>I have the data in the tables now. What is the best way to automatically generate a big list of INSERT statements from that dataset?</p> <p>The only way I can think of doing it is to save the table to an excel sheet and then write an excel formula to create an INSERT for every row, which is surely not the best way.</p> <p>I'm using the 2008 Management Studio to connect to a SQL Server 2005 database.</p>
<p>Microsoft should advertise this functionality of SSMS 2008. The feature you are looking for is built into the <strong>Generate Script</strong> utility, but the functionality is turned off by default and must be enabled when scripting a table.</p> <p>This is a quick run through to generate the <code>INSERT</code> statements for all of the data in your table, using no scripts or add-ins to SQL Management Studio 2008:</p> <ol> <li>Right-click on the database and go to <strong>Tasks</strong> > <strong>Generate Scripts</strong>.</li> <li>Select the tables (or objects) that you want to generate the script against.</li> <li>Go to <strong>Set scripting options</strong> tab and click on the <strong>Advanced</strong> button.</li> <li>In the <strong>General</strong> category, go to <strong>Type of data to script</strong></li> <li>There are 3 options: <strong>Schema Only</strong>, <strong>Data Only</strong>, and <strong>Schema and Data</strong>. Select the appropriate option and click on <strong>OK</strong>. <a href="https://i.stack.imgur.com/fWKfA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fWKfA.png" alt="SqlDataOptions"></a></li> </ol> <p>You will then get the <code>CREATE TABLE</code> statement and all of the <code>INSERT</code> statements for the data straight out of SSMS.</p>
{ "question_id": 982568, "question_date": "2009-06-11T17:42:28.067Z", "question_score": 718, "tags": "sql-server|ssms|code-generation", "answer_id": 1316313, "answer_date": "2009-08-22T16:11:27.490Z", "answer_score": 1220 }
Please answer the following Stack Overflow question: Title: What is meant with "const" at end of function declaration? <p>I got a book, where there is written something like:</p> <pre><code>class Foo { public: int Bar(int random_arg) const { // code } }; </code></pre> <p>What does it mean?</p>
<p>A "const function", denoted with the keyword <code>const</code> after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error. </p> <p>Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit <code>this</code> pointer. So a method <code>int Foo::Bar(int random_arg)</code> (without the const at the end) results in a function like <code>int Foo_Bar(Foo* this, int random_arg)</code>, and a call such as <code>Foo f; f.Bar(4)</code> will internally correspond to something like <code>Foo f; Foo_Bar(&amp;f, 4)</code>. Now adding the const at the end (<code>int Foo::Bar(int random_arg) const</code>) can then be understood as a declaration with a const this pointer: <code>int Foo_Bar(const Foo* this, int random_arg)</code>. Since the type of <code>this</code> in such case is const, no modifications of member variables are possible.</p> <p>It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword <code>mutable</code>. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)</p> <p>As usual when dealing with the <code>const</code> keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of <code>const</code> only applies when adding <code>const</code> to the end of the function declaration after the parenthesis. </p> <p><code>const</code> is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about <code>const</code> correctness and the <code>const</code> keyword:</p> <p><a href="http://en.wikipedia.org/wiki/Const-correctness" rel="noreferrer">Const correctness</a></p> <p><a href="http://duramecho.com/ComputerInformation/WhyHowCppConst.html" rel="noreferrer">The C++ 'const' Declaration: Why &amp; How</a></p>
{ "question_id": 3141087, "question_date": "2010-06-29T13:31:02.737Z", "question_score": 718, "tags": "c++|constants", "answer_id": 3141107, "answer_date": "2010-06-29T13:32:15.513Z", "answer_score": 1171 }
Please answer the following Stack Overflow question: Title: HTML form readonly SELECT tag/input <p>According to HTML specs, the <code>select</code> tag in HTML doesn't have a <code>readonly</code> attribute, only a <code>disabled</code> attribute. So if you want to keep the user from changing the dropdown, you have to use <code>disabled</code>.</p> <p>The only problem is that disabled HTML form inputs don't get included in the POST / GET data.</p> <p>What's the best way to emulate the <code>readonly</code> attribute for a <code>select</code> tag, and still get the POST data?</p>
<p>You should keep the <code>select</code> element <code>disabled</code> but also add another hidden <code>input</code> with the same name and value.</p> <p>If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.</p> <p>Here is a demo:</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-js lang-js prettyprint-override"><code>$('#mainform').submit(function() { $('#formdata_container').show(); $('#formdata').html($(this).serialize()); return false; }); $('#enableselect').click(function() { $('#mainform input[name=animal]') .attr("disabled", true); $('#animal-select') .attr('disabled', false) .attr('name', 'animal'); $('#enableselect').hide(); return false; });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#formdata_container { padding: 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt; &lt;form id="mainform"&gt; &lt;select id="animal-select" disabled="true"&gt; &lt;option value="cat" selected&gt;Cat&lt;/option&gt; &lt;option value="dog"&gt;Dog&lt;/option&gt; &lt;option value="hamster"&gt;Hamster&lt;/option&gt; &lt;/select&gt; &lt;input type="hidden" name="animal" value="cat"/&gt; &lt;button id="enableselect"&gt;Enable&lt;/button&gt; &lt;select name="color"&gt; &lt;option value="blue" selected&gt;Blue&lt;/option&gt; &lt;option value="green"&gt;Green&lt;/option&gt; &lt;option value="red"&gt;Red&lt;/option&gt; &lt;/select&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="formdata_container" style="display:none"&gt; &lt;div&gt;Submitted data:&lt;/div&gt; &lt;div id="formdata"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 368813, "question_date": "2008-12-15T15:59:09.987Z", "question_score": 717, "tags": "javascript|html", "answer_id": 368834, "answer_date": "2008-12-15T16:03:17.060Z", "answer_score": 529 }
Please answer the following Stack Overflow question: Title: How can I remove the first line of a text file using bash/sed script? <p>I need to repeatedly remove the first line from a huge text file using a bash script.</p> <p>Right now I am using <code>sed -i -e "1d" $FILE</code> - but it takes around a minute to do the deletion.</p> <p>Is there a more efficient way to accomplish this?</p>
<p>Try <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer">tail</a>:</p> <pre><code>tail -n +2 "$FILE" </code></pre> <p><code>-n x</code>: Just print the last <code>x</code> lines. <code>tail -n 5</code> would give you the last 5 lines of the input. The <code>+</code> sign kind of inverts the argument and make <code>tail</code> print anything but the first <code>x-1</code> lines. <code>tail -n +1</code> would print the whole file, <code>tail -n +2</code> everything but the first line, etc.</p> <p>GNU <code>tail</code> is much faster than <code>sed</code>. <code>tail</code> is also available on BSD and the <code>-n +2</code> flag is consistent across both tools. Check the <a href="https://www.freebsd.org/cgi/man.cgi?query=tail" rel="noreferrer">FreeBSD</a> or <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html" rel="noreferrer">OS X</a> man pages for more. </p> <p>The BSD version can be much slower than <code>sed</code>, though. I wonder how they managed that; <code>tail</code> should just read a file line by line while <code>sed</code> does pretty complex operations involving interpreting a script, applying regular expressions and the like.</p> <p>Note: You may be tempted to use</p> <pre><code># THIS WILL GIVE YOU AN EMPTY FILE! tail -n +2 "$FILE" &gt; "$FILE" </code></pre> <p>but this will give you an <strong>empty file</strong>. The reason is that the redirection (<code>&gt;</code>) happens before <code>tail</code> is invoked by the shell:</p> <ol> <li>Shell truncates file <code>$FILE</code></li> <li>Shell creates a new process for <code>tail</code></li> <li>Shell redirects stdout of the <code>tail</code> process to <code>$FILE</code></li> <li><code>tail</code> reads from the now empty <code>$FILE</code></li> </ol> <p>If you want to remove the first line inside the file, you should use:</p> <pre><code>tail -n +2 "$FILE" &gt; "$FILE.tmp" &amp;&amp; mv "$FILE.tmp" "$FILE" </code></pre> <p>The <code>&amp;&amp;</code> will make sure that the file doesn't get overwritten when there is a problem.</p>
{ "question_id": 339483, "question_date": "2008-12-04T02:50:16.447Z", "question_score": 717, "tags": "bash|scripting|sed", "answer_id": 339941, "answer_date": "2008-12-04T08:55:16.587Z", "answer_score": 1278 }
Please answer the following Stack Overflow question: Title: Regex to replace multiple spaces with a single space <p>Given a string like: </p> <pre>"The dog has a long tail, and it is RED!"</pre> <p>What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?</p> <p>Goal: </p> <pre>"The dog has a long tail, and it is RED!"</pre>
<p>Given that you also want to cover tabs, newlines, etc, just replace <code>\s\s+</code> with <code>' '</code>: </p> <pre><code>string = string.replace(/\s\s+/g, ' '); </code></pre> <p>If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:</p> <pre><code>string = string.replace(/ +/g, ' '); </code></pre>
{ "question_id": 1981349, "question_date": "2009-12-30T17:28:58.513Z", "question_score": 717, "tags": "javascript|jquery|regex", "answer_id": 1981366, "answer_date": "2009-12-30T17:31:26.237Z", "answer_score": 1281 }
Please answer the following Stack Overflow question: Title: Should I use Singular or Plural name convention for REST resources? <p>I'm new to REST and I've observed that in some RESTful services they use different resource URI for update/get/delete and Create. Such as</p> <ul> <li>Create - using <strong><em>/resources</em></strong> with POST method (observe plural) at some places using <strong><em>/resource</em></strong> (singular)</li> <li>Update - using <strong><em>/resource/123</em></strong> with PUT method</li> <li>Get - Using <strong><em>/resource/123</em></strong> with GET method</li> </ul> <p>I'm little bit confused about this URI naming convention. What should we use plural or singular for resource creation? What should be the criteria while deciding that?</p>
<p>The premise of using <code>/resources</code> is that it is representing "all" resources. If you do a <code>GET /resources</code>, you will likely return the entire collection. By POSTing to <code>/resources</code>, you are adding to the collection.</p> <p>However, the individual resources are available at /resource. If you do a <code>GET /resource</code>, you will likely error, as this request doesn't make any sense, whereas <code>/resource/123</code> makes perfect sense.</p> <p>Using <code>/resource</code> instead of <code>/resources</code> is similar to how you would do this if you were working with, say, a file system and a collection of files and <code>/resource</code> is the "directory" with the individual <code>123</code>, <code>456</code> files in it.</p> <p>Neither way is right or wrong, go with what you like best.</p>
{ "question_id": 6845772, "question_date": "2011-07-27T14:05:37.540Z", "question_score": 717, "tags": "rest|resources|naming-conventions|uri", "answer_id": 6846057, "answer_date": "2011-07-27T14:26:27.417Z", "answer_score": 367 }
Please answer the following Stack Overflow question: Title: What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__() <p>What's the difference between:</p> <pre><code>class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() </code></pre> <p>and:</p> <pre><code>class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) </code></pre> <p>I've seen <code>super</code> being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.</p>
<p>The benefits of <code>super()</code> in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.</p> <p>However, it's almost impossible to use multiple-inheritance without <code>super()</code>. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended <code>Child</code> and a mixin, their code would not work properly.</p>
{ "question_id": 222877, "question_date": "2008-10-21T18:13:15.027Z", "question_score": 717, "tags": "python|oop|inheritance|multiple-inheritance|super", "answer_id": 222922, "answer_date": "2008-10-21T18:24:50.463Z", "answer_score": 352 }
Please answer the following Stack Overflow question: Title: Asking the user for input until they give a valid response <p>I am writing a program that accepts user input.</p> <pre><code>#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input` age = int(input(&quot;Please enter your age: &quot;)) if age &gt;= 18: print(&quot;You are able to vote in the United States!&quot;) else: print(&quot;You are not able to vote in the United States.&quot;) </code></pre> <p>The program works as expected as long as the the user enters meaningful data.</p> <pre class="lang-none prettyprint-override"><code>Please enter your age: 23 You are able to vote in the United States! </code></pre> <p>But it fails if the user enters invalid data:</p> <pre class="lang-none prettyprint-override"><code>Please enter your age: dickety six Traceback (most recent call last): File &quot;canyouvote.py&quot;, line 1, in &lt;module&gt; age = int(input(&quot;Please enter your age: &quot;)) ValueError: invalid literal for int() with base 10: 'dickety six' </code></pre> <p>Instead of crashing, I would like the program to ask for the input again. Like this:</p> <pre class="lang-none prettyprint-override"><code>Please enter your age: dickety six Sorry, I didn't understand that. Please enter your age: 26 You are able to vote in the United States! </code></pre> <p>How do I ask for valid input instead of crashing or accepting invalid values (e.g. <code>-1</code>)?</p>
<p>The simplest way to accomplish this is to put the <code>input</code> method in a while loop. Use <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="noreferrer"><code>continue</code></a> when you get bad input, and <code>break</code> out of the loop when you're satisfied.</p> <h2>When Your Input Might Raise an Exception</h2> <p>Use <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="noreferrer"><code>try</code> and <code>except</code></a> to detect when the user enters data that can't be parsed.</p> <pre><code>while True: try: # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: #age was successfully parsed! #we're ready to exit the loop. break if age &gt;= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") </code></pre> <h2>Implementing Your Own Validation Rules</h2> <p>If you want to reject values that Python can successfully parse, you can add your own validation logic.</p> <pre><code>while True: data = input("Please enter a loud message (must be all caps): ") if not data.isupper(): print("Sorry, your response was not loud enough.") continue else: #we're happy with the value given. #we're ready to exit the loop. break while True: data = input("Pick an answer from A to D:") if data.lower() not in ('a', 'b', 'c', 'd'): print("Not an appropriate choice.") else: break </code></pre> <h2>Combining Exception Handling and Custom Validation</h2> <p>Both of the above techniques can be combined into one loop.</p> <pre><code>while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue if age &lt; 0: print("Sorry, your response must not be negative.") continue else: #age was successfully parsed, and we're happy with its value. #we're ready to exit the loop. break if age &gt;= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") </code></pre> <h2>Encapsulating it All in a Function</h2> <p>If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.</p> <pre><code>def get_non_negative_int(prompt): while True: try: value = int(input(prompt)) except ValueError: print("Sorry, I didn't understand that.") continue if value &lt; 0: print("Sorry, your response must not be negative.") continue else: break return value age = get_non_negative_int("Please enter your age: ") kids = get_non_negative_int("Please enter the number of children you have: ") salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ") </code></pre> <h3>Putting It All Together</h3> <p>You can extend this idea to make a very generic input function:</p> <pre><code>def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None): if min_ is not None and max_ is not None and max_ &lt; min_: raise ValueError("min_ must be less than or equal to max_.") while True: ui = input(prompt) if type_ is not None: try: ui = type_(ui) except ValueError: print("Input type must be {0}.".format(type_.__name__)) continue if max_ is not None and ui &gt; max_: print("Input must be less than or equal to {0}.".format(max_)) elif min_ is not None and ui &lt; min_: print("Input must be greater than or equal to {0}.".format(min_)) elif range_ is not None and ui not in range_: if isinstance(range_, range): template = "Input must be between {0.start} and {0.stop}." print(template.format(range_)) else: template = "Input must be {0}." if len(range_) == 1: print(template.format(*range_)) else: expected = " or ".join(( ", ".join(str(x) for x in range_[:-1]), str(range_[-1]) )) print(template.format(expected)) else: return ui </code></pre> <p>With usage such as:</p> <pre><code>age = sanitised_input("Enter your age: ", int, 1, 101) answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd')) </code></pre> <h2>Common Pitfalls, and Why you Should Avoid Them</h2> <h3>The Redundant Use of Redundant <code>input</code> Statements</h3> <p>This method works but is generally considered poor style:</p> <pre><code>data = input("Please enter a loud message (must be all caps): ") while not data.isupper(): print("Sorry, your response was not loud enough.") data = input("Please enter a loud message (must be all caps): ") </code></pre> <p>It might look attractive initially because it's shorter than the <code>while True</code> method, but it violates the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">Don't Repeat Yourself</a> principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing <code>input</code> to <code>raw_input</code>, but accidentally change only the first <code>input</code> above? It's a <code>SyntaxError</code> just waiting to happen.</p> <h3>Recursion Will Blow Your Stack</h3> <p>If you've just learned about recursion, you might be tempted to use it in <code>get_non_negative_int</code> so you can dispose of the while loop.</p> <pre><code>def get_non_negative_int(prompt): try: value = int(input(prompt)) except ValueError: print("Sorry, I didn't understand that.") return get_non_negative_int(prompt) if value &lt; 0: print("Sorry, your response must not be negative.") return get_non_negative_int(prompt) else: return value </code></pre> <p>This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a <code>RuntimeError: maximum recursion depth exceeded</code>. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!</p>
{ "question_id": 23294658, "question_date": "2014-04-25T13:31:47.347Z", "question_score": 716, "tags": "python|validation|input", "answer_id": 23294659, "answer_date": "2014-04-25T13:31:47.347Z", "answer_score": 935 }
Please answer the following Stack Overflow question: Title: Can I set an unlimited length for maxJsonLength in web.config? <p>I am using the autocomplete feature of jQuery. When I try to retrieve the list of more then 17000 records (each won't have more than 10 char length), it's exceeding the length and throws the error:</p> <blockquote> <p>Exception information: <br/> Exception type: InvalidOperationException <br/> Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.</p> </blockquote> <p>Can I set an unlimited length for <code>maxJsonLength</code> in <code>web.config</code>? If not, what is the maximum length I can set?</p>
<p><strong>NOTE:</strong> this answer applies only to Web services, if you are returning JSON from a Controller method, make sure you read this SO answer below as well: <a href="https://stackoverflow.com/questions/1151987/can-i-set-an-unlimited-length-for-maxjsonlength-in-web-config/7207539#7207539">https://stackoverflow.com/a/7207539/1246870</a></p> <hr> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.maxjsonlength.aspx" rel="noreferrer">MaxJsonLength</a> property cannot be unlimited, is an integer property that defaults to 102400 (100k).</p> <p>You can set the <code>MaxJsonLength</code> property on your web.config:</p> <pre><code>&lt;configuration&gt; &lt;system.web.extensions&gt; &lt;scripting&gt; &lt;webServices&gt; &lt;jsonSerialization maxJsonLength="50000000"/&gt; &lt;/webServices&gt; &lt;/scripting&gt; &lt;/system.web.extensions&gt; &lt;/configuration&gt; </code></pre>
{ "question_id": 1151987, "question_date": "2009-07-20T06:38:32.907Z", "question_score": 716, "tags": "asp.net|asp.net-mvc|json", "answer_id": 1151993, "answer_date": "2009-07-20T06:43:01.930Z", "answer_score": 786 }
Please answer the following Stack Overflow question: Title: JavaScript unit test tools for TDD <p>I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?</p>
<h2><a href="http://karma-runner.github.io" rel="nofollow noreferrer">Karma</a> or <a href="http://angular.github.io/protractor/#/" rel="nofollow noreferrer">Protractor</a></h2> <p>Karma is a JavaScript test-runner built with Node.js and meant for unit testing.</p> <p>The Protractor is for end-to-end testing and uses Selenium Web Driver to drive tests.</p> <p>Both have been made by the Angular team. You can use any assertion-library you want with either.</p> <p>Screencast: <a href="http://www.youtube.com/watch?v=MVw8N3hTfCI" rel="nofollow noreferrer">Karma Getting started</a></p> <p><strong>related</strong>:</p> <ul> <li><a href="https://stackoverflow.com/questions/21732379/should-i-be-using-protractor-or-karma-for-my-end-to-end-testing/21733114#21733114">Should I be using Protractor or Karma for my end-to-end testing?</a></li> <li><a href="https://stackoverflow.com/questions/17070522/can-protractor-and-karma-be-used-together">Can Protractor and Karma be used together?</a></li> </ul> <p><strong>pros</strong>:</p> <ul> <li>Uses Node.js, so compatible with Win/OS X/Linux</li> <li>Run tests from a browser or headless with PhantomJS</li> <li>Run on multiple clients at once</li> <li>Option to launch, capture, and automatically shut down browsers</li> <li>Option to run server/clients on development computer or separately</li> <li>Run tests from a command line (can be integrated into ant/maven)</li> <li>Write tests xUnit or BDD style</li> <li>Supports multiple JavaScript test frameworks</li> <li>Auto-run tests on save</li> <li>Proxies requests cross-domain</li> <li>Possible to customize: <ul> <li>Extend it to wrap other test-frameworks (Jasmine, Mocha, QUnit built-in)</li> <li>Your own assertions/refutes</li> <li>Reporters</li> <li>Browser Launchers</li> </ul> </li> <li>Plugin for WebStorm</li> <li>Supported by NetBeans IDE</li> </ul> <p><strong>Cons</strong>:</p> <ul> <li>Does <a href="https://stackoverflow.com/a/16660909/1175496">not support Node.js (i.e. backend)</a> testing</li> <li>No plugin for Eclipse (yet)</li> <li>No history of previous test results</li> </ul> <h1><a href="http://mochajs.org" rel="nofollow noreferrer">mocha.js</a></h1> <p>I'm totally unqualified to comment on mocha.js's features, strengths, and weaknesses, but it was just recommended to me by someone I trust in the JS community.</p> <p>List of features, as reported by its website:</p> <ul> <li>browser support</li> <li>simple async support, including promises</li> <li>test coverage reporting</li> <li>string diff support</li> <li>JavaScript # API for running tests</li> <li>proper exit status for CI support etc</li> <li>auto-detects and disables coloring for non-ttys</li> <li>maps uncaught exceptions to the correct test case</li> <li>async test timeout support</li> <li>test-specific timeouts</li> <li>growl notification support</li> <li>reports test durations</li> <li>highlights slow tests</li> <li>file watcher support</li> <li>global variable leak detection</li> <li>optionally run tests that match a regexp</li> <li>auto-exit to prevent &quot;hanging&quot; with an active loop</li> <li>easily meta-generate suites &amp; test-cases</li> <li>mocha.opts file support</li> <li>clickable suite titles to filter test execution</li> <li>node debugger support</li> <li>detects multiple calls to done()</li> <li>use any assertion library you want</li> <li>extensible reporting, bundled with 9+ reporters</li> <li>extensible test DSLs or &quot;interfaces&quot;</li> <li>before, after, before each, after each hook</li> <li>arbitrary transpiler support (coffee-script etc)</li> <li>TextMate bundle</li> </ul> <h2><a href="http://www.yolpo.com" rel="nofollow noreferrer">yolpo</a></h2> <p><img src="https://i.imgur.com/5HKEWSW.png" alt="yolpo" /></p> <blockquote> <p>This no longer exists, redirects to <a href="https://sequential.js.org" rel="nofollow noreferrer">sequential.js</a> instead</p> </blockquote> <p>Yolpo is a tool to visualize the execution of JavaScript. JavaScript API developers are encouraged to write their use cases to show and tell their API. Such use cases forms the basis of regression tests.</p> <h2><a href="https://github.com/sindresorhus/ava" rel="nofollow noreferrer">AVA</a></h2> <p><a href="https://github.com/sindresorhus/ava" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/43HiK.png" alt="AVA logo" /></a></p> <p>Futuristic test runner with built-in support for ES2015. Even though JavaScript is single-threaded, I/O in Node.js can happen in parallel due to its async nature. AVA takes advantage of this and runs your tests concurrently, which is especially beneficial for I/O heavy tests. In addition, test files are run in parallel as separate processes, giving you even better performance and an isolated environment for each test file.</p> <ul> <li>Minimal and fast</li> <li>Simple test syntax</li> <li>Runs tests concurrently</li> <li>Enforces writing atomic tests</li> <li>No implicit globals</li> <li>Isolated environment for each test file</li> <li>Write your tests in ES2015</li> <li>Promise support</li> <li>Generator function support</li> <li>Async function support</li> <li>Observable support</li> <li>Enhanced asserts</li> <li>Optional TAP o utput</li> <li>Clean stack traces</li> </ul> <h2><a href="http://busterjs.org/" rel="nofollow noreferrer">Buster.js</a></h2> <p>A JavaScript test-runner built with Node.js. Very modular and flexible. It comes with its own assertion library, but you can add your own if you like. The <a href="http://docs.busterjs.org/en/latest/modules/referee/" rel="nofollow noreferrer">assertions library</a> is decoupled, so you can also use it with other test-runners. Instead of using <code>assert(!...)</code> or <code>expect(...).not...</code>, it uses <code>refute(...)</code> which is a nice twist imho.</p> <blockquote> <p>A browser JavaScript testing toolkit. It does browser testing with browser automation (think JsTestDriver), QUnit style static HTML page testing, testing in headless browsers (PhantomJS, jsdom, ...), and more. Take a look at <a href="http://docs.busterjs.org/en/latest/overview/" rel="nofollow noreferrer">the overview</a>!</p> <p>A Node.js testing toolkit. You get the same test case library, assertion library, etc. This is also great for hybrid browser and Node.js code. Write your test case with <code>Buster.JS</code> and run it both in Node.js and in a real browser.</p> </blockquote> <p>Screencast: <a href="http://www.youtube.com/watch?v=VSFGAl1BekY" rel="nofollow noreferrer">Buster.js Getting started</a> (2:45)</p> <p><strong>pros</strong>:</p> <ul> <li>Uses Node.js, so compatible with Win/OS X/Linux</li> <li>Run tests from a browser or headless with PhantomJS (soon)</li> <li>Run on multiple clients at once</li> <li>Supports Node.js testing</li> <li>Don't need to run server/clients on development computer (no need for IE)</li> <li>Run tests from a command line (can be integrated into ant/maven)</li> <li>Write tests xUnit or BDD style</li> <li>Supports multiple JavaScript test frameworks</li> <li>Defer tests instead of commenting them out</li> <li>SinonJS built-in</li> <li><a href="http://www.youtube.com/watch?v=gKVej9SAzH4" rel="nofollow noreferrer">Auto-run tests on save</a></li> <li>Proxies requests cross-domain</li> <li>Possible to customize: <ul> <li>Extend it to wrap other test-frameworks (JsTestDriver built in)</li> <li>Your own assertions/refutes</li> <li>Reporters (xUnit XML, traditional dots, specification, tap, TeamCity and more built-in)</li> <li>Customize/replace the HTML that is used to run the browser-tests</li> </ul> </li> <li>TextMate and Emacs integration</li> </ul> <p><strong>Cons</strong>:</p> <ul> <li>Stil in beta so can be buggy</li> <li>No plugin for Eclipse/IntelliJ (yet)</li> <li>Doesn't group results by os/browser/version like TestSwarm *. It does, however, print out the browser name and version in the test results.</li> <li>No history of previous test results like TestSwarm *</li> <li>Doesn't fully work on windows <a href="http://docs.busterjs.org/en/latest/developers/windows/" rel="nofollow noreferrer">as of May 2014</a></li> </ul> <p>* TestSwarm is also a Continuous Integration server, while you need a separate CI server for <code>Buster.js</code>. It does, however, output xUnit XML reports, so it should be easy to integrate with <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a>, <a href="http://www.atlassian.com/software/bamboo/overview" rel="nofollow noreferrer">Bamboo</a> or other CI servers.</p> <h2><a href="https://github.com/jquery/testswarm/" rel="nofollow noreferrer">TestSwarm</a></h2> <p><a href="https://github.com/jquery/testswarm" rel="nofollow noreferrer">https://github.com/jquery/testswarm</a></p> <p>TestSwarm is officially no longer under active development as stated on their GitHub webpage. They recommend Karma, browserstack-runner, or Intern.</p> <h2><a href="https://github.com/pivotal/jasmine/" rel="nofollow noreferrer">Jasmine</a></h2> <p><img src="https://jasmine.github.io/images/jasmine-purple-horizontal.svg" alt="Jasmine" /></p> <p>This is a behavior-driven framework (as stated in quote below) that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on <a href="http://rspec.info/" rel="nofollow noreferrer">RSpec</a> that are used for testing in Rails projects.</p> <p>Jasmine specs can be run from an HTML page (in qUnit fashion) or from a test runner (as Karma).</p> <blockquote> <p>Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.</p> </blockquote> <p>If you have experience with this testing framework, please contribute with more info :)</p> <p>Project home: <a href="https://github.com/pivotal/jasmine/" rel="nofollow noreferrer">http://jasmine.github.io/</a></p> <h2><a href="http://qunitjs.com/" rel="nofollow noreferrer">QUnit</a></h2> <p>QUnit focuses on testing JavaScript in the browser while providing as much convenience to the developer as possible. Blurb from the site:</p> <blockquote> <p>QUnit is a powerful, easy-to-use JavaScript unit test suite. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code</p> </blockquote> <p>QUnit shares some history with TestSwarm (above):</p> <blockquote> <p>QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone. QUnit's assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.</p> </blockquote> <p>Project home: <a href="http://qunitjs.com/" rel="nofollow noreferrer">http://qunitjs.com/</a></p> <h2><a href="http://sinonjs.org" rel="nofollow noreferrer">Sinon</a></h2> <p>Another great tool is <a href="http://sinonjs.org" rel="nofollow noreferrer">sinon.js</a> by Christian Johansen, the author of <a href="http://tddjs.com/" rel="nofollow noreferrer">Test-Driven JavaScript Development</a>. Best described by himself:</p> <blockquote> <p>Standalone test spies, stubs and mocks for JavaScript. No dependencies works with any unit testing framework.</p> </blockquote> <h2><a href="http://theintern.io" rel="nofollow noreferrer">Intern</a></h2> <p>The <a href="http://theintern.io/#compare" rel="nofollow noreferrer">Intern Web site</a> provides a direct feature comparison to the other testing frameworks on this list. It offers more features out of the box than any other JavaScript-based testing system.</p> <h2><a href="https://jestjs.io/" rel="nofollow noreferrer">JEST</a></h2> <p>A new but yet very powerful testing framework. It allows snapshot based testing as well this increases the testing speed and creates a new dynamic in terms of testing</p> <p>Check out one of their talks: <a href="https://www.youtube.com/watch?v=cAKYQpTC7MA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=cAKYQpTC7MA</a></p> <p>Better yet: <a href="https://jestjs.io/docs/en/getting-started.html" rel="nofollow noreferrer">Getting Started</a></p>
{ "question_id": 300855, "question_date": "2008-11-19T02:35:49.913Z", "question_score": 716, "tags": "javascript|unit-testing|tdd", "answer_id": 680713, "answer_date": "2009-03-25T08:44:55.243Z", "answer_score": 1518 }
Please answer the following Stack Overflow question: Title: How to create a new branch from a tag? <p>I'd like to create a new master branch from an existing tag. Say I have a tag <code>v1.0</code>. How to create a new branch from this tag?</p>
<p>Wow, that was easier than I thought:</p> <pre><code>git checkout -b newbranch v1.0 </code></pre>
{ "question_id": 10940981, "question_date": "2012-06-07T22:55:08.527Z", "question_score": 716, "tags": "git|git-branch|git-tag", "answer_id": 10940996, "answer_date": "2012-06-07T22:57:40.197Z", "answer_score": 1138 }
Please answer the following Stack Overflow question: Title: How do you stop tracking a remote branch in Git? <p>How do you stop tracking a remote branch in <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a>?</p> <p>I am asking to stop tracking because in my concrete case, I want to delete the local branch, but not the remote one. Deleting the local one and pushing the deletion to remote will delete the remote branch as well:</p> <ul> <li><a href="https://stackoverflow.com/q/2003505/367456">How do I delete a Git branch both locally and in GitHub?</a></li> </ul> <p>Can I just do <code>git branch -d the_branch</code>, and it won't get propagated when I later <code>git push</code>? </p> <p>Will it only propagate if I were to run <code>git push origin :the_branch</code> later on?</p>
<p>As mentioned in <a href="https://stackoverflow.com/users/1541707/yoshua-wuyts">Yoshua Wuyts</a>' <a href="https://stackoverflow.com/a/29080220/6309">answer</a>, using <a href="http://git-scm.com/docs/git-branch" rel="noreferrer"><code>git branch</code></a>:</p> <pre><code>git branch --unset-upstream </code></pre> <h3>Other options:</h3> <p>You don't have to delete your local branch.</p> <p>Simply delete the local branch that is tracking the remote branch:</p> <pre><code>git branch -d -r origin/&lt;remote branch name&gt; </code></pre> <p><code>-r, --remotes</code> tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This <a href="https://stackoverflow.com/questions/3046436/how-do-you-stop-tracking-a-remote-branch-in-git/3046478?noredirect=1#comment13741233_3046478">will <em>not</em> delete the branch on the remote repo</a>!</p> <p>See "<a href="https://stackoverflow.com/questions/1070496/having-a-hard-time-understanding-git-fetch">Having a hard time understanding git-fetch</a>"</p> <blockquote> <p>there's no such concept of local tracking branches, only remote tracking branches.<br> So <code>origin/master</code> is a remote tracking branch for <code>master</code> in the <code>origin</code> repo</p> </blockquote> <p>As mentioned in <a href="https://stackoverflow.com/users/399738/dobes-vandermeer">Dobes Vandermeer</a>'s <a href="https://stackoverflow.com/a/3376017/6309">answer</a>, you also need to reset the configuration associated to the <em>local</em> branch:</p> <pre><code>git config --unset branch.&lt;branch&gt;.remote git config --unset branch.&lt;branch&gt;.merge </code></pre> <blockquote> <p>Remove the upstream information for <code>&lt;branchname&gt;</code>.<br> If no branch is specified it defaults to the current branch.</p> </blockquote> <p>(git 1.8+, Oct. 2012, <a href="https://github.com/git/git/commit/b84869ef14081b298a4ab825219221ccfcb2a3ba" rel="noreferrer">commit b84869e</a> by <a href="https://github.com/carlosmn" rel="noreferrer">Carlos Martín Nieto (<code>carlosmn</code>)</a>)</p> <p>That will make any push/pull completely unaware of <code>origin/&lt;remote branch name&gt;</code>.</p>
{ "question_id": 3046436, "question_date": "2010-06-15T15:06:32.893Z", "question_score": 716, "tags": "git|branch|git-track", "answer_id": 3046478, "answer_date": "2010-06-15T15:11:39.713Z", "answer_score": 977 }
Please answer the following Stack Overflow question: Title: @class vs. #import <p>It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an <code>#import</code> is a simple <code>ifndef</code> so that an include only happens once.</p> <p>My inquiry is this: When does one use <code>#import</code> and when does one use <code>@class</code>? Sometimes if I use a <code>@class</code> declaration, I see a common compiler warning such as the following:</p> <blockquote> <p><code>warning: receiver 'FooController' is a forward class and corresponding @interface may not exist.</code></p> </blockquote> <p>Would really love to understand this, versus just removing the <code>@class</code> forward-declaration and throwing an <code>#import</code> in to silence the warnings the compiler is giving me.</p>
<p>If you see this warning:</p> <blockquote> <p>warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist</p> </blockquote> <p>you need to <code>#import</code> the file, but you can do that in your implementation file (.m), and use the <code>@class</code> declaration in your header file. </p> <p><code>@class</code> does not (usually) remove the need to <code>#import</code> files, it just moves the requirement down closer to where the information is useful. </p> <p><strong>For Example</strong></p> <p>If you say <code>@class MyCoolClass</code>, the compiler knows that it may see something like:</p> <pre><code>MyCoolClass *myObject; </code></pre> <p>It doesn't have to worry about anything other than <code>MyCoolClass</code> is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, <code>@class</code> suffices 90% of the time.</p> <p>However, if you ever need to create or access <code>myObject</code>'s members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to <code>#import "MyCoolClass.h"</code>, to tell the compiler additional information beyond just "this is a class".</p>
{ "question_id": 322597, "question_date": "2008-11-27T00:20:17.140Z", "question_score": 716, "tags": "objective-c|cocoa|cocoa-touch", "answer_id": 322627, "answer_date": "2008-11-27T00:33:10.813Z", "answer_score": 758 }
Please answer the following Stack Overflow question: Title: No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? <p>I'm compiling a project in Eclipse using m2eclipse. I set the JDK path in Eclipse like this:</p> <pre><code>Windows--&gt;preferences--&gt;installed jres--&gt; jdk1.7.xx path </code></pre> <p>But this is showing an error</p> <pre><code>[ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? [INFO] 1 error [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.424s [INFO] Finished at: Tue Oct 29 15:21:01 IST 2013 [INFO] Final Memory: 5M/15M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler- plugin:3.1:compile (default-compile) on project TEST-WEB: Compilation failure [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? </code></pre>
<ol> <li>On your Eclipse IDE, go into <strong><em>Window</em></strong> > <strong><em>Preferences</em></strong> > <strong><em>Java</em></strong> > <strong><em>Installed JREs</em></strong> > and check your <strong><em>installed JREs</em></strong>. You should have an entry with a JDK there. </li> <li>Select the Execution Env as show below. Click <strong><em>OK</em></strong></li> <li>Then <strong><em>Right-Click</em></strong> on your Project -> <strong><em>Maven</em></strong> -> <strong><em>Update Project</em></strong></li> </ol> <p>Additionally, you may have to change Maven JRE (see @jlars62 answer) which is as follows. Goto Run -> Run Configurations, selecting the Maven Build I was running (from the left panel). Then, I clicked the JRE tab and selected the option Workspace default JRE</p> <p><a href="https://i.stack.imgur.com/KEU8N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KEU8N.png" alt="enter image description here"></a></p>
{ "question_id": 19655184, "question_date": "2013-10-29T10:11:50.420Z", "question_score": 715, "tags": "java|eclipse|maven|java-7|m2eclipse", "answer_id": 21279068, "answer_date": "2014-01-22T09:34:38.673Z", "answer_score": 1085 }
Please answer the following Stack Overflow question: Title: Google Maps JS API v3 - Simple Multiple Marker Example <p>Fairly new to the Google Maps Api. I've got an array of data that I want to cycle through and plot on a map. Seems fairly simple, but all the multi-marker tutorials I have found are quite complex.</p> <p>Let's use the data array from Google's site for an example:</p> <pre><code>var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; </code></pre> <p>I simply want to plot all of these points and have an <code>infoWindow</code> pop up when clicked to display the name.</p>
<p>This is the simplest I could reduce it to:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt; &lt;title&gt;Google Maps Multiple Markers&lt;/title&gt; &lt;script src=&quot;http://maps.google.com/maps/api/js?key=YOUR_API_KEY&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;map&quot; style=&quot;width: 500px; height: 400px;&quot;&gt;&lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt; var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i &lt; locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <blockquote> <p>‍ <a href="https://codepen.io/ahmadawais/pen/NQdWQx?editors=1010" rel="noreferrer">Edit/fork on a Codepen →</a></p> </blockquote> <p><strong>SCREENSHOT</strong></p> <p><img src="https://i.imgur.com/mM82YXg.png" alt="Google Maps Multiple Markers" /></p> <p>There is some closure magic happening when passing the callback argument to the <code>addListener</code> method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:</p> <p>❯ <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Closures" rel="noreferrer">Mozilla Dev Center: Working with Closures</a></p>
{ "question_id": 3059044, "question_date": "2010-06-17T05:14:33.957Z", "question_score": 714, "tags": "javascript|google-maps|google-maps-api-3", "answer_id": 3059129, "answer_date": "2010-06-17T05:36:38.610Z", "answer_score": 1206 }
Please answer the following Stack Overflow question: Title: How do I clone a generic list in C#? <p>I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do <code>list.Clone()</code>.</p> <p>Is there an easy way around this?</p>
<p>You can use an extension method.</p> <pre><code>static class Extensions { public static IList&lt;T&gt; Clone&lt;T&gt;(this IList&lt;T&gt; listToClone) where T: ICloneable { return listToClone.Select(item =&gt; (T)item.Clone()).ToList(); } } </code></pre>
{ "question_id": 222598, "question_date": "2008-10-21T16:47:05.823Z", "question_score": 714, "tags": "c#|generics|list|clone", "answer_id": 222640, "answer_date": "2008-10-21T16:58:54.363Z", "answer_score": 441 }
Please answer the following Stack Overflow question: Title: Formatting a number with leading zeros in PHP <p>I have a variable which contains the value <code>1234567</code>.</p> <p>I would like it to contain exactly 8 digits, i.e. <code>01234567</code>.</p> <p>Is there a PHP function for that?</p>
<p>Use <a href="http://fi2.php.net/manual/en/function.sprintf.php" rel="noreferrer"><code>sprintf</code></a> :</p> <pre><code>sprintf('%08d', 1234567); </code></pre> <p>Alternatively you can also use <a href="http://www.php.net/manual/en/function.str-pad.php" rel="noreferrer"><code>str_pad</code></a>:</p> <pre><code>str_pad($value, 8, '0', STR_PAD_LEFT); </code></pre>
{ "question_id": 1699958, "question_date": "2009-11-09T09:25:01.553Z", "question_score": 714, "tags": "php|numbers|format", "answer_id": 1699980, "answer_date": "2009-11-09T09:29:03.203Z", "answer_score": 1422 }
Please answer the following Stack Overflow question: Title: How do I remove packages installed with Python's easy_install? <p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
<p><a href="http://pypi.python.org/pypi/pip/" rel="noreferrer">pip</a>, an alternative to setuptools/easy_install, provides an "uninstall" command. </p> <p>Install pip according to the <a href="http://pip.readthedocs.org/en/stable/installing/" rel="noreferrer">installation instructions</a>:</p> <pre><code>$ wget https://bootstrap.pypa.io/get-pip.py $ python get-pip.py </code></pre> <p>Then you can use <code>pip uninstall</code> to remove packages installed with <code>easy_install</code></p>
{ "question_id": 1231688, "question_date": "2009-08-05T07:33:13.900Z", "question_score": 714, "tags": "python|package|setuptools|easy-install", "answer_id": 3297564, "answer_date": "2010-07-21T08:47:21.617Z", "answer_score": 622 }
Please answer the following Stack Overflow question: Title: Can you get the number of lines of code from a GitHub repository? <p>In a GitHub repository you can see “language statistics”, which displays the <em>percentage</em> of the project that’s written in a language. It doesn’t, however, display how many lines of code the project consists of. Often, I want to quickly get an impression of the scale and complexity of a project, and the count of lines of code can give a good first impression. 500 lines of code implies a relatively simple project, 100,000 lines of code implies a very large/complicated project.</p> <p>So, is it possible to get the lines of code written in the various languages from a GitHub repository, preferably without cloning it?</p> <hr> <p>The question “<a href="https://stackoverflow.com/q/4822471/388916">Count number of lines in a git repository</a>” asks how to count the lines of code in a local Git repository, but:</p> <ol> <li>You have to clone the project, which could be massive. Cloning a project like Wine, for example, takes ages.</li> <li>You would count lines in files that wouldn’t necessarily be code, like i13n files.</li> <li>If you count <em>just</em> (for example) Ruby files, you’d potentially miss massive amount of code in other languages, like JavaScript. You’d have to know beforehand which languages the project uses. You’d also have to repeat the count for every language the project uses.</li> </ol> <p>All in all, this is potentially far too time-intensive for “quickly checking the scale of a project”.</p>
<h3>Not currently possible on Github.com or their API-s</h3> <p>I have talked to customer support and confirmed that this can not be done on github.com. They have passed the suggestion along to the Github team though, so hopefully it will be possible in the future. If so, I'll be sure to edit this answer.</p> <p>Meanwhile, <a href="https://stackoverflow.com/a/29012789/388916">Rory O'Kane's answer</a> is a brilliant alternative based on <code>cloc</code> and a shallow repo clone.</p>
{ "question_id": 26881441, "question_date": "2014-11-12T07:26:48.293Z", "question_score": 714, "tags": "github|line-count", "answer_id": 26929074, "answer_date": "2014-11-14T11:34:36.213Z", "answer_score": 44 }
Please answer the following Stack Overflow question: Title: Is there a portable way to get the current username in Python? <p>What is a portable way (e.g. for Linux and Windows) to get the current user's username? Something similar to <code>os.getuid()</code> would be nice:</p> <pre><code>&gt;&gt;&gt; os.getuid() 42 &gt;&gt;&gt; os.getusername() 'slartibartfast' </code></pre> <p>The <a href="https://docs.python.org/3/library/pwd.html" rel="noreferrer"><code>pwd</code></a> module works for Unix only. Some people suggest that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service).</p>
<p>Look at <a href="http://docs.python.org/library/getpass.html" rel="noreferrer"><code>getpass</code></a> module</p> <pre><code>import getpass getpass.getuser() 'kostya' </code></pre> <p>Availability: Unix, Windows</p> <hr /> <p>p.s. Per comment below &quot;<em>this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other).</em>&quot;</p>
{ "question_id": 842059, "question_date": "2009-05-08T22:20:20.120Z", "question_score": 714, "tags": "python|portability", "answer_id": 842096, "answer_date": "2009-05-08T22:30:51.030Z", "answer_score": 1011 }
Please answer the following Stack Overflow question: Title: How do I get cURL to not show the progress bar? <p>I'm trying to use cURL in a script and get it to <strong><em>not</em></strong> show the progress bar. </p> <p>I've tried the <code>-s</code>, <code>-silent</code>, <code>-S</code>, and <code>-quiet</code> options, but none of them work.</p> <p>Here's a typical command I've tried:</p> <pre><code>curl -s http://google.com &gt; temp.html </code></pre> <p>I only get the progress bar when pushing it to a file, so <code>curl -s http://google.com</code> doesn't have a progress bar, but <code>curl -s http://google.com &gt; temp.html</code> does.</p>
<pre><code>curl -s http://google.com &gt; temp.html </code></pre> <p>works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:</p> <pre><code>curl http://google.com 2&gt;/dev/null &gt; temp.html </code></pre>
{ "question_id": 7373752, "question_date": "2011-09-10T18:30:50.083Z", "question_score": 714, "tags": "linux|bash|unix|scripting|curl", "answer_id": 7373922, "answer_date": "2011-09-10T19:04:05.093Z", "answer_score": 690 }
Please answer the following Stack Overflow question: Title: Sqlite primary key on multiple columns <p>What is the syntax for specifying a primary key on more than 1 column in SQLITE ? </p>
<p>According to the <a href="http://www.sqlite.org/lang_createtable.html" rel="noreferrer">documentation</a>, it's</p> <pre><code>CREATE TABLE something ( column1, column2, column3, PRIMARY KEY (column1, column2) ); </code></pre>
{ "question_id": 734689, "question_date": "2009-04-09T15:17:31.807Z", "question_score": 714, "tags": "sqlite|primary-key|ddl|composite-primary-key", "answer_id": 734704, "answer_date": "2009-04-09T15:21:34.683Z", "answer_score": 925 }
Please answer the following Stack Overflow question: Title: zsh compinit: insecure directories <p>What does it mean and how can I fix it?</p> <pre><code>zsh compinit: insecure directories, run compaudit for list. Ignore insecure directories and continue [y] or abort compinit [n]? </code></pre> <p>Running the <code>compaudit</code> returns the follows:</p> <pre><code>There are insecure directories: /usr/local/share/zsh/site-functions </code></pre>
<p><strong>Note:</strong> This answer is from 2012.</p> <hr /> <p>This fixed it for me:</p> <pre><code>$ sudo chmod -R 755 /usr/local/share/zsh/site-functions </code></pre> <p>Credit: <a href="http://www.zsh.org/mla/users/2008/msg00566.html" rel="noreferrer">a post on zsh mailing list</a></p> <hr /> <p><strong>EDIT:</strong> As pointed out by @biocyberman in the comments. You may need to update the owner of <code>site-functions</code> as well:</p> <pre><code>$ sudo chown -R root:root /usr/local/share/zsh/site-functions </code></pre> <p>On my machine (OSX 10.9), I do not need to do this but YMMV.</p> <p><strong>EDIT2:</strong> On OSX 10.11, only this worked:</p> <pre><code>$ sudo chmod -R 755 /usr/local/share/zsh $ sudo chown -R root:staff /usr/local/share/zsh </code></pre> <p>Also user:staff is the correct default permission on OSX.</p>
{ "question_id": 13762280, "question_date": "2012-12-07T11:34:43.870Z", "question_score": 714, "tags": "zsh|zsh-completion", "answer_id": 13785716, "answer_date": "2012-12-09T08:07:40.343Z", "answer_score": 910 }
Please answer the following Stack Overflow question: Title: Create list of single item repeated N times <p>I want to create a series of lists, all of varying lengths. Each list will contain the same element <code>e</code>, repeated <code>n</code> times (where <code>n</code> = length of the list).</p> <p>How do I create the lists, without using a list comprehension <code>[e for number in xrange(n)]</code> for each list?</p>
<p>You can also write:</p> <pre class="lang-py prettyprint-override"><code>[e] * n </code></pre> <p>You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.</p> <p><strong>Performance testing</strong></p> <p>At first glance it <em>seems</em> that repeat is the fastest way to create a list with n identical elements:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000) 0.37095273281943264 &gt;&gt;&gt; timeit.timeit('[0] * 10', 'import itertools', number = 1000000) 0.5577236771712819 </code></pre> <p>But wait - it's not a fair test...</p> <pre><code>&gt;&gt;&gt; itertools.repeat(0, 10) repeat(0, 10) # Not a list!!! </code></pre> <p>The function <code>itertools.repeat</code> doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000) 1.7508119747063233 </code></pre> <p>So if you want a list, use <code>[e] * n</code>. If you want to generate the elements lazily, use <code>repeat</code>.</p>
{ "question_id": 3459098, "question_date": "2010-08-11T14:01:33.550Z", "question_score": 713, "tags": "python|list-comprehension|multiplication|replicate", "answer_id": 3459131, "answer_date": "2010-08-11T14:04:53.087Z", "answer_score": 1053 }
Please answer the following Stack Overflow question: Title: Can an abstract class have a constructor? <p>Can an abstract class have a constructor?</p> <p>If so, how can it be used and for what purposes?</p>
<p>Yes, an abstract class can have a constructor. Consider this:</p> <pre><code>abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } } </code></pre> <p>The superclass <code>Product</code> is abstract and has a constructor. The concrete class <code>TimesTwo</code> has a constructor that just hardcodes the value 2. The concrete class <code>TimesWhat</code> has a constructor that allows the caller to specify the value.</p> <p>Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.</p> <blockquote> <p>NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.</p> </blockquote>
{ "question_id": 260666, "question_date": "2008-11-04T02:46:21.807Z", "question_score": 713, "tags": "java|constructor|abstract-class", "answer_id": 260755, "answer_date": "2008-11-04T03:19:37.777Z", "answer_score": 730 }
Please answer the following Stack Overflow question: Title: How can I do string interpolation in JavaScript? <p>Consider this code:</p> <pre><code>var age = 3; console.log("I'm " + age + " years old!"); </code></pre> <p>Are there any other ways to insert the value of a variable in to a string, apart from string concatenation?</p>
<p>Since ES6, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="noreferrer">template literals</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-js lang-js prettyprint-override"><code>const age = 3 console.log(`I'm ${age} years old!`)</code></pre> </div> </div> </p> <p><strong>P.S.</strong> Note the use of backticks: <code>``</code>.</p>
{ "question_id": 1408289, "question_date": "2009-09-10T23:40:11.223Z", "question_score": 713, "tags": "javascript|string|string-interpolation", "answer_id": 35984254, "answer_date": "2016-03-14T09:52:21.037Z", "answer_score": 810 }
Please answer the following Stack Overflow question: Title: Interop type cannot be embedded <p>I am creating a web application on the .NET 4.0 framework (beta2) in C#.</p> <p>When I try to use a assembly called "ActiveHomeScriptLib", I get the following error:</p> <blockquote> <p>Interop type 'ActiveHomeScriptLib.ActiveHomeClass' cannot be embedded. Use the applicable interface instead.</p> </blockquote> <p>When I change the framework to version 3.5, I don't have any errors.</p> <p>What is an Interop Type and why does this only occur when I use the 4.0 framework?</p>
<p>.NET 4.0 allows primary interop assemblies (or rather, the bits of it that you need) to be embedded into your assembly so that you don't need to deploy them alongside your application.</p> <p>For whatever reason, this assembly can't be embedded - but it sounds like that's not a problem for you. Just open the Properties tab for the assembly in Visual Studio 2010 and set "Embed Interop Types" to "False".</p> <p>EDIT: See also Michael Gustus's <a href="https://stackoverflow.com/a/4553402/641833">answer</a>, removing the <code>Class</code> suffix from the types you're using.</p>
{ "question_id": 2483659, "question_date": "2010-03-20T15:47:01.217Z", "question_score": 713, "tags": "c#|visual-studio-2010|visual-studio|c#-4.0", "answer_id": 2483688, "answer_date": "2010-03-20T15:54:14.687Z", "answer_score": 1146 }
Please answer the following Stack Overflow question: Title: postgres: upgrade a user to be a superuser? <p>In postgres, how do I change an existing user to be a superuser? I don't want to delete the existing user, for various reasons. </p> <pre><code># alter user myuser ...? </code></pre>
<pre><code>ALTER USER myuser WITH SUPERUSER; </code></pre> <p>You can read more at the <a href="http://www.postgresql.org/docs/current/static/sql-alteruser.html" rel="noreferrer">Documentation</a></p>
{ "question_id": 10757431, "question_date": "2012-05-25T15:43:18.613Z", "question_score": 713, "tags": "sql|postgresql", "answer_id": 10757486, "answer_date": "2012-05-25T15:46:25.913Z", "answer_score": 1374 }
Please answer the following Stack Overflow question: Title: Show a number to two decimal places <p>What's the correct way to round a PHP string to two decimal places?</p> <pre><code>$number = "520"; // It's a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number; </code></pre> <p>The output should be <code>520.00</code>;</p> <p>How should the <code>round_to_2dp()</code> function definition be?</p>
<p>You can use <a href="http://php.net/number_format">number_format()</a>:</p> <pre><code>return number_format((float)$number, 2, '.', ''); </code></pre> <p>Example:</p> <pre><code>$foo = "105"; echo number_format((float)$foo, 2, '.', ''); // Outputs -&gt; 105.00 </code></pre> <p>This function returns a <strong>string</strong>.</p>
{ "question_id": 4483540, "question_date": "2010-12-19T15:10:30.473Z", "question_score": 712, "tags": "php|formatting|numbers|rounding|number-formatting", "answer_id": 4483561, "answer_date": "2010-12-19T15:14:12.323Z", "answer_score": 1381 }
Please answer the following Stack Overflow question: Title: Split string with multiple delimiters in Python <p>I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here.</p> <p>I have a string that needs to be split by either a ';' or ', ' That is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouched</p> <p>Example string:</p> <pre><code>"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]" </code></pre> <p>should be split into a list containing the following:</p> <pre><code>('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') </code></pre>
<p>Luckily, Python has this built-in :)</p> <pre><code>import re re.split('; |, ', string_to_split) </code></pre> <p><strong>Update:</strong><br>Following your comment:</p> <pre><code>&gt;&gt;&gt; a='Beautiful, is; better*than\nugly' &gt;&gt;&gt; import re &gt;&gt;&gt; re.split('; |, |\*|\n',a) ['Beautiful', 'is', 'better', 'than', 'ugly'] </code></pre>
{ "question_id": 4998629, "question_date": "2011-02-14T23:42:13.300Z", "question_score": 712, "tags": "python|string|split|delimiter", "answer_id": 4998688, "answer_date": "2011-02-14T23:52:24.837Z", "answer_score": 1152 }
Please answer the following Stack Overflow question: Title: Get top 1 row of each group <p>I have a table which I want to get the latest entry for each group. Here's the table:</p> <p><code>DocumentStatusLogs</code> Table</p> <pre><code>|ID| DocumentID | Status | DateCreated | | 2| 1 | S1 | 7/29/2011 | | 3| 1 | S2 | 7/30/2011 | | 6| 1 | S1 | 8/02/2011 | | 1| 2 | S1 | 7/28/2011 | | 4| 2 | S2 | 7/30/2011 | | 5| 2 | S3 | 8/01/2011 | | 6| 3 | S1 | 8/02/2011 | </code></pre> <p>The table will be grouped by <code>DocumentID</code> and sorted by <code>DateCreated</code> in descending order. For each <code>DocumentID</code>, I want to get the latest status. </p> <p>My preferred output:</p> <pre><code>| DocumentID | Status | DateCreated | | 1 | S1 | 8/02/2011 | | 2 | S3 | 8/01/2011 | | 3 | S1 | 8/02/2011 | </code></pre> <ul> <li><p>Is there any aggregate function to get only the top from each group? See pseudo-code <code>GetOnlyTheTop</code> below:</p> <pre><code>SELECT DocumentID, GetOnlyTheTop(Status), GetOnlyTheTop(DateCreated) FROM DocumentStatusLogs GROUP BY DocumentID ORDER BY DateCreated DESC </code></pre></li> <li><p>If such function doesn't exist, is there any way I can achieve the output I want?</p></li> <li>Or at the first place, could this be caused by unnormalized database? I'm thinking, since what I'm looking for is just one row, should that <code>status</code> also be located in the parent table?</li> </ul> <p>Please see the parent table for more information:</p> <p>Current <code>Documents</code> Table</p> <pre><code>| DocumentID | Title | Content | DateCreated | | 1 | TitleA | ... | ... | | 2 | TitleB | ... | ... | | 3 | TitleC | ... | ... | </code></pre> <p>Should the parent table be like this so that I can easily access its status?</p> <pre><code>| DocumentID | Title | Content | DateCreated | CurrentStatus | | 1 | TitleA | ... | ... | s1 | | 2 | TitleB | ... | ... | s3 | | 3 | TitleC | ... | ... | s1 | </code></pre> <p><strong>UPDATE</strong> I just learned how to use "apply" which makes it easier to address such problems.</p>
<pre><code>;WITH cte AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC) AS rn FROM DocumentStatusLogs ) SELECT * FROM cte WHERE rn = 1 </code></pre> <p>If you expect 2 entries per day, then this will arbitrarily pick one. To get both entries for a day, use DENSE_RANK instead</p> <p>As for normalised or not, it depends if you want to:</p> <ul> <li>maintain status in 2 places</li> <li>preserve status history</li> <li>...</li> </ul> <p>As it stands, you preserve status history. If you want latest status in the parent table too (which is denormalisation) you'd need a trigger to maintain "status" in the parent. or drop this status history table.</p>
{ "question_id": 6841605, "question_date": "2011-07-27T08:41:16.790Z", "question_score": 712, "tags": "sql|sql-server|tsql|sql-server-2005|greatest-n-per-group", "answer_id": 6841644, "answer_date": "2011-07-27T08:44:10.200Z", "answer_score": 900 }
Please answer the following Stack Overflow question: Title: How can I represent an infinite number in Python? <p>How can I represent an infinite number in python? No matter which number you enter in the program, no number should be greater than this representation of infinity.</p>
<p>In Python, you can do:</p> <pre><code>test = float("inf") </code></pre> <p>In Python 3.5, you can do:</p> <pre><code>import math test = math.inf </code></pre> <p>And then:</p> <pre><code>test &gt; 1 test &gt; 10000 test &gt; x </code></pre> <p>Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").</p> <p>Additionally (Python 2.x ONLY), in a comparison to <code>Ellipsis</code>, <code>float(inf)</code> is lesser, e.g:</p> <pre><code>float('inf') &lt; Ellipsis </code></pre> <p>would return true.</p>
{ "question_id": 7781260, "question_date": "2011-10-15T23:06:22.687Z", "question_score": 712, "tags": "python|infinite|infinity", "answer_id": 7781273, "answer_date": "2011-10-15T23:09:43.343Z", "answer_score": 864 }
Please answer the following Stack Overflow question: Title: Get root view from current activity <p>I know how to get the root view with <a href="http://developer.android.com/reference/android/view/View.html#getRootView%28%29">View.getRootView()</a>. I am also able to get the view from a button's <code>onClick</code> event where the argument is a <a href="http://developer.android.com/reference/android/view/View.html">View</a>. But how can I get the <strong>view</strong> in an <a href="http://developer.android.com/reference/android/app/Activity.html">activity</a>?</p>
<p>If you need root view of your activity (so you can add your contents there) use</p> <pre><code>findViewById(android.R.id.content).getRootView() </code></pre> <p>Also it was reported that on some devices you have to use </p> <pre><code>getWindow().getDecorView().findViewById(android.R.id.content) </code></pre> <p>instead.</p> <p>Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).</p> <p>If you need to get view that you added to your activity using <code>setContentView()</code> method then as pottedmeat wrote you can use</p> <pre><code>final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this .findViewById(android.R.id.content)).getChildAt(0); </code></pre> <p>But better just set id to this view in your xml layout and use this id instead.</p>
{ "question_id": 4486034, "question_date": "2010-12-20T00:40:33.510Z", "question_score": 712, "tags": "android|android-activity|view", "answer_id": 4488149, "answer_date": "2010-12-20T08:58:01.023Z", "answer_score": 1155 }
Please answer the following Stack Overflow question: Title: Error: request entity too large <p>I'm receiving the following error with express:</p> <pre><code>Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/json.js:60:5) at Object.bodyParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:53:5) at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15) at Object.cookieParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5) at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15) at Object.logger (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/logger.js:158:5) at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15) at Object.staticMiddleware [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61) at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15) TypeError: /Users/michaeljames/Documents/Projects/Proj/mean/app/views/includes/foot.jade:31 29| script(type="text/javascript", src="/js/socketio/connect.js") 30| &gt; 31| if (req.host='localhost') 32| //Livereload script rendered 33| script(type='text/javascript', src='http://localhost:35729/livereload.js') 34| Cannot set property 'host' of undefined at eval (eval at &lt;anonymous&gt; (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:152:8), &lt;anonymous&gt;:273:15) at /Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:153:35 at Object.exports.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:197:10) at Object.exports.renderFile (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:233:18) at View.exports.renderFile [as engine] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:218:21) at View.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/view.js:76:8) at Function.app.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/application.js:504:10) at ServerResponse.res.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/response.js:801:7) at Object.handle (/Users/michaeljames/Documents/Projects/Proj/mean/config/express.js:82:29) at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:188:17) POST /api/0.1/people 500 618ms </code></pre> <p>I am using meanstack. I have the following use statements in my express.js</p> <pre><code>//Set Request Size Limit app.use(express.limit(100000000)); </code></pre> <p>Within fiddler I can see the content-length header with a value of: 1078702</p> <p>I believe this is in octets, this is 1.0787 megabytes.</p> <p>I have no idea why express is not letting me post the json array I was posting previously in another express project that was not using the mean stack project structure.</p>
<p>I had the same error recently, and all the solutions I've found did not work.</p> <p>After some digging, I found that setting <code>app.use(express.bodyParser({limit: '50mb'}));</code> did set the limit correctly. </p> <p>When adding a <code>console.log('Limit file size: '+limit);</code> in <code>node_modules/express/node_modules/connect/lib/middleware/json.js:46</code> and restarting node, I get this output in the console: </p> <pre class="lang-none prettyprint-override"><code>Limit file size: 1048576 connect.multipart() will be removed in connect 3.0 visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives connect.limit() will be removed in connect 3.0 Limit file size: 52428800 Express server listening on port 3002 </code></pre> <p>We can see that at first, when loading the <code>connect</code> module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the <code>console.log</code> is called again and this time the limit is 52428800 (50mb). However, I still get a <code>413 Request entity too large</code>.</p> <p>Then I added <code>console.log('Limit file size: '+limit);</code> in <code>node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10</code> and saw another line in the console when calling the route with a big request (before the error output) : </p> <pre class="lang-none prettyprint-override"><code>Limit file size: 1048576 </code></pre> <p>This means that somehow, somewhere, <code>connect</code> resets the limit parameter and ignores what we specified. I tried specifying the <code>bodyParser</code> parameters in the route definition individually, but no luck either.</p> <p>While I did not find any proper way to set it permanently, you can "<em>patch</em>" it in the module directly. If you are using Express 3.4.4, add this at line 46 of <code>node_modules/express/node_modules/connect/lib/middleware/json.js</code> :</p> <pre class="lang-js prettyprint-override"><code>limit = 52428800; // for 50mb, this corresponds to the size in bytes </code></pre> <p>The line number might differ if you don't run the same version of Express. Please note that this is <strong>bad practice</strong> and it will be <strong>overwritten</strong> if you update your module.</p> <p>So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.</p> <p>I have opened <a href="https://github.com/visionmedia/express/issues/1815" rel="noreferrer">an issue on their GitHub</a> about this problem.</p> <p><strong>[edit - found the solution]</strong></p> <p>After some research and testing, I found that when debugging, I added <code>app.use(express.bodyParser({limit: '50mb'}));</code>, but <strong>after</strong> <code>app.use(express.json());</code>. Express would then set the global limit to 1mb because the first parser he encountered when running the script was <code>express.json()</code>. Moving <code>bodyParser</code> above it did the trick.</p> <p>That said, the <code>bodyParser()</code> method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :</p> <pre class="lang-js prettyprint-override"><code>app.use(express.json({limit: '50mb'})); app.use(express.urlencoded({limit: '50mb'})); </code></pre> <p>In case you need multipart (for file uploads) see <a href="https://groups.google.com/forum/#!msg/express-js/iP2VyhkypHo/5AXQiYN3RPcJ" rel="noreferrer">this post</a>.</p> <p><strong>[second edit]</strong></p> <p>Note that in Express 4, instead of <code>express.json()</code> and <code>express.urlencoded()</code>, you must require the <a href="https://github.com/expressjs/body-parser" rel="noreferrer">body-parser</a> module and use its <code>json()</code> and <code>urlencoded()</code> methods, like so:</p> <pre class="lang-js prettyprint-override"><code>var bodyParser = require('body-parser'); app.use(bodyParser.json({limit: '50mb'})); app.use(bodyParser.urlencoded({limit: '50mb', extended: true})); </code></pre> <p>If the <code>extended</code> option is not explicitly defined for <code>bodyParser.urlencoded()</code>, it will throw a warning (<code>body-parser deprecated undefined extended: provide extended option</code>). This is because this option will be required in the next version and will <strong>not</strong> be optional anymore. For more info on the <code>extended</code> option, you can refer to the <a href="https://github.com/expressjs/body-parser#extended" rel="noreferrer">readme</a> of <code>body-parser</code>.</p> <p><strong>[third edit]</strong></p> <p>It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):</p> <pre><code>app.use(express.json({limit: '50mb'})); app.use(express.urlencoded({limit: '50mb'})); </code></pre>
{ "question_id": 19917401, "question_date": "2013-11-11T22:40:25.923Z", "question_score": 712, "tags": "javascript|node.js|http|express", "answer_id": 19965089, "answer_date": "2013-11-13T21:48:58.507Z", "answer_score": 1406 }
Please answer the following Stack Overflow question: Title: Print a file, skipping the first X lines, in Bash <p>I have a very long file which I want to print, skipping the first 1,000,000 lines, for example.</p> <p>I looked into the cat man page, but I did not see any option to do this. I am looking for a command to do this or a simple Bash program.</p>
<p>You'll need tail. Some examples: </p> <pre><code>$ tail great-big-file.log &lt; Last 10 lines of great-big-file.log &gt; </code></pre> <p>If you really need to SKIP a particular number of "first" lines, use</p> <pre><code>$ tail -n +&lt;N+1&gt; &lt;filename&gt; &lt; filename, excluding first N lines. &gt; </code></pre> <p>That is, if you want to skip N lines, you start printing line N+1. Example:</p> <pre><code>$ tail -n +11 /tmp/myfile &lt; /tmp/myfile, starting at line 11, or skipping the first 10 lines. &gt; </code></pre> <p>If you want to just see the last so many lines, omit the "+":</p> <pre><code>$ tail -n &lt;N&gt; &lt;filename&gt; &lt; last N lines of file. &gt; </code></pre>
{ "question_id": 604864, "question_date": "2009-03-03T02:19:54.090Z", "question_score": 712, "tags": "linux|bash|printing|skip", "answer_id": 604871, "answer_date": "2009-03-03T02:24:05.813Z", "answer_score": 1156 }
Please answer the following Stack Overflow question: Title: How can I see normal print output created during pytest run? <p>Sometimes I want to just insert some print statements in my code, and see what gets printed out when I exercise it. My usual way to "exercise" it is with existing pytest tests. But when I run these, I don't seem able to see any standard output (at least from within PyCharm, my IDE).</p> <p>Is there a simple way to see standard output during a pytest run?</p>
<p>The <a href="https://docs.pytest.org/en/latest/capture.html#setting-capturing-methods-or-disabling-capturing" rel="noreferrer"><code>-s</code> switch</a> disables per-test capturing (only if a test fails).</p> <p><code>-s</code> is equivalent to <code>--capture=no</code>.</p>
{ "question_id": 14405063, "question_date": "2013-01-18T18:14:38.833Z", "question_score": 712, "tags": "python|logging|pytest", "answer_id": 14414325, "answer_date": "2013-01-19T12:22:57.527Z", "answer_score": 894 }
Please answer the following Stack Overflow question: Title: Shortcut to exit scale mode in VirtualBox <p>What is the shortcut to exit scale mode in Oracle VirtualBox, Windows 7 host?</p>
<p>To exit Scale Mode, press:</p> <p><kbd>Right Ctrl (Host Key)</kbd> + <kbd>c</kbd></p> <hr> <p><em>Note that your</em> <kbd>(Host Key)</kbd> <em>may be different from</em> <kbd>Right Ctrl</kbd><em>. To check the current binding, go to <code>VirtualBox Preferences &gt; Input &gt; Virtual Machine &gt; Host Key Combination</code>.</em></p>
{ "question_id": 10716899, "question_date": "2012-05-23T09:16:11.253Z", "question_score": 711, "tags": "keyboard-shortcuts|virtual-machine|virtualbox|mode", "answer_id": 10716934, "answer_date": "2012-05-23T09:18:11.410Z", "answer_score": 1254 }
Please answer the following Stack Overflow question: Title: jQuery selectors on custom data attributes using HTML5 <p>I would like to know what selectors are available for these data attributes that come with HTML5.</p> <p>Taking this piece of HTML as an example:</p> <pre><code>&lt;ul data-group="Companies"&gt; &lt;li data-company="Microsoft"&gt;&lt;/li&gt; &lt;li data-company="Google"&gt;&lt;/li&gt; &lt;li data-company ="Facebook"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Are there selectors to get:</p> <ul> <li>All elements with <code>data-company="Microsoft"</code> below <code>"Companies"</code></li> <li>All elements with <code>data-company!="Microsoft"</code> below <code>"Companies"</code></li> <li>In other cases is it possible to use other selectors like "contains, less than, greater than, etc...".</li> </ul>
<pre><code>$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies" $("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies" </code></pre> <p>Look in to <a href="http://api.jquery.com/category/selectors/">jQuery Selectors</a> :contains is a selector</p> <p>here is info on the <a href="http://api.jquery.com/contains-selector/">:contains selector</a></p>
{ "question_id": 4146502, "question_date": "2010-11-10T16:15:25.370Z", "question_score": 711, "tags": "javascript|jquery|jquery-selectors|custom-data-attribute", "answer_id": 4146566, "answer_date": "2010-11-10T16:21:52.187Z", "answer_score": 1112 }
Please answer the following Stack Overflow question: Title: How to drop columns using Rails migration <p>What's the syntax for dropping a database table column through a <a href="https://guides.rubyonrails.org/active_record_migrations.html" rel="noreferrer">Rails migration</a>?</p>
<pre><code>remove_column :table_name, :column_name </code></pre> <p>For instance:</p> <pre><code>remove_column :users, :hobby </code></pre> <p>would remove the hobby Column from the users table.</p>
{ "question_id": 2831059, "question_date": "2010-05-14T00:02:54.707Z", "question_score": 711, "tags": "ruby-on-rails|ruby|database|activerecord|rails-migrations", "answer_id": 2963582, "answer_date": "2010-06-03T05:49:17.690Z", "answer_score": 1040 }
Please answer the following Stack Overflow question: Title: *.h or *.hpp for your class definitions <p>I've always used a <code>*.h</code> file for my class definitions, but after reading some boost library code, I realised they all use <code>*.hpp</code>. I've always had an aversion to that file extension, I think mainly because I'm not used to it.</p> <p>What are the advantages and disadvantages of using <code>*.hpp</code> over <code>*.h</code>?</p>
<p>Here are a couple of reasons for having different naming of C vs C++ headers:</p> <ul> <li>Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically</li> <li>Naming, I've been on projects where there were libraries written in C and then wrappers had been implemented in C++. Since the headers usually had similar names, i.e. Feature.h vs Feature.hpp, they were easy to tell apart.</li> <li>Inclusion, maybe your project has more appropriate versions available written in C++ but you are using the C version (see above point). If headers are named after the language they are implemented in you can easily spot all the C-headers and check for C++ versions.</li> </ul> <p>Remember, C is <strong>not</strong> C++ and it can be very dangerous to mix and match unless you know what you are doing. Naming your sources appropriately helps you tell the languages apart.</p>
{ "question_id": 152555, "question_date": "2008-09-30T10:47:16.163Z", "question_score": 711, "tags": "c++|header", "answer_id": 152671, "answer_date": "2008-09-30T11:41:07.437Z", "answer_score": 682 }
Please answer the following Stack Overflow question: Title: Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7 <p>Starting in iOS7, there is additional space at the top of my <code>UITableView</code>'s which have a style <code>UITableViewStyleGrouped</code>.</p> <p>Here is an example:</p> <p><img src="https://i.stack.imgur.com/yNYTL.png" alt="enter image description here" /></p> <p>The tableview starts at the first arrow, there are 35 pixels of unexplained padding, then the green header is a <code>UIView</code> returned by <code>viewForHeaderInSection</code> (where the section is 0).</p> <p>Can anyone explain where this 35-pixel amount is coming from and how I can get rid of it without switching to <code>UITableViewStylePlain</code>?</p> <hr /> <h1>Update (Answer):</h1> <p>In iOS 11 and later:</p> <pre><code>tableView.contentInsetAdjustmentBehavior = .never </code></pre>
<p>I have found the cause of my original bug and created a sample project showcasing it. I believe there is an iOS7 bug. </p> <p>As of iOS7, if you create a UITableView with the Grouped style, but do not have a delegate set on first layout, then you set a delegate and call reloadData, there will be a 35px space at the top that will never go away. </p> <p>See this project I made showcasing the bug: <a href="https://github.com/esilverberg/TableViewDelayedDelegateBug">https://github.com/esilverberg/TableViewDelayedDelegateBug</a></p> <p>Specifically this file: <a href="https://github.com/esilverberg/TableViewDelayedDelegateBug/blob/master/TableViewDelayedDelegateBug/ViewController.m">https://github.com/esilverberg/TableViewDelayedDelegateBug/blob/master/TableViewDelayedDelegateBug/ViewController.m</a></p> <p>If line 24 is active,</p> <pre><code>[self performSelector:@selector(updateDelegate) withObject:nil afterDelay:0.0]; </code></pre> <p>there will be an extra 35 px space at the top. If line 27 is active and 24 is commented out, </p> <pre><code>self.tableView.delegate = self; </code></pre> <p>no space at the top. It's like the tableView is caching a result somewhere and not redrawing itself after the delegate is set and reloadData is called. </p>
{ "question_id": 18880341, "question_date": "2013-09-18T19:07:06.863Z", "question_score": 711, "tags": "ios|uitableview|ios7", "answer_id": 19194505, "answer_date": "2013-10-05T05:52:57.133Z", "answer_score": 60 }
Please answer the following Stack Overflow question: Title: Should I put input elements inside a label element? <p>Is there a best practice concerning the nesting of <code>label</code> and <code>input</code> HTML elements?</p> <p>classic way:</p> <pre class="lang-html prettyprint-override"><code>&lt;label for="myinput"&gt;My Text&lt;/label&gt; &lt;input type="text" id="myinput" /&gt; </code></pre> <p>or</p> <pre class="lang-html prettyprint-override"><code>&lt;label for="myinput"&gt;My Text &lt;input type="text" id="myinput" /&gt; &lt;/label&gt; </code></pre>
<p>From the W3's <a href="http://www.w3.org/TR/html401/interact/forms.html#edef-LABEL" rel="noreferrer">HTML4 specification</a>:</p> <blockquote> <p>The label itself may be positioned before, after or around the associated control.</p> </blockquote> <hr /> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label for="lastname"&gt;Last Name&lt;/label&gt; &lt;input type="text" id="lastname" /&gt;</code></pre> </div> </div> </p> <p>or</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-html lang-html prettyprint-override"><code>&lt;input type="text" id="lastname" /&gt; &lt;label for="lastname"&gt;Last Name&lt;/label&gt;</code></pre> </div> </div> </p> <p>or</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-html lang-html prettyprint-override"><code>&lt;label&gt; &lt;input type="text" name="lastname" /&gt; Last Name &lt;/label&gt;</code></pre> </div> </div> </p> <p>Note that the third technique cannot be used when a table is being used for layout, with the label in one cell and its associated form field in another cell.</p> <p>Either one is valid. I like to use either the first or second example, as it gives you more style control.</p>
{ "question_id": 774054, "question_date": "2009-04-21T18:52:05.527Z", "question_score": 711, "tags": "html|semantics", "answer_id": 774065, "answer_date": "2009-04-21T18:54:35.583Z", "answer_score": 591 }
Please answer the following Stack Overflow question: Title: Node / Express: EADDRINUSE, Address already in use - Kill server <p>I have a simple server running in node.js using connect:</p> <pre><code>var server = require('connect').createServer(); //actions... server.listen(3000); </code></pre> <p>In my code I have actual handlers, but thats the basic idea. The problem I keep getting is</p> <pre><code>EADDRINUSE, Address already in use </code></pre> <p>I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with <code>ctr + z</code>.</p> <p>I am fairly certain all I have to do is close out the server or connection. I tried calling <code>server.close()</code> in <code>process.on('exit', ...);</code> with no luck.</p>
<p><code>process.on('exit', ..)</code> isn't called if the process crashes or is killed. It is only called when the event loop ends, and since <code>server.close()</code> <em>sort of</em> ends the event loop (it still has to wait for currently running stacks here and there) it makes no sense to put that inside the exit event...</p> <p>On crash, do <code>process.on('uncaughtException', ..)</code> and on kill do <code>process.on('SIGTERM', ..)</code></p> <p>That being said, SIGTERM (default kill signal) lets the app clean up, while SIGKILL (immediate termination) won't let the app do anything.</p>
{ "question_id": 4075287, "question_date": "2010-11-02T06:08:27.317Z", "question_score": 710, "tags": "node.js", "answer_id": 4086015, "answer_date": "2010-11-03T10:22:04.097Z", "answer_score": 178 }
Please answer the following Stack Overflow question: Title: denied: requested access to the resource is denied: docker <p>I am following <a href="https://docs.docker.com/engine/getstarted/step_four/" rel="noreferrer">this link</a> to create my first docker Image and it went successfully and now I am trying to push this Image into my docker repository from this <a href="https://docs.docker.com/engine/getstarted/step_six/" rel="noreferrer">link</a>. But whenever I am trying to push this Image into repository, I got this type of error.</p> <pre><code>denied: requested access to the resource is denied </code></pre> <p><a href="https://i.stack.imgur.com/GCu19.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GCu19.png" alt="" /></a></p> <p>Note: I have successfully login into docker</p>
<p>You may need to switch your docker repo to private before docker push.</p> <p>Thanks to the <a href="https://stackoverflow.com/a/42403423/4096935">answer</a> provided by <a href="https://stackoverflow.com/users/7607604/dean-wu">Dean Wu</a> and <a href="https://stackoverflow.com/questions/41984399/denied-requested-access-to-the-resource-is-denied-docker/41984666#comment94770203_41984666">this comment</a> by <a href="https://stackoverflow.com/users/369759/ses">ses</a>, before pushing, remember to <strong>log out</strong>, then <strong>log in</strong> from the command line to your docker hub account</p> <pre><code># you may need log out first `docker logout` ref. https://stackoverflow.com/a/53835882/248616 docker login </code></pre> <p>According to the <a href="https://docs.docker.com/engine/getstarted/step_six/#/step-1-tag-and-push-the-image" rel="noreferrer">docs</a>:</p> <pre><code>You need to include the namespace for Docker Hub to associate it with your account. The namespace is the same as your Docker Hub account name. You need to rename the image to YOUR_DOCKERHUB_NAME/docker-whale. </code></pre> <p>So, this means you have to <strong>tag</strong> your image before pushing:</p> <pre><code>docker tag firstimage YOUR_DOCKERHUB_NAME/firstimage </code></pre> <p>and then you should be able to push it.</p> <pre><code>docker push YOUR_DOCKERHUB_NAME/firstimage </code></pre>
{ "question_id": 41984399, "question_date": "2017-02-01T16:08:53.033Z", "question_score": 710, "tags": "docker|dockerfile", "answer_id": 41984666, "answer_date": "2017-02-01T16:22:45.067Z", "answer_score": 1097 }
Please answer the following Stack Overflow question: Title: How do I run a single test using Jest? <p>I have a test 'works with nested children' within the file fix-order-test.js.</p> <p>Running the below runs all the tests in the file.</p> <pre><code>jest fix-order-test </code></pre> <p>How do I run only a single test? The below does not work as it searches for a file of the regex specified.</p> <pre><code>jest 'works with nested children' </code></pre>
<p>From the command line, use the <code>--testNamePattern</code> or <code>-t</code> flag:</p> <pre><code>jest -t 'fix-order-test' </code></pre> <p>This will only run tests that match the test name pattern you provide. It's in the <a href="https://jestjs.io/docs/en/cli#--testnamepatternregex" rel="noreferrer">Jest documentation</a>.</p> <p>Another way is to run tests in watch mode, <code>jest --watch</code>, and then press <kbd>P</kbd> to filter the tests by typing the test file name or <kbd>T</kbd> to run a single test name.</p> <hr /> <p>If you have an <code>it</code> inside of a <code>describe</code> block, you have to run</p> <pre><code>jest -t '&lt;describeString&gt; &lt;itString&gt;' </code></pre>
{ "question_id": 42827054, "question_date": "2017-03-16T06:46:11.110Z", "question_score": 710, "tags": "jestjs", "answer_id": 42897994, "answer_date": "2017-03-20T07:28:23.553Z", "answer_score": 826 }
Please answer the following Stack Overflow question: Title: What is the equivalent of the C++ Pair<L,R> in Java? <p>Is there a good reason why there is no <code>Pair&lt;L,R&gt;</code> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.</p> <p>It seems that <strong>1.6</strong> is providing something similar (<code>AbstractMap.SimpleEntry&lt;K,V&gt;</code>), but this looks quite convoluted.</p>
<p>In <a href="http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b" rel="noreferrer">a thread on <code>comp.lang.java.help</code></a>, Hunter Gratzner gives some arguments against the presence of a <code>Pair</code> construct in Java. The main argument is that a class <code>Pair</code> doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?).</p> <p>A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the <code>Pair</code> class. <code>Map.Entry</code> is an example of a pair that carry its meaning in its name.</p> <p>To sum up, in my opinion it is better to have a class <code>Position(x,y)</code>, a class <code>Range(begin,end)</code> and a class <code>Entry(key,value)</code> rather than a generic <code>Pair(first,second)</code> that doesn't tell me anything about what it's supposed to do.</p>
{ "question_id": 156275, "question_date": "2008-10-01T04:48:41.553Z", "question_score": 710, "tags": "java|tuples|std-pair", "answer_id": 156685, "answer_date": "2008-10-01T08:18:24.500Z", "answer_score": 423 }
Please answer the following Stack Overflow question: Title: How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0? <p>How to wait in a bash script for several subprocesses spawned from that script to finish, and then return exit code <code>!=0</code> when any of the subprocesses ends with code <code>!=0</code>?</p> <p>Simple script:</p> <pre><code>#!/bin/bash for i in `seq 0 9`; do doCalculations $i &amp; done wait </code></pre> <p>The above script will wait for all 10 spawned subprocesses, but it will always give exit status <code>0</code> (see <code>help wait</code>). How can I modify this script so it will discover exit statuses of spawned subprocesses and return exit code <code>1</code> when any of subprocesses ends with code <code>!=0</code>?</p> <p>Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?</p>
<p><a href="https://www.gnu.org/software/bash/manual/html_node/Job-Control-Builtins.html#index-wait" rel="noreferrer"><code>wait</code></a> also (optionally) takes the <code>PID</code> of the process to wait for, and with <code>$!</code> you get the <code>PID</code> of the last command launched in the background. Modify the loop to store the <code>PID</code> of each spawned sub-process into an array, and then loop again waiting on each <code>PID</code>.</p> <pre class="lang-sh prettyprint-override"><code># run processes and store pids in array for i in $n_procs; do ./procs[${i}] &amp; pids[${i}]=$! done # wait for all pids for pid in ${pids[*]}; do wait $pid done </code></pre>
{ "question_id": 356100, "question_date": "2008-12-10T13:54:26.353Z", "question_score": 709, "tags": "bash|process|wait", "answer_id": 356154, "answer_date": "2008-12-10T14:07:51.350Z", "answer_score": 681 }
Please answer the following Stack Overflow question: Title: "Parameter" vs "Argument" <p>I got <em>parameter</em> and <em>argument</em> kind of mixed up and did not really pay attention to when to use one and when to use the other. </p> <p>Can you please tell me? </p>
<p>A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.</p> <p>Consider the following code:</p> <pre class="lang-cs prettyprint-override"><code>void Foo(int i, float f) { // Do things } void Bar() { int anInt = 1; Foo(anInt, 2.0); } </code></pre> <p>Here <code>i</code> and <code>f</code> are the parameters, and <code>anInt</code> and <code>2.0</code> are the arguments.</p>
{ "question_id": 1788923, "question_date": "2009-11-24T09:28:28.043Z", "question_score": 709, "tags": "function|parameters|language-agnostic|arguments|terminology", "answer_id": 1788926, "answer_date": "2009-11-24T09:29:18.603Z", "answer_score": 1206 }
Please answer the following Stack Overflow question: Title: How do you round UP a number? <p>How does one round a number UP in Python?</p> <p>I tried <code>round(number)</code> but it rounds the number down. Example:</p> <pre><code>round(2.3) = 2.0 </code></pre> <p>and not 3, as I would like.</p> <p>The I tried <code>int(number + .5)</code> but it round the number down again! Example:</p> <pre><code>int(2.3 + .5) = 2 </code></pre>
<p>The <a href="https://docs.python.org/3/library/math.html#math.ceil" rel="noreferrer">math.ceil</a> (ceiling) function returns the smallest integer higher or equal to <code>x</code>.</p> <p>For Python 3:</p> <pre><code>import math print(math.ceil(4.2)) </code></pre> <p>For Python 2:</p> <pre><code>import math print(int(math.ceil(4.2))) </code></pre>
{ "question_id": 2356501, "question_date": "2010-03-01T14:40:04.830Z", "question_score": 708, "tags": "python|floating-point|integer|rounding", "answer_id": 2356510, "answer_date": "2010-03-01T14:40:58.137Z", "answer_score": 1174 }
Please answer the following Stack Overflow question: Title: AsyncTask Android example <p>I was reading about <code>AsyncTask</code>, and I tried the simple program below. But it does not seem to work. How can I make it work?</p> <pre><code>public class AsyncTaskActivity extends Activity { Button btn; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button) findViewById(R.id.button1); btn.setOnClickListener((OnClickListener) this); } public void onClick(View view){ new LongOperation().execute(""); } private class LongOperation extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { for(int i=0;i&lt;5;i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } TextView txt = (TextView) findViewById(R.id.output); txt.setText("Executed"); return null; } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } } </code></pre> <p>I am just trying to change the label after 5 seconds in the background process.</p> <p>This is my <strong>main.xml</strong>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:indeterminate="false" android:max="10" android:padding="10dip"&gt; &lt;/ProgressBar&gt; &lt;Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Progress" &gt; &lt;/Button&gt; &lt;TextView android:id="@+id/output" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Replace"/&gt; &lt;/LinearLayout&gt; </code></pre>
<p>Ok, you are trying to access the GUI via another thread. This, in the main, is not good practice.</p> <p>The AsyncTask executes everything in <code>doInBackground()</code> inside of another thread, which does not have access to the GUI where your views are.</p> <p><code>preExecute()</code> and <code>postExecute()</code> offer you access to the GUI before and after the heavy lifting occurs in this new thread, and you can even pass the result of the long operation to <code>postExecute()</code> to then show any results of processing.</p> <p>See these lines where you are later updating your TextView:</p> <pre><code>TextView txt = findViewById(R.id.output); txt.setText("Executed"); </code></pre> <p>Put them in <code>onPostExecute()</code>.</p> <p>You will then see your TextView text updated after the <code>doInBackground</code> completes.</p> <p>I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.</p> <pre><code>import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings.System; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.view.View.OnClickListener; public class AsyncTaskActivity extends Activity implements OnClickListener { Button btn; AsyncTask&lt;?, ?, ?&gt; runningTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = findViewById(R.id.button1); // Because we implement OnClickListener, we only // have to pass "this" (much easier) btn.setOnClickListener(this); } @Override public void onClick(View view) { // Detect the view that was "clicked" switch (view.getId()) { case R.id.button1: if (runningTask != null) runningTask.cancel(true); runningTask = new LongOperation(); runningTask.execute(); break; } } @Override protected void onDestroy() { super.onDestroy(); // Cancel running task(s) to avoid memory leaks if (runningTask != null) runningTask.cancel(true); } private final class LongOperation extends AsyncTask&lt;Void, Void, String&gt; { @Override protected String doInBackground(Void... params) { for (int i = 0; i &lt; 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // We were cancelled; stop sleeping! } } return "Executed"; } @Override protected void onPostExecute(String result) { TextView txt = (TextView) findViewById(R.id.output); txt.setText("Executed"); // txt.setText(result); // You might want to change "executed" for the returned string // passed into onPostExecute(), but that is up to you } } } </code></pre>
{ "question_id": 9671546, "question_date": "2012-03-12T17:09:39.727Z", "question_score": 708, "tags": "android|android-asynctask", "answer_id": 9671602, "answer_date": "2012-03-12T17:12:49.010Z", "answer_score": 714 }
Please answer the following Stack Overflow question: Title: What is the quickest way to HTTP GET in Python? <p>What is the quickest way to HTTP GET in Python if I know the content will be a string? I am searching the documentation for a quick one-liner like:</p> <pre><code>contents = url.get("http://example.com/foo/bar") </code></pre> <p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p> <p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p> <ol> <li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li> </ol>
<p>Python 3:</p> <pre><code>import urllib.request contents = urllib.request.urlopen("http://example.com/foo/bar").read() </code></pre> <p>Python 2:</p> <pre><code>import urllib2 contents = urllib2.urlopen("http://example.com/foo/bar").read() </code></pre> <p>Documentation for <a href="https://docs.python.org/library/urllib.request.html" rel="noreferrer"><code>urllib.request</code></a> and <a href="https://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects" rel="noreferrer"><code>read</code></a>.</p>
{ "question_id": 645312, "question_date": "2009-03-14T03:44:22.350Z", "question_score": 708, "tags": "python|http|networking", "answer_id": 645318, "answer_date": "2009-03-14T03:48:24.290Z", "answer_score": 958 }
Please answer the following Stack Overflow question: Title: How to check internet access on Android? InetAddress never times out <p>I got a <code>AsyncTask</code> that is supposed to check the network access to a host name. But the <code>doInBackground()</code> is never timed out. Anyone have a clue?</p> <pre><code>public class HostAvailabilityTask extends AsyncTask&lt;String, Void, Boolean&gt; { private Main main; public HostAvailabilityTask(Main main) { this.main = main; } protected Boolean doInBackground(String... params) { Main.Log("doInBackground() isHostAvailable():"+params[0]); try { return InetAddress.getByName(params[0]).isReachable(30); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } protected void onPostExecute(Boolean... result) { Main.Log("onPostExecute()"); if(result[0] == false) { main.setContentView(R.layout.splash); return; } main.continueAfterHostCheck(); } } </code></pre>
<h1>Network connection / Internet access</h1> <ul> <li><code>isConnectedOrConnecting()</code> (used in most answers) checks for any <strong>network</strong> connection</li> <li>To know whether any of those networks have <strong>internet</strong> access, use one of the following</li> </ul> <h3>A) Ping a Server (easy)</h3> <pre><code>// ICMP public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec(&quot;/system/bin/ping -c 1 8.8.8.8&quot;); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } </code></pre> <p><code>+</code> could run on main thread</p> <p><code>-</code> does not work on some old devices (Galays S3, etc.), it blocks a while if no internet is available.</p> <h3>B) Connect to a Socket on the Internet (advanced)</h3> <pre><code>// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.) public boolean isOnline() { try { int timeoutMs = 1500; Socket sock = new Socket(); SocketAddress sockaddr = new InetSocketAddress(&quot;8.8.8.8&quot;, 53); sock.connect(sockaddr, timeoutMs); sock.close(); return true; } catch (IOException e) { return false; } } </code></pre> <p><code>+</code> very fast (either way), works on all devices, <em>very</em> reliable</p> <p><code>-</code> can't run on the UI thread</p> <p>This works very reliably, on every device, and is very fast. It needs to run in a separate task though (e.g. <code>ScheduledExecutorService</code> or <code>AsyncTask</code>).</p> <h3>Possible Questions</h3> <ul> <li><p>Is it really fast enough?</p> <p><em>Yes, very fast ;-)</em></p> </li> <li><p>Is there no reliable way to check internet, other than testing something on the internet?</p> <p><em>Not as far as I know, but let me know, and I will edit my answer.</em></p> </li> <li><p>What if the DNS is down?</p> <p><em>Google DNS (e.g. <code>8.8.8.8</code>) is the largest public DNS in the world. As of 2018 it handled over a trillion queries a day [<a href="https://security.googleblog.com/2018/08/google-public-dns-turns-8888-years-old.html" rel="noreferrer">1</a>]. Let 's just say, your app would probably not be the talk of the day.</em></p> </li> <li><p>Which permissions are required?</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; </code></pre> <p><em>Just internet access - surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about internet access, without this permission?)</em></p> </li> </ul> <p> </p> <h3>Extra: One-shot <code>RxJava/RxAndroid</code> Example (Kotlin)</h3> <pre><code>fun hasInternetConnection(): Single&lt;Boolean&gt; { return Single.fromCallable { try { // Connect to Google DNS to check for connection val timeoutMs = 1500 val socket = Socket() val socketAddress = InetSocketAddress(&quot;8.8.8.8&quot;, 53) socket.connect(socketAddress, timeoutMs) socket.close() true } catch (e: IOException) { false } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } /////////////////////////////////////////////////////////////////////////////////// // Usage hasInternetConnection().subscribe { hasInternet -&gt; /* do something */} </code></pre> <h3>Extra: One-shot <code>RxJava/RxAndroid</code> Example (Java)</h3> <pre><code>public static Single&lt;Boolean&gt; hasInternetConnection() { return Single.fromCallable(() -&gt; { try { // Connect to Google DNS to check for connection int timeoutMs = 1500; Socket socket = new Socket(); InetSocketAddress socketAddress = new InetSocketAddress(&quot;8.8.8.8&quot;, 53); socket.connect(socketAddress, timeoutMs); socket.close(); return true; } catch (IOException e) { return false; } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } /////////////////////////////////////////////////////////////////////////////////// // Usage hasInternetConnection().subscribe((hasInternet) -&gt; { if(hasInternet) { }else { } }); </code></pre> <h3>Extra: One-shot <code>AsyncTask</code> Example</h3> <p><em>Caution:</em> This shows another example of how to do the request. However, since <code>AsyncTask</code> is deprecated, it should be replaced by your App's thread scheduling, Kotlin Coroutines, Rx, ...</p> <pre><code>class InternetCheck extends AsyncTask&lt;Void,Void,Boolean&gt; { private Consumer mConsumer; public interface Consumer { void accept(Boolean internet); } public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); } @Override protected Boolean doInBackground(Void... voids) { try { Socket sock = new Socket(); sock.connect(new InetSocketAddress(&quot;8.8.8.8&quot;, 53), 1500); sock.close(); return true; } catch (IOException e) { return false; } } @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); } } /////////////////////////////////////////////////////////////////////////////////// // Usage new InternetCheck(internet -&gt; { /* do something with boolean response */ }); </code></pre>
{ "question_id": 1560788, "question_date": "2009-10-13T14:59:51.580Z", "question_score": 708, "tags": "java|android|android-asynctask|android-networking", "answer_id": 27312494, "answer_date": "2014-12-05T09:20:21.937Z", "answer_score": 655 }
Please answer the following Stack Overflow question: Title: Maximum call stack size exceeded error <p>I am using a Direct Web Remoting (DWR) JavaScript library file and am getting an error only in Safari (desktop and iPad)</p> <p>It says </p> <blockquote> <p>Maximum call stack size exceeded.</p> </blockquote> <p>What exactly does this error mean and does it stop processing completely?</p> <p>Also any fix for <code>Safari</code> browser (Actually on the <code>iPad Safari</code>, it says </p> <blockquote> <p>JS:execution exceeded timeout</p> </blockquote> <p>which I am assuming is the same call stack issue)</p>
<p>It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit.</p> <p>This is almost always because of a recursive function with a base case that isn't being met.</p> <h3>Viewing the stack</h3> <p>Consider this code...</p> <pre><code>(function a() { a(); })(); </code></pre> <p>Here is the stack after a handful of calls...</p> <p><img src="https://i.stack.imgur.com/aSwnu.png" alt="Web Inspector" /></p> <p>As you can see, the call stack grows until it hits a limit: the browser hardcoded stack size or memory exhaustion.</p> <p>In order to fix it, ensure that your recursive function has a base case which is able to be met...</p> <pre><code>(function a(x) { // The following condition // is the base case. if ( ! x) { return; } a(--x); })(10); </code></pre>
{ "question_id": 6095530, "question_date": "2011-05-23T09:49:48.257Z", "question_score": 707, "tags": "javascript|html|webkit|callstack|dwr", "answer_id": 6095695, "answer_date": "2011-05-23T10:05:44.163Z", "answer_score": 802 }
Please answer the following Stack Overflow question: Title: Find and Replace Inside a Text File from a Bash Command <p>What's the simplest way to do a find and replace for a given input string, say <code>abc</code>, and replace with another string, say <code>XYZ</code> in file <code>/tmp/file.txt</code>?</p> <p>I am writting an app and using IronPython to execute commands through SSH &mdash; but I don't know Unix that well and don't know what to look for.</p> <p>I have heard that Bash, apart from being a command line interface, can be a very powerful scripting language. So, if this is true, I assume you can perform actions like these.</p> <p>Can I do it with bash, and what's the simplest (one line) script to achieve my goal?</p>
<p>The easiest way is to use sed (or perl):</p> <pre class="lang-sh prettyprint-override"><code>sed -i -e 's/abc/XYZ/g' /tmp/file.txt </code></pre> <p>Which will invoke sed to do an in-place edit due to the <code>-i</code> option. This can be called from bash.</p> <p>If you really really want to use just bash, then the following can work:</p> <pre class="lang-sh prettyprint-override"><code>while IFS='' read -r a; do echo &quot;${a//abc/XYZ}&quot; done &lt; /tmp/file.txt &gt; /tmp/file.txt.t mv /tmp/file.txt{.t,} </code></pre> <p>This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)</p> <h3>For Mac users:</h3> <pre class="lang-sh prettyprint-override"><code>sed -i '' 's/abc/XYZ/g' /tmp/file.txt </code></pre> <p><em>(See the comment below why)</em></p>
{ "question_id": 525592, "question_date": "2009-02-08T11:57:39.143Z", "question_score": 707, "tags": "bash|replace|scripting|ironpython", "answer_id": 525612, "answer_date": "2009-02-08T12:20:29.707Z", "answer_score": 1178 }
Please answer the following Stack Overflow question: Title: How to replace a string in multiple files in linux command line <p>I need to replace a string in a lot of files in a folder, with only <code>ssh</code> access to the server. How can I do this?</p>
<pre><code>cd /path/to/your/folder sed -i 's/foo/bar/g' * </code></pre> <p>Occurrences of "foo" will be replaced with "bar".</p> <p>On BSD systems like macOS, you need to provide a backup extension like <code>-i '.bak'</code> or else "risk corruption or partial content" per the manpage.</p> <pre><code>cd /path/to/your/folder sed -i '.bak' 's/foo/bar/g' * </code></pre>
{ "question_id": 11392478, "question_date": "2012-07-09T09:37:47.687Z", "question_score": 707, "tags": "linux|string", "answer_id": 11392505, "answer_date": "2012-07-09T09:39:40.697Z", "answer_score": 893 }
Please answer the following Stack Overflow question: Title: Ignoring new fields on JSON objects using Jackson <p>I'm using Jackson JSON library to convert some JSON objects to POJO classes on an android application. The problem is, the JSON objects might change and have new fields added while the application is published, but currently it will break even when a simple String field is added, which can safely be ignored. </p> <p>Is there any way to tell Jackson to ignore newly added fields? (e.g. non-existing on the POJO objects)? A global ignore would be great.</p>
<p>Jackson provides an annotation that can be used on class level (<a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html" rel="noreferrer">JsonIgnoreProperties</a>). </p> <p>Add the following to the top of your class (<em>not</em> to individual methods):</p> <pre><code>@JsonIgnoreProperties(ignoreUnknown = true) public class Foo { ... } </code></pre> <p>Depending on the jackson version you are using you would have to use a different import in the current version it is:</p> <pre><code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties; </code></pre> <p>in older versions it has been:</p> <pre><code>import org.codehaus.jackson.annotate.JsonIgnoreProperties; </code></pre>
{ "question_id": 5455014, "question_date": "2011-03-28T05:26:16.557Z", "question_score": 707, "tags": "java|json|jackson", "answer_id": 5455563, "answer_date": "2011-03-28T06:52:26.663Z", "answer_score": 974 }
Please answer the following Stack Overflow question: Title: C# Equivalent of SQL Server DataTypes <p>For the following SQL Server datatypes, what would be the corresponding datatype in C#?</p> <p><strong>Exact Numerics</strong></p> <pre><code>bigint numeric bit smallint decimal smallmoney int tinyint money </code></pre> <hr> <p><strong>Approximate Numerics</strong></p> <pre><code>float real </code></pre> <hr> <p><strong>Date and Time</strong></p> <pre><code>date datetimeoffset datetime2 smalldatetime datetime time </code></pre> <hr> <p><strong>Character Strings</strong></p> <pre><code>char varchar text </code></pre> <hr> <p><strong>Unicode Character Strings</strong></p> <pre><code>nchar nvarchar ntext </code></pre> <hr> <p><strong>Binary Strings</strong></p> <pre><code>binary varbinary image </code></pre> <hr> <p><strong>Other Data Types</strong></p> <pre><code>cursor timestamp hierarchyid uniqueidentifier sql_variant xml table </code></pre> <p>(source: <a href="http://msdn.microsoft.com/en-us/library/ms187752.aspx" rel="noreferrer">MSDN</a>)</p>
<p>This is for <a href="http://msdn.microsoft.com/en-us/library/ms131092(SQL.90).aspx" rel="noreferrer">SQL Server 2005</a>. There are updated versions of the table for <a href="http://msdn.microsoft.com/en-us/library/ms131092%28v=sql.100%29.aspx" rel="noreferrer">SQL Server 2008</a>, <a href="http://msdn.microsoft.com/en-us/library/ms131092%28v=sql.105%29.aspx" rel="noreferrer">SQL Server 2008 R2</a>, <a href="http://msdn.microsoft.com/en-us/library/ms131092%28v=sql.110%29.aspx" rel="noreferrer">SQL Server 2012</a> and <a href="http://msdn.microsoft.com/en-us/library/ms131092(v=sql.120).aspx" rel="noreferrer">SQL Server 2014</a>.</p> <h2>SQL Server Data Types and Their .NET Framework Equivalents</h2> <p>The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the <strong>System.Data.SqlTypes</strong> namespace, and their native CLR equivalents in the Microsoft .NET Framework.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SQL Server data type</th> <th>CLR data type (SQL Server)</th> <th>CLR data type (.NET Framework)</th> </tr> </thead> <tbody> <tr> <td>varbinary</td> <td>SqlBytes, SqlBinary</td> <td>Byte[]</td> </tr> <tr> <td>binary</td> <td>SqlBytes, SqlBinary</td> <td>Byte[]</td> </tr> <tr> <td>varbinary(1), binary(1)</td> <td>SqlBytes, SqlBinary</td> <td>byte, Byte[]</td> </tr> <tr> <td>image</td> <td>None</td> <td>None</td> </tr> <tr> <td>varchar</td> <td>None</td> <td>None</td> </tr> <tr> <td>char</td> <td>None</td> <td>None</td> </tr> <tr> <td>nvarchar(1), nchar(1)</td> <td>SqlChars, SqlString</td> <td>Char, String, Char[]</td> </tr> <tr> <td>nvarchar</td> <td>SqlChars, SqlString</td> <td>String, Char[]</td> </tr> <tr> <td>nchar</td> <td>SqlChars, SqlString</td> <td>String, Char[]</td> </tr> <tr> <td>text</td> <td>None</td> <td>None</td> </tr> <tr> <td>ntext</td> <td>None</td> <td>None</td> </tr> <tr> <td>uniqueidentifier</td> <td>SqlGuid</td> <td>Guid</td> </tr> <tr> <td>rowversion</td> <td>None</td> <td>Byte[]</td> </tr> <tr> <td>bit</td> <td>SqlBoolean</td> <td>Boolean</td> </tr> <tr> <td>tinyint</td> <td>SqlByte</td> <td>Byte</td> </tr> <tr> <td>smallint</td> <td>SqlInt16</td> <td>Int16</td> </tr> <tr> <td>int</td> <td>SqlInt32</td> <td>Int32</td> </tr> <tr> <td>bigint</td> <td>SqlInt64</td> <td>Int64</td> </tr> <tr> <td>smallmoney</td> <td>SqlMoney</td> <td>Decimal</td> </tr> <tr> <td>money</td> <td>SqlMoney</td> <td>Decimal</td> </tr> <tr> <td>numeric</td> <td>SqlDecimal</td> <td>Decimal</td> </tr> <tr> <td>decimal</td> <td>SqlDecimal</td> <td>Decimal</td> </tr> <tr> <td>real</td> <td>SqlSingle</td> <td>Single</td> </tr> <tr> <td>float</td> <td>SqlDouble</td> <td>Double</td> </tr> <tr> <td>smalldatetime</td> <td>SqlDateTime</td> <td>DateTime</td> </tr> <tr> <td>datetime</td> <td>SqlDateTime</td> <td>DateTime</td> </tr> <tr> <td>sql_variant</td> <td>None</td> <td>Object</td> </tr> <tr> <td>User-defined type(UDT)</td> <td>None</td> <td>user-defined type</td> </tr> <tr> <td>table</td> <td>None</td> <td>None</td> </tr> <tr> <td>cursor</td> <td>None</td> <td>None</td> </tr> <tr> <td>timestamp</td> <td>None</td> <td>None</td> </tr> <tr> <td>xml</td> <td>SqlXml</td> <td>None</td> </tr> </tbody> </table> </div>
{ "question_id": 425389, "question_date": "2009-01-08T18:51:08.753Z", "question_score": 707, "tags": "c#|.net|sql-server", "answer_id": 968734, "answer_date": "2009-06-09T07:57:43.567Z", "answer_score": 1264 }