input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How Can I add HTML And CSS Into PDF
<p>I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML.</p>
<p>I'm now after a way of converting it to PDF. I have tried:</p>
<ul>
<li><a href="https://github.com/dompdf/dompdf" rel="noreferrer">DOMPDF</a>: it had huge problems with tables. I factored out my large nested tables and it helped (before it was just consuming up to 128M of memory then dying--thats my limit on memory in php.ini) but it makes a complete mess of tables and doesn't seem to get images. The tables were just basic stuff with some border styles to add some lines at various points;</li>
<li><a href="https://github.com/spipu/html2pdf" rel="noreferrer">HTML2PDF and HTML2PS</a>: I actually had better luck with this. It rendered some of the images (all the images are Google Chart URLs) and the table formatting was much better but it seemed to have some complexity problem I haven't figured out yet and kept dying with unknown node_type() errors. Not sure where to go from here; and</li>
<li><a href="http://www.msweet.org/projects.php?Z1" rel="noreferrer">Htmldoc</a>: this seems to work fine on basic HTML but has almost no support for CSS whatsoever so you have to do everything in HTML (I didn't realize it was still 2001 in Htmldoc-land...) so it's useless to me.</li>
</ul>
<p>I tried a Windows app called Html2Pdf Pilot that actually did a pretty decent job but I need something that at a minimum runs on Linux and ideally runs on-demand via PHP on the Webserver.</p>
<p>What am I missing, or how can I resolve this issue?</p> | <p><strong>Important:</strong>
Please note that this answer was written in 2009 and it might not be the most cost-effective solution today in 2019. Online alternatives are better today at this than they were back then.</p>
<p>Here are some online services that you can use:</p>
<ul>
<li><a href="https://pdfshift.io" rel="noreferrer">PDFShift</a></li>
<li><a href="https://restpack.io/html2pdf" rel="noreferrer">Restpack</a></li>
<li><a href="https://pdflayer.com" rel="noreferrer">PDF Layer</a></li>
<li><a href="https://docraptor.com" rel="noreferrer">DocRaptor</a></li>
<li><a href="https://htmlpdfapi.com" rel="noreferrer">HTMLPDFAPI</a></li>
<li><a href="https://www.html2pdfrocket.com" rel="noreferrer">HTML to PDF Rocket</a></li>
</ul>
<hr>
<p>Have a look at <a href="http://princexml.com" rel="noreferrer">PrinceXML</a>.</p>
<p>It's definitely the best HTML/CSS to PDF converter out there, although it's not free (But hey, your programming might not be free either, so if it saves you 10 hours of work, you're home free (since you also need to take into account that the alternative solutions will require you to setup a dedicated server with the right software)</p>
<p>Oh yeah, did I mention that this is the first (and probably only) HTML2PDF solution that does full <a href="http://princexml.com/samples/acid2/acid2.pdf" rel="noreferrer">ACID2</a> ?</p>
<p><a href="http://princexml.com/samples/" rel="noreferrer">PrinceXML Samples</a></p> | {
"question_id": 391005,
"question_date": "2008-12-24T08:14:20.757Z",
"question_score": 1708,
"tags": "php|html|css|pdf|pdf-generation",
"answer_id": 434827,
"answer_date": "2009-01-12T08:47:28.523Z",
"answer_score": 563
} |
Please answer the following Stack Overflow question:
Title: Difference between StringBuilder and StringBuffer
<p>What is the main difference between <code>StringBuffer</code> and <code>StringBuilder</code>?
Is there any performance issues when deciding on any one of these?</p> | <p><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html" rel="noreferrer"><code>StringBuffer</code></a> is synchronized, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html" rel="noreferrer"><code>StringBuilder</code></a> is not.</p> | {
"question_id": 355089,
"question_date": "2008-12-10T04:34:26.263Z",
"question_score": 1708,
"tags": "java|stringbuilder|stringbuffer",
"answer_id": 355092,
"answer_date": "2008-12-10T04:36:23.110Z",
"answer_score": 1762
} |
Please answer the following Stack Overflow question:
Title: HTTP status code for update and delete?
<p>What status code should I set for <code>UPDATE</code> (<code>PUT</code>) and <code>DELETE</code> (e.g. product successfully updated)?</p> | <p>For a <strong>PUT</strong> request: <strong>HTTP 200</strong>, <strong>HTTP 204</strong> should imply "resource updated successfully". <strong>HTTP 201</strong> if the <strong>PUT</strong> request created a new resource.</p>
<p>For a <strong>DELETE</strong> request: <strong>HTTP 200</strong> or <strong>HTTP 204</strong> should imply "resource deleted successfully".</p>
<p><strong>HTTP 202</strong> can also be returned by either operation and would imply that the instruction was accepted by the server, but not fully applied yet. It's possible that the operation fails later, so the client shouldn't fully assume that it was success.</p>
<p>A client that receives a status code it doesn't recognize, but it's starting with 2 should treat it as a 200 OK.</p>
<blockquote>
<p><strong><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6" rel="noreferrer">PUT</a></strong></p>
<p>If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.</p>
</blockquote>
<blockquote>
<p><strong><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7" rel="noreferrer">DELETE</a></strong></p>
<p>A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.</p>
</blockquote>
<p>Source: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">W3.org: HTTP/1.1 Method Definitions</a></p>
<blockquote>
<p><strong>HTTP 200 OK:</strong> Standard response for successful HTTP
requests. The actual response will
depend on the request method used.</p>
<p><strong>HTTP 204 No Content:</strong> The server successfully processed the request, but is not returning any content</p>
</blockquote>
<p>Source: <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success" rel="noreferrer">List of HTTP status codes: 2xx Success</a></p> | {
"question_id": 2342579,
"question_date": "2010-02-26T15:16:40.613Z",
"question_score": 1706,
"tags": "http|http-status-codes",
"answer_id": 2342589,
"answer_date": "2010-02-26T15:18:16.380Z",
"answer_score": 2566
} |
Please answer the following Stack Overflow question:
Title: Disabling Chrome cache for website development
<p>I am modifying a site's appearance (CSS modifications) but can't see the result on Chrome because of annoying persistent cache. I tried <kbd>Shift</kbd>+refresh but it doesn't work.</p>
<p>How can I disable the cache temporarily or refresh the page in some way that I could see the changes?</p> | <p>The Chrome DevTools can disable the cache.</p>
<ol>
<li><strong>Right-click</strong> and choose <code>Inspect Element</code> to open the DevTools. Or use one of the following <a href="https://developers.google.com/web/tools/chrome-devtools/shortcuts" rel="noreferrer">keyboard shortcuts</a>:</li>
</ol>
<ul>
<li><kbd>F12</kbd></li>
<li><kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd></li>
<li><kbd>Command</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd></li>
</ul>
<ol>
<li><strong>Click</strong> <code>Network</code> in the toolbar to open the network pane.</li>
<li><strong>Check</strong> the <code>Disable cache</code> checkbox at the top.</li>
</ol>
<p><img src="https://i.stack.imgur.com/Grwsc.png" alt="screenshot of development tools panel" /></p>
<p>Keep in mind, as a <a href="https://twitter.com/ChromiumDev/status/227356682890670080" rel="noreferrer">tweet</a> from <a href="https://twitter.com/chromiumdev" rel="noreferrer">@ChromiumDev</a> stated, this setting is <strong>only active while the devtools are open</strong>.</p>
<p>Note that this will result in <em>all</em> resources being reloaded. Should you desire to disable the cache only for some resources, you can <a href="https://stackoverflow.com/questions/11532636/how-to-prevent-http-file-caching-in-apache-httpd-mamp">modify the HTTP header</a> that your server sends alongside your files.</p>
<p>If you do not want to use the <code>Disable cache</code> checkbox, a long press on the refresh button <strong>with the DevTools open</strong> will show a menu with the options to <code>Hard Reload</code> or <code>Empty Cache and Hard Reload</code> which should have a similar effect. Read about the <a href="https://stackoverflow.com/questions/14969315/whats-the-difference-between-normal-reload-hard-reload-and-empty-cache-a#14969509">difference between the options</a> to know which option to choose. The following shortcuts are available:</p>
<ul>
<li><kbd>Command</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> on Mac</li>
<li><kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> on Windows or Linux</li>
</ul>
<p><img src="https://i.stack.imgur.com/QAtRy.jpg" alt="long press" /></p> | {
"question_id": 5690269,
"question_date": "2011-04-16T23:10:49.650Z",
"question_score": 1703,
"tags": "google-chrome|caching|browser|google-chrome-devtools|browser-cache",
"answer_id": 7000899,
"answer_date": "2011-08-09T18:20:42.717Z",
"answer_score": 2067
} |
Please answer the following Stack Overflow question:
Title: Differences between Lodash and Underscore.js
<p>Why would someone prefer either the <a href="http://lodash.com/" rel="noreferrer">Lodash</a> or <a href="http://underscorejs.org/" rel="noreferrer">Underscore.js</a> utility library over the other?</p>
<p>Lodash seems to be a drop-in replacement for underscore, the latter having been around longer.</p>
<p>I think both are brilliant, but I do not know enough about how they work to make an educated comparison, and I would like to know more about the differences.</p> | <p>I created Lodash to provide more consistent cross-environment iteration support for arrays, strings, objects, and <code>arguments</code> objects<sup>1</sup>. It has since become a superset of Underscore.js, providing more consistent API behavior, more <a href="http://lodash.com" rel="noreferrer">features</a> (like AMD support, deep clone, and deep merge), more thorough <a href="http://lodash.com/docs" rel="noreferrer">documentation</a> and unit tests (tests which run in <a href="https://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a>, <a href="https://github.com/ringo/ringojs" rel="noreferrer">RingoJS</a>, <a href="https://en.wikipedia.org/wiki/Rhino_%28JavaScript_engine%29" rel="noreferrer">Rhino</a>, <a href="https://github.com/tlrobinson/narwhal" rel="noreferrer">Narwhal</a>, <a href="https://en.wikipedia.org/wiki/PhantomJS" rel="noreferrer">PhantomJS</a>, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with <a href="http://lodash.com/" rel="noreferrer">custom builds</a> and template pre-compilation utilities.</p>
<p>Because Lodash is updated more frequently than Underscore.js, a <code>lodash underscore</code> build <a href="http://lodash.com/" rel="noreferrer">is provided</a> to ensure compatibility with the latest stable version of Underscore.js.</p>
<p>At one point I was even given <a href="https://s3.amazonaws.com/f.cl.ly/items/2e0O0S010f2A3s1W283U/push_access.png?v=ba693725" rel="noreferrer">push access</a> to Underscore.js, in part because Lodash is responsible for raising more than 30 issues; landing bug fixes, new features, and performance gains in Underscore.js v1.4.x+.</p>
<p>In addition, there are at least three <a href="https://en.wikipedia.org/wiki/Backbone.js" rel="noreferrer">Backbone.js</a> boilerplates that include Lodash by default and Lodash is now mentioned in Backbone.js’s official <a href="http://backbonejs.org/#downloads" rel="noreferrer">documentation</a>.</p>
<p>Check out Kit Cambridge's post, <em><a href="https://web.archive.org/web/20180101093627/http://kitcambridge.be/blog/say-hello-to-lo-dash/" rel="noreferrer">Say "Hello" to Lo-Dash</a></em>, for a deeper breakdown on the differences between Lodash and Underscore.js.</p>
<p>Footnotes:</p>
<ol>
<li>Underscore.js has inconsistent support for arrays, strings, objects, and <code>arguments</code> objects. In newer browsers, Underscore.js methods ignore <a href="http://www.2ality.com/2012/06/dense-arrays.html" rel="noreferrer">holes in arrays</a>, "Objects" methods iterate <code>arguments</code> objects, strings are treated as array-like, and methods correctly iterate functions (ignoring their "prototype" property) and objects (iterating shadowed properties like "toString" and "valueOf"), while in older browsers they will not. Also, Underscore.js methods, like <code>_.clone</code>, preserve holes in arrays, while others like <code>_.flatten</code> don't.</li>
</ol> | {
"question_id": 13789618,
"question_date": "2012-12-09T17:08:36.030Z",
"question_score": 1700,
"tags": "underscore.js|javascript|lodash",
"answer_id": 13898916,
"answer_date": "2012-12-16T05:34:06.213Z",
"answer_score": 2133
} |
Please answer the following Stack Overflow question:
Title: Extracting extension from filename in Python
<p>Is there a function to extract the extension from a filename?</p> | <p>Use <a href="https://docs.python.org/3/library/os.path.html#os.path.splitext" rel="noreferrer"><code>os.path.splitext</code></a>:</p>
<pre><code>>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
</code></pre>
<p>Unlike most manual string-splitting attempts, <code>os.path.splitext</code> will correctly treat <code>/a/b.c/d</code> as having no extension instead of having extension <code>.c/d</code>, and it will treat <code>.bashrc</code> as having no extension instead of having extension <code>.bashrc</code>:</p>
<pre><code>>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
</code></pre> | {
"question_id": 541390,
"question_date": "2009-02-12T14:11:50.570Z",
"question_score": 1696,
"tags": "python|filenames|file-extension",
"answer_id": 541394,
"answer_date": "2009-02-12T14:12:46.010Z",
"answer_score": 2483
} |
Please answer the following Stack Overflow question:
Title: How can I selectively merge or pick changes from another branch in Git?
<p>I'm using Git on a new project that has two parallel -- but currently experimental -- development branches:</p>
<ul>
<li><code>master</code>: import of existing codebase plus a few modifications that I'm generally sure of</li>
<li><code>exp1</code>: experimental branch #1</li>
<li><code>exp2</code>: experimental branch #2</li>
</ul>
<p><code>exp1</code> and <code>exp2</code> represent two very different architectural approaches. Until I get further along I have no way of knowing which one (if either) will work. As I make progress in one branch I sometimes have edits that would be useful in the other branch and would like to merge just those.</p>
<p><strong>What is the best way to merge selective changes from one development branch to another while leaving behind everything else?</strong></p>
<p>Approaches I've considered:</p>
<ol>
<li><p><code>git merge --no-commit</code> followed by manual unstaging of a large number of edits that I don't want to make common between the branches.</p>
</li>
<li><p>Manual copying of common files into a temporary directory followed by <code>git checkout</code> to move to the other branch and then more manual copying out of the temporary directory into the working tree.</p>
</li>
<li><p>A variation on the above. Abandon the <code>exp</code> branches for now and use two additional local repositories for experimentation. This makes the manual copying of files much more straightforward.</p>
</li>
</ol>
<p>All three of these approaches seem tedious and error-prone. I'm hoping there is a better approach; something akin to a filter path parameter that would make <code>git-merge</code> more selective.</p> | <p>You use the <a href="https://git-scm.com/docs/git-cherry-pick" rel="nofollow noreferrer">cherry-pick</a> command to get individual commits from one branch.</p>
<p>If the change(s) you want are not in individual commits, then use the method shown here to <a href="http://plasmasturm.org/log/530/" rel="nofollow noreferrer">split the commit into individual commits</a>. Roughly speaking, you use <code>git rebase -i</code> to get the original commit to edit, then <code>git reset HEAD^</code> to selectively revert changes, then <code>git commit</code> to commit that bit as a new commit in the history.</p>
<p><a href="http://web.archive.org/web/20130727101330/http://magazine.redhat.com:80/2008/05/02/shipping-quality-code-with-git/" rel="nofollow noreferrer">There is another nice method here</a> in Red Hat Magazine, where they use <code>git add --patch</code> or possibly <code>git add --interactive</code> which allows you to add just parts of a hunk, if you want to split different changes to an individual file (search in that page for "split").</p>
<p>Having split the changes, you can now cherry-pick just the ones you want.</p> | {
"question_id": 449541,
"question_date": "2009-01-16T04:55:08.973Z",
"question_score": 1696,
"tags": "git|git-merge|git-cherry-pick|git-patch",
"answer_id": 449632,
"answer_date": "2009-01-16T06:01:26.250Z",
"answer_score": 551
} |
Please answer the following Stack Overflow question:
Title: Is there a "previous sibling" selector?
<p>The plus sign (<code>+</code>) is for selecting the next sibling.</p>
<p>Is there an equivalent for the previous sibling?</p> | <p>No, there is no "previous sibling" selector.</p>
<p>On a related note, <code>~</code> is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. <code>+</code> is for next sibling and is CSS2.1.</p>
<p>See <a href="http://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators" rel="noreferrer">Adjacent sibling combinator</a> from <a href="http://www.w3.org/TR/css3-selectors/" rel="noreferrer">Selectors Level 3</a> and <a href="http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors" rel="noreferrer">5.7 Adjacent sibling selectors</a> from <a href="http://www.w3.org/TR/CSS21/cover.html#minitoc" rel="noreferrer">Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification</a>.</p> | {
"question_id": 1817792,
"question_date": "2009-11-30T04:06:36.633Z",
"question_score": 1696,
"tags": "css|css-selectors|siblings",
"answer_id": 1817801,
"answer_date": "2009-11-30T04:08:54.133Z",
"answer_score": 976
} |
Please answer the following Stack Overflow question:
Title: .gitignore is ignored by Git
<p>My <code>.gitignore</code> file seems to be being ignored by Git - could the <code>.gitignore</code> file be corrupt? Which file format, locale or culture does Git expect?</p>
<p>My <code>.gitignore</code>:</p>
<pre><code># This is a comment
debug.log
nbproject/
</code></pre>
<p>Output from <code>git status</code>:</p>
<pre><code># On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# debug.log
# nbproject/
nothing added to commit but untracked files present (use "git add" to track)
</code></pre>
<p>I would like <code>debug.log</code> and <code>nbproject/</code> not to appear in the untracked files list.</p>
<p>Where should I start looking to fix this?</p> | <p>Fixed. OK, I created the .gitignore file in Notepad on Windows and it wasn't working. When I viewed the .gitignore file on Linux it looked like organised gibberish - perhaps Notepad had written out Unicode rather than ASCII or whatever 8-bit is.</p>
<p>So I rewrote the file on my Linux box, and when I pulled it back into Windows it works fine! Hurrah!</p> | {
"question_id": 11451535,
"question_date": "2012-07-12T12:09:56.280Z",
"question_score": 1696,
"tags": "git|gitignore",
"answer_id": 11451916,
"answer_date": "2012-07-12T12:30:50.053Z",
"answer_score": 224
} |
Please answer the following Stack Overflow question:
Title: How to prettyprint a JSON file?
<p>How do I pretty-print a JSON file in Python?</p> | <p>Use the <code>indent=</code> parameter of <a href="https://docs.python.org/3/library/json.html#json.dump" rel="noreferrer"><code>json.dump()</code></a> or <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="noreferrer"><code>json.dumps()</code></a> to specify how many spaces to indent by:</p>
<pre><code>>>> import json
>>>
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
</code></pre>
<p>To parse a file, use <a href="https://docs.python.org/3/library/json.html#json.load" rel="noreferrer"><code>json.load()</code></a>:</p>
<pre><code>with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
</code></pre> | {
"question_id": 12943819,
"question_date": "2012-10-17T21:38:43.023Z",
"question_score": 1695,
"tags": "python|json|formatting|pretty-print",
"answer_id": 12944035,
"answer_date": "2012-10-17T21:54:12.800Z",
"answer_score": 2600
} |
Please answer the following Stack Overflow question:
Title: Difference between == and === in JavaScript
<p>What is the difference between <code>==</code> and <code>===</code> in JavaScript? I have also seen <code>!=</code> and <code>!==</code> operators. Are there more such operators?</p> | <p><code>===</code> and <code>!==</code> are strict comparison operators:</p>
<blockquote>
<p>JavaScript has both strict and
type-converting equality comparison.
For <code>strict</code> equality the objects being
compared must have the same type and:</p>
<ul>
<li>Two strings are strictly equal when they have the same sequence of
characters, same length, and same
characters in corresponding positions.</li>
<li>Two numbers are strictly equal when they are numerically equal (have
the same number value). <code>NaN</code> is not
equal to anything, including <code>NaN</code>.
Positive and negative zeros are equal
to one another.</li>
<li>Two Boolean operands are strictly equal if both are true or
both are false.</li>
<li>Two objects are strictly equal if they refer to the same <code>Object</code>.</li>
<li><code>Null</code> and <code>Undefined</code> types are <code>==</code> (but not <code>===</code>). [I.e. (<code>Null==Undefined</code>) is <code>true</code> but (<code>Null===Undefined</code>) is <code>false</code>]</li>
</ul>
</blockquote>
<p><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators" rel="noreferrer">Comparison Operators - MDC</a></p> | {
"question_id": 523643,
"question_date": "2009-02-07T11:53:04.270Z",
"question_score": 1694,
"tags": "javascript|comparison-operators|equality-operator|identity-operator",
"answer_id": 523647,
"answer_date": "2009-02-07T11:55:34.547Z",
"answer_score": 1212
} |
Please answer the following Stack Overflow question:
Title: What is the difference between an abstract method and a virtual method?
<p>What is the difference between an abstract method and a virtual method? In which cases is it recommended to use abstract or virtual methods? Which one is the best approach?</p> | <p><strong>An abstract function cannot have functionality.</strong> You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. </p>
<p><strong>A virtual function</strong>, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.</p> | {
"question_id": 391483,
"question_date": "2008-12-24T14:11:43.377Z",
"question_score": 1694,
"tags": "oop|language-agnostic|abstract|virtual-functions",
"answer_id": 391492,
"answer_date": "2008-12-24T14:14:19.673Z",
"answer_score": 2877
} |
Please answer the following Stack Overflow question:
Title: How to find a deleted file in the project commit history?
<p>Once upon a time, there was a file in my project that I would now like to be able to get.</p>
<p>The problem is: I have no idea of when have I deleted it and on which path it was.</p>
<p>How can I locate the commits of this file when it existed?</p> | <p>If you do not know the exact path you may use</p>
<pre><code>git log --all --full-history -- "**/thefile.*"
</code></pre>
<p>If you know the path the file was at, you can do this:</p>
<pre><code>git log --all --full-history -- <path-to-file>
</code></pre>
<p>This should show a list of commits in all branches which touched that file. Then, you can find the version of the file you want, and display it with...</p>
<pre><code>git show <SHA> -- <path-to-file>
</code></pre>
<p>Or restore it into your working copy with:</p>
<p><code>git checkout <SHA>^ -- <path-to-file></code></p>
<p>Note the caret symbol (<code>^</code>), which gets the checkout <em>prior</em> to the one identified, because at the moment of <code><SHA></code> commit the file is deleted, we need to look at the previous commit to get the deleted file's contents</p> | {
"question_id": 7203515,
"question_date": "2011-08-26T10:43:29.447Z",
"question_score": 1693,
"tags": "git",
"answer_id": 7203551,
"answer_date": "2011-08-26T10:46:00.663Z",
"answer_score": 2093
} |
Please answer the following Stack Overflow question:
Title: How to vertically align an image inside a div
<p>How can you align an image inside of a containing <code>div</code>?</p>
<h2>Example</h2>
<p>In my example, I need to vertically center the <code><img></code> in the <code><div></code> with <code>class ="frame</code>":</p>
<pre><code><div class="frame" style="height: 25px;">
<img src="http://jsfiddle.net/img/logo.png" />
</div>
</code></pre>
<p><code>.frame</code>'s height is fixed and the image's height is unknown. I can add new elements in <code>.frame</code> if that's the only solution. I'm trying to do this on Internet Explorer 7 and later, WebKit, Gecko.</p>
<p>See the jsfiddle <a href="http://jsfiddle.net/4RPFa/61/" rel="noreferrer">here</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.frame {
height: 25px; /* Equals maximum image height */
line-height: 25px;
width: 160px;
border: 1px solid red;
text-align: center;
margin: 1em 0;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=15 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=13 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=11 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=9 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=7 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=5 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=3 />
</div></code></pre>
</div>
</div>
</p> | <p>The only (and the best cross-browser) way as I know is to use an <code>inline-block</code> helper with <code>height: 100%</code> and <code>vertical-align: middle</code> on both elements.</p>
<p>So there is a solution: <a href="http://jsfiddle.net/kizu/4RPFa/4570/" rel="noreferrer">http://jsfiddle.net/kizu/4RPFa/4570/</a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.frame {
height: 25px; /* Equals maximum image height */
width: 160px;
border: 1px solid red;
white-space: nowrap; /* This is required unless you put the helper span closely near the img */
text-align: center;
margin: 1em 0;
}
.helper {
display: inline-block;
height: 100%;
vertical-align: middle;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="frame">
<span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />
</div>
<div class="frame">
<span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />
</div>
<div class="frame">
<span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />
</div>
<div class="frame">
<span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />
</div>
<div class="frame">
<span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=17px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=15px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=13px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=11px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=9px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=7px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=5px />
</div>
<div class="frame">
<span class="helper"></span>
<img src="http://jsfiddle.net/img/logo.png" height=3px />
</div></code></pre>
</div>
</div>
</p>
<p>Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:</p>
<p>The solution with <code>:before</code> and <code>expression()</code> for Internet Explorer: <a href="http://jsfiddle.net/kizu/4RPFa/4571/" rel="noreferrer">http://jsfiddle.net/kizu/4RPFa/4571/</a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.frame {
height: 25px; /* Equals maximum image height */
width: 160px;
border: 1px solid red;
white-space: nowrap;
text-align: center;
margin: 1em 0;
}
.frame:before,
.frame_before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}
/* Move this to conditional comments */
.frame {
list-style:none;
behavior: expression(
function(t){
t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');
t.runtimeStyle.behavior = 'none';
}(this)
);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div></code></pre>
</div>
</div>
</p>
<hr>
<p>How it works:</p>
<ol>
<li><p>When you have two <code>inline-block</code> elements near each other, you can align each to other's side, so with <code>vertical-align: middle</code> you'll get something like this:</p>
<p><img src="https://i.stack.imgur.com/XIFPv.png" alt="Two aligned blocks"></p></li>
<li><p>When you have a block with fixed height (in <code>px</code>, <code>em</code> or another absolute unit), you can set the height of inner blocks in <code>%</code>.</p></li>
<li>So, adding one <code>inline-block</code> with <code>height: 100%</code> in a block with fixed height would align another <code>inline-block</code> element in it (<code><img/></code> in your case) vertically near it.</li>
</ol> | {
"question_id": 7273338,
"question_date": "2011-09-01T16:25:51.283Z",
"question_score": 1691,
"tags": "css|image|vertical-alignment",
"answer_id": 7310398,
"answer_date": "2011-09-05T16:04:27.090Z",
"answer_score": 2297
} |
Please answer the following Stack Overflow question:
Title: How do I configure git to ignore some files locally?
<p>Can I ignore files locally without polluting the global git config for everyone else? I have untracked files that are spam in my git status but I don't want to commit git config changes for every single little random untracked file I have in my local branches.</p> | <p>From <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">the relevant Git documentation</a>:</p>
<blockquote>
<p>Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the <code>$GIT_DIR/info/exclude</code> file.</p>
</blockquote>
<p>The <code>.git/info/exclude</code> file has the same format as any <code>.gitignore</code> file. Another option is to set <code>core.excludesFile</code> to the name of a file containing global patterns.</p>
<p>Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:</p>
<pre><code>git update-index --assume-unchanged <file-list>
</code></pre>
<p><em>Note on <code>$GIT_DIR</code></em>: This is a notation used <a href="https://git-scm.com/docs/git-rev-parse#_options_for_files" rel="noreferrer">all over</a> the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.</p>
<hr>
<p><strong>Edit</strong>: Another way is to use:</p>
<pre><code>git update-index --skip-worktree <file-list>
</code></pre>
<p>Reverse it by:</p>
<pre><code>git update-index --no-skip-worktree <file-list>
</code></pre> | {
"question_id": 1753070,
"question_date": "2009-11-18T01:36:47.597Z",
"question_score": 1691,
"tags": "git|ignore|gitignore",
"answer_id": 1753078,
"answer_date": "2009-11-18T01:38:18.813Z",
"answer_score": 2324
} |
Please answer the following Stack Overflow question:
Title: How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
<p>I am trying to use <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> as my all-in-one tool edit, run, compile, etc.</p>
<p>I have <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine#Execution_environment" rel="noreferrer">JRE</a> installed, and I have setup my path variable to the <code>.../bin</code> directory.</p>
<p>When I run my "Hello world" in Notepad++, I get this message:</p>
<pre class="lang-none prettyprint-override"><code>java.lang.UnsupportedClassVersionError: test_hello_world :
Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
.........................................
</code></pre>
<p>I think the problem here is about versions; some versions of Java may be old or too new.</p>
<ol>
<li>How do I fix it?</li>
<li>Should I install the JDK, and setup my path variable to the JDK instead of JRE?</li>
<li>What is the difference between the <code>PATH</code> variable in JRE or JDK?</li>
</ol> | <p>The version number shown describes the version of the JRE the class file is compatible with.</p>
<p>The reported major numbers are:</p>
<pre class="lang-none prettyprint-override"><code>Java SE 18 = 62,
Java SE 17 = 61,
Java SE 16 = 60,
Java SE 15 = 59,
Java SE 14 = 58,
Java SE 13 = 57,
Java SE 12 = 56,
Java SE 11 = 55,
Java SE 10 = 54,
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
</code></pre>
<p>(Source: <a href="https://en.wikipedia.org/wiki/Java_class_file#General_layout" rel="nofollow noreferrer">Wikipedia</a>)</p>
<p>To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.</p>
<p>For example, in order to generate class files compatible with Java 1.4, use the following command line:</p>
<pre class="lang-none prettyprint-override"><code>javac -target 1.4 HelloWorld.java
</code></pre>
<p>With newer versions of the Java compiler you are likely to get a warning about the bootstrap class path not being set. More information about this error is available in a blog post <em><a href="https://blogs.oracle.com/darcy/entry/bootclasspath_older_source" rel="nofollow noreferrer">New javac warning for setting an older source without bootclasspath</a></em>.</p> | {
"question_id": 10382929,
"question_date": "2012-04-30T11:28:24.877Z",
"question_score": 1686,
"tags": "java|jvm|incompatibility|unsupported-class-version",
"answer_id": 11432195,
"answer_date": "2012-07-11T11:59:50.970Z",
"answer_score": 2069
} |
Please answer the following Stack Overflow question:
Title: What's the canonical way to check for type in Python?
<p>How do I check if an object is of a given type, or if it inherits from a given type?</p>
<p>How do I check if the object <code>o</code> is of type <code>str</code>?</p>
<hr />
<p><sub>Beginners often wrongly expect the string to <em>already be</em> "a number" - either expecting Python 3.x <code>input</code> to convert type, or expecting that a string like <code>'1'</code> is <em>also simultaneously</em> an integer. This is the wrong canonical for those questions. Please carefully read the question and then use <a href="https://stackoverflow.com/questions/354038">How do I check if a string represents a number (float or int)?</a>, <a href="https://stackoverflow.com/questions/20449427/">How can I read inputs as numbers?</a> and/or <a href="https://stackoverflow.com/questions/23294658/">Asking the user for input until they give a valid response</a> as appropriate.</sub></p> | <p>Use <a href="https://docs.python.org/library/functions.html#isinstance" rel="noreferrer"><code>isinstance</code></a> to check if <code>o</code> is an instance of <code>str</code> or any subclass of <code>str</code>:</p>
<pre><code>if isinstance(o, str):
</code></pre>
<p>To check if the type of <code>o</code> is exactly <code>str</code>, <em>excluding subclasses of <code>str</code></em>:</p>
<pre><code>if type(o) is str:
</code></pre>
<p>Another alternative to the above:</p>
<pre><code>if issubclass(type(o), str):
</code></pre>
<p>See <a href="http://docs.python.org/library/functions.html" rel="noreferrer">Built-in Functions</a> in the Python Library Reference for relevant information.</p>
<hr />
<h4>Checking for strings in Python 2</h4>
<p>For Python 2, this is a better way to check if <code>o</code> is a string:</p>
<pre><code>if isinstance(o, basestring):
</code></pre>
<p>because this will also catch Unicode strings. <a href="https://docs.python.org/2/library/functions.html#unicode" rel="noreferrer"><code>unicode</code></a> is not a subclass of <code>str</code>; whereas, both <code>str</code> and <code>unicode</code> are subclasses of <a href="https://docs.python.org/2/library/functions.html#basestring" rel="noreferrer"><code>basestring</code></a>. In Python 3, <code>basestring</code> no longer exists since there's <a href="https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit" rel="noreferrer">a strict separation</a> of strings (<a href="https://docs.python.org/3/library/functions.html#func-str" rel="noreferrer"><code>str</code></a>) and binary data (<a href="https://docs.python.org/3/library/functions.html#func-bytes" rel="noreferrer"><code>bytes</code></a>).</p>
<p>Alternatively, <code>isinstance</code> accepts a tuple of classes. This will return <code>True</code> if <code>o</code> is an instance of any subclass of any of <code>(str, unicode)</code>:</p>
<pre><code>if isinstance(o, (str, unicode)):
</code></pre> | {
"question_id": 152580,
"question_date": "2008-09-30T11:00:10.140Z",
"question_score": 1686,
"tags": "python|types",
"answer_id": 152596,
"answer_date": "2008-09-30T11:07:45.597Z",
"answer_score": 1990
} |
Please answer the following Stack Overflow question:
Title: How do I debug Node.js applications?
<p>How do I debug a Node.js server application?</p>
<p>Right now I'm mostly using <em>alert debugging</em> with print statements like this:</p>
<pre><code>sys.puts(sys.inspect(someVariable));
</code></pre>
<p>There must be a better way to debug. I know that <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Google Chrome</a> has a command-line debugger. Is this debugger available for Node.js as well?</p> | <p>The <a href="http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29" rel="noreferrer">V8</a> debugger released as part of the Google <a href="http://code.google.com/p/chromedevtools/" rel="noreferrer">Chrome Developer Tools</a> can be used to debug Node.js scripts. A detailed explanation of how this works can be found in the <a href="https://github.com/nodejs/node/wiki/Using-Eclipse-as-Node-Applications-Debugger" rel="noreferrer">Node.js GitHub wiki</a>.</p> | {
"question_id": 1911015,
"question_date": "2009-12-15T22:50:07.870Z",
"question_score": 1685,
"tags": "javascript|node.js|debugging|google-chrome-devtools",
"answer_id": 2536734,
"answer_date": "2010-03-29T08:57:06.560Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: What is the meaning of single and double underscore before an object name?
<p>What do single and double leading underscores before an object's name represent in Python?</p> | <h2>Single Underscore</h2>
<p>In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not <em>enforced</em> in any way.
Using leading underscores for functions in a module indicates it should not be imported from somewhere else.</p>
<p>From the <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP-8</a> style guide:</p>
<blockquote>
<p><code>_single_leading_underscore</code>: weak "internal use" indicator. E.g. <code>from M import *</code> does not import objects whose name starts with an underscore.</p>
</blockquote>
<h2>Double Underscore (Name Mangling)</h2>
<p>From <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="noreferrer">the Python docs</a>:</p>
<blockquote>
<p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with <code>_classname__spam</code>, where <code>classname</code> is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.</p>
</blockquote>
<p>And a warning from the same page:</p>
<blockquote>
<p>Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; <em>it still is possible for a determined soul to access or modify a variable that is considered private.</em></p>
</blockquote>
<h2>Example</h2>
<pre><code>>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
</code></pre> | {
"question_id": 1301346,
"question_date": "2009-08-19T17:11:57.037Z",
"question_score": 1681,
"tags": "python|oop|naming-conventions|identifier",
"answer_id": 1301369,
"answer_date": "2009-08-19T17:15:53.427Z",
"answer_score": 1468
} |
Please answer the following Stack Overflow question:
Title: What is the difference between const int*, const int * const, and int const *?
<p>I always mess up how to use <code>const int*</code>, <code>const int * const</code>, and <code>int const *</code> correctly. Is there a set of rules defining what you can and cannot do?</p>
<p>I want to know all the do's and all don'ts in terms of assignments, passing to the functions, etc.</p> | <p>Read it backwards (as driven by <a href="http://c-faq.com/decl/spiral.anderson.html" rel="noreferrer">Clockwise/Spiral Rule</a>):</p>
<ul>
<li><code>int*</code> - pointer to int</li>
<li><code>int const *</code> - pointer to const int</li>
<li><code>int * const</code> - const pointer to int</li>
<li><code>int const * const</code> - const pointer to const int</li>
</ul>
<p>Now the first <code>const</code> can be on either side of the type so:</p>
<ul>
<li><code>const int *</code> == <code>int const *</code></li>
<li><code>const int * const</code> == <code>int const * const</code></li>
</ul>
<p>If you want to go really crazy you can do things like this:</p>
<ul>
<li><code>int **</code> - pointer to pointer to int</li>
<li><code>int ** const</code> - a const pointer to a pointer to an int</li>
<li><code>int * const *</code> - a pointer to a const pointer to an int</li>
<li><code>int const **</code> - a pointer to a pointer to a const int</li>
<li><code>int * const * const</code> - a const pointer to a const pointer to an int</li>
<li>...</li>
</ul>
<p>And to make sure we are clear on the meaning of <code>const</code>:</p>
<pre><code>int a = 5, b = 10, c = 15;
const int* foo; // pointer to constant int.
foo = &a; // assignment to where foo points to.
/* dummy statement*/
*foo = 6; // the value of a can´t get changed through the pointer.
foo = &b; // the pointer foo can be changed.
int *const bar = &c; // constant pointer to int
// note, you actually need to set the pointer
// here because you can't change it later ;)
*bar = 16; // the value of c can be changed through the pointer.
/* dummy statement*/
bar = &a; // not possible because bar is a constant pointer.
</code></pre>
<p><code>foo</code> is a variable pointer to a constant integer. This lets you change what you point to but not the value that you point to. Most often this is seen with C-style strings where you have a pointer to a <code>const char</code>. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed.</p>
<p><code>bar</code> is a constant or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a <code>T* const</code> pointer unless you need to allow <code>NULL</code> pointers.</p> | {
"question_id": 1143262,
"question_date": "2009-07-17T13:28:09.233Z",
"question_score": 1679,
"tags": "c++|c|pointers|constants|c++-faq",
"answer_id": 1143272,
"answer_date": "2009-07-17T13:29:58.390Z",
"answer_score": 2657
} |
Please answer the following Stack Overflow question:
Title: How are parameters sent in an HTTP POST request?
<p>In an HTTP <strong>GET</strong> request, parameters are sent as a <strong><em>query string</em></strong>:</p>
<pre>http://example.com/page<b><i>?parameter=value&also=another</i></b></pre>
<p>In an HTTP <strong>POST</strong> request, the parameters are not sent along with the URI.</p>
<p><strong><em>Where are the values?</em></strong> In the request header? In the request body? What does it look like?</p> | <p>The values are sent in the request body, in the format that the content type specifies.</p>
<p>Usually the content type is <code>application/x-www-form-urlencoded</code>, so the request body uses the same format as the query string:</p>
<pre><code>parameter=value&also=another
</code></pre>
<p>When you use a file upload in the form, you use the <code>multipart/form-data</code> encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.</p> | {
"question_id": 14551194,
"question_date": "2013-01-27T19:19:07.627Z",
"question_score": 1678,
"tags": "http|post|parameters|request|uri",
"answer_id": 14551320,
"answer_date": "2013-01-27T19:32:10.950Z",
"answer_score": 1411
} |
Please answer the following Stack Overflow question:
Title: How do I properly force a Git push?
<p>I've set up a remote non-bare "main" repo and cloned it to my computer. I made some local changes, updated my local repository, and pushed the changes back to my remote repo. Things were fine up to that point.</p>
<p>Now, I had to change something in the remote repo. Then I changed something in my local repo. I realized that the change to the remote repo was not needed. So I tried to <code>git push</code> from my local repo to my remote repo, but I got an error like:</p>
<blockquote>
<p>To prevent you from losing history, non-fast-forward updates were
rejected Merge the remote changes before pushing again. See the 'Note
about fast-forwards' section of <code>git push --help</code> for details.</p>
</blockquote>
<p>I thought that probably a</p>
<pre><code>git push --force
</code></pre>
<p>would force my local copy to push changes to the remote one and make it the same. <strong>It does force the update</strong>, but when I go back to the remote repo and make a commit, I notice that the files contain outdated changes (ones that the main remote repo previously had).</p>
<p>As I mentioned in the <a href="https://stackoverflow.com/questions/5509543/how-do-i-properly-force-a-git-push#comment6275726_5509588">comments to one of the answers</a>:</p>
<blockquote>
<p>[I] tried forcing, but when going back to master server to save the changes, i get outdated staging. Thus, when i commit the repositories are not the same. And when i try to use git push again, i get the same error.</p>
</blockquote>
<p>How can I fix this issue?</p> | <p>Just do:</p>
<pre><code>git push origin <your_branch_name> --force
</code></pre>
<p>or if you have a specific repo:</p>
<pre><code>git push https://git.... --force
</code></pre>
<p>This will delete your previous commit(s) and push your current one.</p>
<p>It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...</p>
<h3>Short flag</h3>
<p>Also note that <code>-f</code> is short for <code>--force</code>, so</p>
<pre><code>git push origin <your_branch_name> -f
</code></pre>
<p>will also work.</p> | {
"question_id": 5509543,
"question_date": "2011-04-01T05:35:54.763Z",
"question_score": 1676,
"tags": "git|push|git-push|git-non-bare-repository",
"answer_id": 12610763,
"answer_date": "2012-09-26T21:31:33.550Z",
"answer_score": 2929
} |
Please answer the following Stack Overflow question:
Title: Event binding on dynamically created elements?
<p>I have a bit of code where I am looping through all the select boxes on a page and binding a <code>.hover</code> event to them to do a bit of twiddling with their width on <code>mouse on/off</code>.</p>
<p>This happens on page ready and works just fine.</p>
<p>The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.</p>
<p>I have found this plugin (<a href="http://brandonaaron.net/docs/livequery/#getting-started" rel="noreferrer">jQuery Live Query Plugin</a>), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.</p> | <p><strong>As of jQuery 1.7</strong> you should use <a href="https://api.jquery.com/on/#on-events-selector-data-handler" rel="noreferrer"><code>jQuery.fn.on</code></a> with the selector parameter filled:</p>
<pre><code>$(staticAncestors).on(eventName, dynamicChild, function() {});
</code></pre>
<p><em>Explanation:</em></p>
<p>This is called event delegation and works as followed. The event is attached to a static parent (<code>staticAncestors</code>) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (<code>dynamicChild</code>). When there is a match then your custom handler function is executed.</p>
<hr />
<p><strong>Prior to this</strong>, the recommended approach was to use <a href="http://api.jquery.com/live" rel="noreferrer"><code>live()</code></a>:</p>
<pre><code>$(selector).live( eventName, function(){} );
</code></pre>
<p>However, <code>live()</code> was deprecated in 1.7 in favour of <code>on()</code>, and completely removed in 1.9. The <code>live()</code> signature:</p>
<pre><code>$(selector).live( eventName, function(){} );
</code></pre>
<p>... can be replaced with the following <a href="http://api.jquery.com/on/" rel="noreferrer"><code>on()</code></a> signature:</p>
<pre><code>$(document).on( eventName, selector, function(){} );
</code></pre>
<hr />
<p>For example, if your page was dynamically creating elements with the class name <code>dosomething</code> you would bind the event to <strong>a parent which already exists</strong> (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is <code>document</code>. Though bear in mind <a href="https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document"><code>document</code> may not be the most efficient option</a>.</p>
<pre><code>$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
</code></pre>
<p>Any parent that exists at the time the event is bound is fine. For example</p>
<pre><code>$('.buttons').on('click', 'button', function(){
// do something here
});
</code></pre>
<p>would apply to</p>
<pre><code><div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
</code></pre> | {
"question_id": 203198,
"question_date": "2008-10-14T23:25:19.113Z",
"question_score": 1675,
"tags": "javascript|jquery|events|unobtrusive-javascript",
"answer_id": 1207393,
"answer_date": "2009-07-30T15:34:49.733Z",
"answer_score": 2506
} |
Please answer the following Stack Overflow question:
Title: How can I merge multiple commits onto another branch as a single squashed commit?
<p>I have a remote Git server, here is the scenario which I want to perform:</p>
<ul>
<li><p>For each bug/feature I create a different Git branch</p></li>
<li><p>I keep on committing my code in that Git branch with un-official Git messages</p></li>
<li><p>In top repository we have to do one commit for one bug with official Git message</p></li>
</ul>
<p>So how can I merge my branch to remote branch so that they get just one commit for all my check-ins (I even want to provide commit message for this)?</p> | <p>Say your bug fix branch is called <code>bugfix</code> and you want to merge it into <code>master</code>:</p>
<pre><code>git checkout master
git merge --squash bugfix
git commit
</code></pre>
<p>This will take all the commits from the <code>bugfix</code> branch, squash them into 1 commit, and merge it with your <code>master</code> branch.</p>
<hr />
<p><strong>Explanation</strong>:</p>
<pre><code>git checkout master
</code></pre>
<p>Switches to your <code>master</code> branch.</p>
<pre><code>git merge --squash bugfix
</code></pre>
<p>Takes all commits from the <code>bugfix</code> branch and groups it for a 1 commit with your current branch.<br />
<em>(no merge commit appears; you could resolve conflicts manually before following commit)</em></p>
<pre><code>git commit
</code></pre>
<p>Creates a single commit from the merged changes.</p>
<p>Omitting the <code>-m</code> parameter lets you modify a draft commit message containing every message from your squashed commits before finalizing your commit.</p> | {
"question_id": 5308816,
"question_date": "2011-03-15T07:47:44.943Z",
"question_score": 1675,
"tags": "git|git-merge|git-squash",
"answer_id": 5309051,
"answer_date": "2011-03-15T08:16:45.477Z",
"answer_score": 2682
} |
Please answer the following Stack Overflow question:
Title: How does the Java 'for each' loop work?
<p>Consider:</p>
<pre><code>List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
</code></pre>
<pre><code>for (String item : someList) {
System.out.println(item);
}
</code></pre>
<p>What would the equivalent <code>for</code> loop look like without using the <em>for each</em> syntax?</p> | <pre><code>for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
</code></pre>
<p>Note that if you need to use <code>i.remove();</code> in your loop, or access the actual iterator in some way, you cannot use the <code>for ( : )</code> idiom, since the actual iterator is merely inferred.</p>
<p>As was noted by Denis Bueno, this code works for any object that implements the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html" rel="noreferrer"><code>Iterable</code> interface</a>.</p>
<p>Also, if the right-hand side of the <code>for (:)</code> idiom is an <code>array</code> rather than an <code>Iterable</code> object, the internal code uses an int index counter and checks against <code>array.length</code> instead. See the <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2" rel="noreferrer">Java Language Specification</a>.</p> | {
"question_id": 85190,
"question_date": "2008-09-17T16:44:32.360Z",
"question_score": 1674,
"tags": "java|foreach|syntactic-sugar",
"answer_id": 85206,
"answer_date": "2008-09-17T16:46:28.283Z",
"answer_score": 1281
} |
Please answer the following Stack Overflow question:
Title: From an array of objects, extract value of a property as array
<p>I have JavaScript object array with the following structure:</p>
<pre><code>objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
</code></pre>
<p>I want to extract a field from each object, and get an array containing the values, for example field <code>foo</code> would give array <code>[ 1, 3, 5 ]</code>.</p>
<p>I can do this with this trivial approach:</p>
<pre><code>function getFields(input, field) {
var output = [];
for (var i=0; i < input.length ; ++i)
output.push(input[i][field]);
return output;
}
var result = getFields(objArray, "foo"); // returns [ 1, 3, 5 ]
</code></pre>
<p>Is there a more elegant or idiomatic way to do this, so that a custom utility function would be unnecessary?</p>
<hr>
<p>Note about <a href="https://stackoverflow.com/questions/6857468">suggested duplicate</a>, it covers how to convert a single <em>object</em> to an array.</p> | <p>Here is a shorter way of achieving it:</p>
<pre><code>let result = objArray.map(a => a.foo);
</code></pre>
<p>OR</p>
<pre><code>let result = objArray.map(({ foo }) => foo)
</code></pre>
<p>You can also check <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>Array.prototype.map()</code></a>.</p> | {
"question_id": 19590865,
"question_date": "2013-10-25T13:13:03.290Z",
"question_score": 1672,
"tags": "javascript|javascript-objects",
"answer_id": 46694321,
"answer_date": "2017-10-11T17:33:48.910Z",
"answer_score": 2316
} |
Please answer the following Stack Overflow question:
Title: Rename package in Android Studio
<p>How do you rename packages in the new IDE Android Studio, based on IntelliJ IDEA?</p>
<p>Is there an automatic refactoring included? </p>
<p>I want to make bulk refactoring, but I don't know how. I worked two years with Eclipse and in Eclipse it's a one-click operation.</p> | <h2>In Android Studio, you can do this:</h2>
<p>For example, if you want to change <code>com.example.app</code> to <code>my.awesome.game</code>, then:</p>
<ol>
<li><p>In your <em><strong>Project panel</strong></em>, click on the little gear icon ( <img src="https://i.stack.imgur.com/lkezT.png" alt="Gears icon" /> )</p>
</li>
<li><p>Uncheck the <code>Compact Empty Middle Packages</code> option</p>
<p><img src="https://i.imgur.com/3j5pzNa.png" alt="Compact Empty Middle Packages" /></p>
</li>
<li><p>Your package directory will now be broken down into individual directories</p>
</li>
<li><p>Individually select each directory you want to rename, and:</p>
</li>
</ol>
<ul>
<li><p>Right-click on it</p>
</li>
<li><p>Select <code>Refactor</code></p>
</li>
<li><p>Click on <code>Rename</code></p>
</li>
<li><p>In the pop-up dialog, click on <code>Rename Package</code> instead of Rename Directory</p>
</li>
<li><p>Enter the new name and hit <strong>Refactor</strong></p>
</li>
<li><p>Click <strong>Do Refactor</strong> in the bottom</p>
</li>
<li><p>Allow a minute to let Android Studio update all changes</p>
</li>
<li><p><em>Note: When renaming <code>com</code> in Android Studio, it might give a warning. In such case, select</em> <strong>Rename All</strong></p>
<p><img src="https://i.imgur.com/PW9oZll.png" alt="Enter image description here" /></p>
</li>
</ul>
<ol start="5">
<li><p>Now open your <em><strong>Gradle Build File</strong></em> (<code>build.gradle</code> - Usually <code>app</code> or <code>mobile</code>). Update the <code>applicationId</code> in the <code>defaultConfig</code> to your new Package Name and Sync Gradle, if it hasn't already been updated automatically:</p>
<p><img src="https://i.imgur.com/hMx08b7.png" alt="Refactor Directories" /></p>
</li>
<li><p>You may need to change the <code>package=</code> attribute in your manifest.</p>
</li>
<li><p>Clean and Rebuild.</p>
<p><img src="https://i.stack.imgur.com/xBqWu.png" alt="Clean and Rebuild" /></p>
</li>
<li><p><em><strong>Done!</strong></em> Anyway, Android Studio needs to make this process a little simpler.</p>
</li>
</ol> | {
"question_id": 16804093,
"question_date": "2013-05-29T01:24:49.327Z",
"question_score": 1672,
"tags": "android-studio",
"answer_id": 29092698,
"answer_date": "2015-03-17T06:32:34.527Z",
"answer_score": 3416
} |
Please answer the following Stack Overflow question:
Title: How to loop through all enum values in C#?
<blockquote>
<p><strong>This question already has an answer here:</strong><br>
<a href="https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum">How do I enumerate an enum in C#?</a> <em>26 answers</em></p>
</blockquote>
<pre><code>public enum Foos
{
A,
B,
C
}
</code></pre>
<p>Is there a way to loop through the possible values of <code>Foos</code>?</p>
<p>Basically?</p>
<pre><code>foreach(Foo in Foos)
</code></pre> | <p>Yes you can use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.enum.getvalues" rel="noreferrer"><code>GetValues</code></a> method:</p>
<pre><code>var values = Enum.GetValues(typeof(Foos));
</code></pre>
<p>Or the typed version:</p>
<pre><code>var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
</code></pre>
<p>I long ago added a helper function to my private library for just such an occasion:</p>
<pre><code>public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
</code></pre>
<p>Usage:</p>
<pre><code>var values = EnumUtil.GetValues<Foos>();
</code></pre> | {
"question_id": 972307,
"question_date": "2009-06-09T20:25:04.640Z",
"question_score": 1672,
"tags": "c#|.net|enums|language-features",
"answer_id": 972323,
"answer_date": "2009-06-09T20:28:22.997Z",
"answer_score": 2379
} |
Please answer the following Stack Overflow question:
Title: How do I print to stderr in Python?
<p>There are several ways to write to stderr:</p>
<pre><code>print >> sys.stderr, "spam" # Python 2 only.
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
</code></pre>
<p>What are the differences between these methods? Which method should be preferred?</p> | <p>I found this to be the only one short, flexible, portable and readable:</p>
<pre><code># This line only if you still care about Python2
from __future__ import print_function
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
</code></pre>
<p>The optional function <code>eprint</code> saves some repetition. It can be used in the same way as the standard <code>print</code> function:</p>
<pre><code>>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz
</code></pre> | {
"question_id": 5574702,
"question_date": "2011-04-07T00:59:10.980Z",
"question_score": 1671,
"tags": "python|printing|stderr",
"answer_id": 14981125,
"answer_date": "2013-02-20T13:31:54.223Z",
"answer_score": 1454
} |
Please answer the following Stack Overflow question:
Title: Hide scroll bar, but while still being able to scroll
<p>I want to be able to scroll through the whole page, but without the scrollbar being shown.</p>
<p>In Google Chrome it's:</p>
<pre><code>::-webkit-scrollbar {
display: none;
}
</code></pre>
<p>But Mozilla Firefox and Internet Explorer don't seem to work like that.</p>
<p>I also tried this in CSS:</p>
<pre><code>overflow: hidden;
</code></pre>
<p>That does hide the scrollbar, but I can't scroll any more.</p>
<p>Is there a way I can remove the scrollbar while still being able to scroll the whole page?</p>
<p>With just CSS or HTML, please.</p> | <p>Just a test which is working fine.</p>
<pre class="lang-css prettyprint-override"><code>#parent{
width: 100%;
height: 100%;
overflow: hidden;
}
#child{
width: 100%;
height: 100%;
overflow-y: scroll;
padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */
box-sizing: content-box; /* So the width will be 100% + 17px */
}
</code></pre>
<p><strong><a href="http://jsfiddle.net/5GCsJ/954/" rel="noreferrer">Working Fiddle</a></strong></p>
<h3>JavaScript:</h3>
<p>Since the scrollbar width differs in different browsers, it is better to handle it with JavaScript. If you do <code>Element.offsetWidth - Element.clientWidth</code>, the exact scrollbar width will show up.</p>
<p><strong><a href="http://jsfiddle.net/5GCsJ/4713/" rel="noreferrer">JavaScript Working Fiddle</a></strong></p>
<h2>Or</h2>
<p>Using <code>Position: absolute</code>,</p>
<pre class="lang-css prettyprint-override"><code>#parent{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#child{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: -17px; /* Increase/Decrease this value for cross-browser compatibility */
overflow-y: scroll;
}
</code></pre>
<p><strong><a href="http://jsfiddle.net/5GCsJ/2125/" rel="noreferrer">Working Fiddle</a></strong></p>
<p><a href="http://jsfiddle.net/5GCsJ/4714/" rel="noreferrer"><strong>JavaScript Working Fiddle</strong></a></p>
<h3>Information:</h3>
<p>Based on this answer, I created a <a href="https://github.com/kamlekar/slim-scroll" rel="noreferrer">simple scroll plugin</a>.</p> | {
"question_id": 16670931,
"question_date": "2013-05-21T13:11:37.403Z",
"question_score": 1669,
"tags": "html|css|google-chrome|internet-explorer|firefox",
"answer_id": 16671476,
"answer_date": "2013-05-21T13:37:22.267Z",
"answer_score": 1001
} |
Please answer the following Stack Overflow question:
Title: Stop setInterval call in JavaScript
<p>I am using <code>setInterval(fname, 10000);</code> to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? </p>
<p>I want the user to be able to stop the repeated refresh of data.</p> | <p><code>setInterval()</code> returns an interval ID, which you can pass to <code>clearInterval()</code>:</p>
<pre><code>var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
</code></pre>
<p>See the docs for <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval" rel="noreferrer"><code>setInterval()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval" rel="noreferrer"><code>clearInterval()</code></a>.</p> | {
"question_id": 109086,
"question_date": "2008-09-20T19:29:55.377Z",
"question_score": 1667,
"tags": "javascript|dom-events|setinterval",
"answer_id": 109091,
"answer_date": "2008-09-20T19:30:59.243Z",
"answer_score": 2564
} |
Please answer the following Stack Overflow question:
Title: startsWith() and endsWith() functions in PHP
<p>How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?</p>
<p>For example:</p>
<pre><code>$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
</code></pre> | <h2>PHP 8.0 and higher</h2>
<p>Since PHP 8.0 you can use the</p>
<p><code>str_starts_with</code>
<a href="https://www.php.net/manual/en/function.str-starts-with" rel="noreferrer">Manual</a>
and</p>
<p><code>str_ends_with</code> <a href="https://www.php.net/manual/en/function.str-ends-with" rel="noreferrer">Manual</a></p>
<h5>Example</h5>
<p><code>echo str_starts_with($str, '|');</code></p>
<h2>PHP before 8.0</h2>
<pre class="lang-php prettyprint-override"><code>function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
</code></pre>
<pre class="lang-php prettyprint-override"><code>function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}
</code></pre> | {
"question_id": 834303,
"question_date": "2009-05-07T12:14:27.567Z",
"question_score": 1667,
"tags": "php|string",
"answer_id": 834355,
"answer_date": "2009-05-07T12:24:25.640Z",
"answer_score": 1812
} |
Please answer the following Stack Overflow question:
Title: Make a Bash alias that takes a parameter?
<p>I used to use CShell (<a href="/questions/tagged/csh" class="post-tag" title="show questions tagged 'csh'" rel="tag">csh</a>), which lets you make an alias that takes a parameter. The notation was something like</p>
<pre><code>alias junk="mv \\!* ~/.Trash"
</code></pre>
<p>In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.</p> | <p>Bash alias does not directly accept parameters. You will have to create a function.</p>
<p><code>alias</code> does not accept parameters but a function can be called just like an alias. For example:</p>
<pre><code>myfunction() {
#do things with parameters like $1 such as
mv "$1" "$1.bak"
cp "$2" "$1"
}
myfunction old.conf new.conf #calls `myfunction`
</code></pre>
<p>By the way, Bash functions defined in your <code>.bashrc</code> and other files are available as commands within your shell. So for instance you can call the earlier function like this </p>
<pre><code>$ myfunction original.conf my.conf
</code></pre> | {
"question_id": 7131670,
"question_date": "2011-08-20T12:11:41.257Z",
"question_score": 1667,
"tags": "bash|alias",
"answer_id": 7131683,
"answer_date": "2011-08-20T12:15:04.200Z",
"answer_score": 2682
} |
Please answer the following Stack Overflow question:
Title: Get the values from the "GET" parameters (JavaScript)
<p>I have a URL with some GET parameters as follows:</p>
<pre><code>www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
</code></pre>
<p>I need to get the whole value of <code>c</code>. I tried to read the URL, but I got only <code>m2</code>. How do I do this using JavaScript?</p> | <p>JavaScript <em>itself</em> has nothing built in for handling query string parameters.</p>
<p>Code running in a (<a href="https://caniuse.com/url" rel="noreferrer">modern</a>) browser can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer"><code>URL</code> object</a> (a <a href="https://developer.mozilla.org/en-US/docs/Web/API" rel="noreferrer">Web API</a>). <code>URL</code> is also implemented by <a href="https://nodejs.org/api/url.html#the-whatwg-url-api" rel="noreferrer">Node.js</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>// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);</code></pre>
</div>
</div>
</p>
<hr />
<p>For older browsers (including Internet Explorer), you can use <a href="https://github.com/webcomponents/URL" rel="noreferrer">this polyfill</a>.</p>
<p>You could also use one for <a href="https://github.com/ungap/url-search-params" rel="noreferrer">URLSearchParams</a> and extract the query string to pass to it with <code>window.location.search.substring(1)</code>.</p>
<hr />
<p>You could also use the code from the original version of this answer that predates <code>URL</code>. The above polyfill is robust and well tested and I strongly recommend it over this though.</p>
<p>You could access <code>location.search</code>, which would give you from the <code>?</code> character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.</p>
<p>Then you can parse it with this:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair.shift());
var value = decodeURIComponent(pair.join("="));
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = value;
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], value];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(value);
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);</code></pre>
</div>
</div>
</p>
<p>You can get the query string from the URL of the current page with:</p>
<pre><code>var query = window.location.search.substring(1);
var qs = parse_query_string(query);
</code></pre> | {
"question_id": 979975,
"question_date": "2009-06-11T08:32:49.687Z",
"question_score": 1666,
"tags": "javascript|url|url-parameters",
"answer_id": 979995,
"answer_date": "2009-06-11T08:37:53.483Z",
"answer_score": 2579
} |
Please answer the following Stack Overflow question:
Title: What does "javascript:void(0)" mean?
<pre class="lang-html prettyprint-override"><code><a href="javascript:void(0)" id="loginlink">login</a>
</code></pre>
<p>I've seen such <code>href</code>s many times, but I don't know what exactly that means.</p> | <blockquote>
<p>The <code>void</code> operator evaluates the given
expression and then returns <code>undefined</code>.</p>
<p>The <code>void</code> operator is often used merely
to obtain the <code>undefined</code> primitive
value, usually using “<code>void(0)</code>” (which
is equivalent to “<code>void 0</code>”). In these
cases, the global variable <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined" rel="noreferrer"><code>undefined</code></a>
can be used instead (assuming it has
not been assigned to a non-default
value).</p>
</blockquote>
<p>An explanation is provided here: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void" rel="noreferrer"><code>void</code> operator</a>.</p>
<p>The reason you’d want to do this with the <code>href</code> of a link is that normally, a <code>javascript:</code> URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is <code>undefined</code>, then the browser stays on the same page. <code>void(0)</code> is just a short and simple script that evaluates to <code>undefined</code>.</p> | {
"question_id": 1291942,
"question_date": "2009-08-18T05:20:13.157Z",
"question_score": 1666,
"tags": "javascript|void",
"answer_id": 1291950,
"answer_date": "2009-08-18T05:23:10.093Z",
"answer_score": 1236
} |
Please answer the following Stack Overflow question:
Title: Proper way to declare custom exceptions in modern Python?
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p>
<p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an <code>Exception</code> object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p>
<p>I was tripped up by the following deprecation warning in Python 2.6.2:</p>
<pre><code>>>> class MyError(Exception):
... def __init__(self, message):
... self.message = message
...
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
</code></pre>
<p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/" rel="noreferrer">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p>
<p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p>
<p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p> | <p>Maybe I missed the question, but why not:</p>
<pre class="lang-py prettyprint-override"><code>class MyException(Exception):
pass
</code></pre>
<p>To override something (or pass extra args), do this:</p>
<pre class="lang-py prettyprint-override"><code>class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super().__init__(message)
# Now for your custom code...
self.errors = errors
</code></pre>
<p>That way you could pass dict of error messages to the second param, and get to it later with <code>e.errors</code>.</p>
<p>In Python 2, you have to use this slightly more complex form of <code>super()</code>:</p>
<pre class="lang-py prettyprint-override"><code>super(ValidationError, self).__init__(message)
</code></pre> | {
"question_id": 1319615,
"question_date": "2009-08-23T21:29:29.903Z",
"question_score": 1664,
"tags": "python|exception",
"answer_id": 1319675,
"answer_date": "2009-08-23T21:55:23.893Z",
"answer_score": 1727
} |
Please answer the following Stack Overflow question:
Title: What does the [Flags] Enum Attribute mean in C#?
<p>From time to time I see an enum like the following:</p>
<pre><code>[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
</code></pre>
<p>I don't understand what exactly the <code>[Flags]</code> attribute does.</p>
<p>Anyone have a good explanation or example they could post?</p> | <p>The <code>[Flags]</code> attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:</p>
<pre><code>var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
</code></pre>
<p>Note that the <code>[Flags]</code> attribute <strong>doesn't</strong> enable this by itself - all it does is allow a nice representation by the <code>.ToString()</code> method:</p>
<pre><code>enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
...
var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"
</code></pre>
<p>It is also important to note that <code>[Flags]</code> <strong>does not</strong> automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. </p>
<p>Incorrect declaration:</p>
<pre><code>[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
</code></pre>
<p>The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.</p>
<p>Here's an example of a correct declaration:</p>
<pre><code>[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
</code></pre>
<p>To retrieve the distinct values in your property, one can do this:</p>
<pre><code>if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
// Yellow is allowed...
}
</code></pre>
<p>or prior to .NET 4:</p>
<pre><code>if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
// Yellow is allowed...
}
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
// Green is allowed...
}
</code></pre>
<p><strong>Under the covers</strong></p>
<p>This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:</p>
<pre><code> Yellow: 00000001
Green: 00000010
Red: 00000100
Blue: 00001000
</code></pre>
<p>Similarly, after you've set your property <em>AllowedColors</em> to Red, Green and Blue using the binary bitwise OR <code>|</code> operator, <em>AllowedColors</em> looks like this:</p>
<pre><code>myProperties.AllowedColors: 00001110
</code></pre>
<p>So when you retrieve the value you are actually performing bitwise AND <code>&</code> on the values:</p>
<pre><code>myProperties.AllowedColors: 00001110
MyColor.Green: 00000010
-----------------------
00000010 // Hey, this is the same as MyColor.Green!
</code></pre>
<p><strong>The None = 0 value</strong></p>
<p>And regarding the use of <code>0</code> in your enumeration, quoting from MSDN:</p>
<pre><code>[Flags]
public enum MyColors
{
None = 0,
....
}
</code></pre>
<blockquote>
<p>Use None as the name of the flag enumerated constant whose value is zero. <strong>You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero.</strong> However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. </p>
</blockquote>
<p>You can find more info about the flags attribute and its usage at <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="noreferrer">msdn</a> and <a href="http://msdn.microsoft.com/en-us/library/ms229062.aspx" rel="noreferrer">designing flags at msdn</a></p> | {
"question_id": 8447,
"question_date": "2008-08-12T04:09:16.083Z",
"question_score": 1664,
"tags": "c#|enums|flags",
"answer_id": 8480,
"answer_date": "2008-08-12T05:10:46.427Z",
"answer_score": 2410
} |
Please answer the following Stack Overflow question:
Title: How can I convert a stack trace to a string?
<p>What is the easiest way to convert the result of <code>Throwable.getStackTrace()</code> to a string that depicts the stacktrace?</p> | <p>One can use the following method to convert an <code>Exception</code> stack trace to <code>String</code>. This class is available in <em>Apache commons-lang which is most common dependent library with many popular open sources</em></p>
<p><a href="http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html#getStackTrace(java.lang.Throwable)" rel="noreferrer"><code>org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)</code></a></p> | {
"question_id": 1149703,
"question_date": "2009-07-19T11:31:43.533Z",
"question_score": 1659,
"tags": "java|stack-trace|tostring",
"answer_id": 2109985,
"answer_date": "2010-01-21T14:39:54.360Z",
"answer_score": 1114
} |
Please answer the following Stack Overflow question:
Title: How to remove focus border (outline) around text/input boxes? (Chrome)
<p>Can anyone explain how to remove the orange or blue border (outline) around text/input boxes? I think it only happens on Chrome to show that the input box is active. Here's the input CSS I'm using:</p>
<pre class="lang-css prettyprint-override"><code>input {
background-color: transparent;
border: 0px solid;
height: 20px;
width: 160px;
color: #CCC;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/HSKYf.png" alt="Text box with blue outline and "Example" written in it"></p> | <p>This border is used to show that the element is focused (i.e. you can type in the input or press the button with Enter). You can remove it with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/outline" rel="noreferrer">outline</a> property, though:</p>
<pre class="lang-css prettyprint-override"><code>textarea:focus, input:focus{
outline: none;
}
</code></pre>
<p>You may want to add some other way for users to know what element has keyboard focus though for usability.</p>
<p>Chrome will also apply highlighting to other elements such as DIV's used as modals. To prevent the highlight on those and all other elements as well, you can do:</p>
<pre class="lang-css prettyprint-override"><code>*:focus {
outline: none;
}
</code></pre>
<hr />
<h3>⚠️ Accessibility warning</h3>
<p>Please notice that removing outline from input is an accessibility bad practice. Users using screen readers will not be able to see where their pointer is focused at. More <a href="https://www.a11yproject.com/posts/2013-01-25-never-remove-css-outlines/#:%7E:text=Using%20the%20CSS%20rule%20%3Afocus,with%20the%20link%20or%20control." rel="noreferrer">info at a11yproject</a></p> | {
"question_id": 3397113,
"question_date": "2010-08-03T13:49:03.267Z",
"question_score": 1656,
"tags": "css|google-chrome|input|focus|border",
"answer_id": 3397158,
"answer_date": "2010-08-03T13:52:36.100Z",
"answer_score": 2963
} |
Please answer the following Stack Overflow question:
Title: fatal error: Python.h: No such file or directory
<p>I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below:</p>
<pre class="lang-none prettyprint-override"><code>gcc -Wall utilsmodule.c -o Utilc
</code></pre>
<p>After executing the command, I get this error message:</p>
<pre><code>> utilsmodule.c:1:20: fatal error: Python.h: No such file or directory
compilation terminated.
</code></pre>
<p>I have tried all the suggested solutions over the internet but the problem still exists. I have no problem with <code>Python.h</code>. I managed to locate the file on my machine.</p> | <p>I managed to solve this issue and generate the .so file in one command </p>
<pre><code>gcc -shared -o UtilcS.so
-fPIC -I/usr/include/python2.7 -lpython2.7 utilsmodule.c
</code></pre> | {
"question_id": 21530577,
"question_date": "2014-02-03T15:00:16.653Z",
"question_score": 1656,
"tags": "python|gcc|python-c-api",
"answer_id": 21548557,
"answer_date": "2014-02-04T09:32:02.917Z",
"answer_score": 14
} |
Please answer the following Stack Overflow question:
Title: What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
<p>What's the difference if one web page starts with</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</code></pre>
<p>and If page starts with</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- without X-UA-Compatible meta -->
</code></pre>
<p>If there is no difference, I suppose I can just ignore the <code>X-UA-Compatible</code> meta header, since I just want it to be rendered in most standard mode in all IE versions.</p> | <p><em><strong>November 2021 Update</strong></em></p>
<p>As this answer is now 10+ years old my recommendation would be to leave this tag out altogether, unless you must support old legacy browsers.</p>
<p><em><strong>October 2015 Update</strong></em></p>
<p>This answer was posted several years ago and now the question really should be <em>should you even consider using the <code>X-UA-Compatible</code> tag on your site?</em> with the changes Microsoft has made to its browsers (more on those below).</p>
<p>Depending upon what Microsoft browsers you support you may not need to continue using the <code>X-UA-Compatible</code> tag. If you need to support IE9 or IE8, then I would recommend using the tag. If you only support the latest browsers (IE11 and/or Edge) then I would consider dropping this tag altogether. If you use Twitter Bootstrap and need to eliminate validation warnings, this tag must appear in its specified order. Additional info below:</p>
<hr />
<p>The <code>X-UA-Compatible</code> meta tag allows web authors to choose what version of Internet Explorer the page should be rendered as. IE11 has made changes to these modes; see the IE11 note below. <a href="https://www.microsoft.com/windows/browser-for-doing" rel="noreferrer">Microsoft Edge</a>, the browser that replaced IE11, only honors the <code>X-UA-Compatible</code> meta tag in certain circumstances. See the Microsoft Edge note below.</p>
<p>According to Microsoft, when using the <code>X-UA-Compatible</code> tag, it should be as high as possible in your document <code>head</code>:</p>
<blockquote>
<p>If you are using the X-UA-Compatible META tag you want to place it as close to the top of the page's HEAD as possible. Internet Explorer begins interpreting markup using the latest version. When Internet Explorer encounters the X-UA-Compatible META tag it starts over using the designated version's engine. This is a performance hit because the browser must stop and restart analyzing the content.</p>
</blockquote>
<p>Here are your options:</p>
<ul>
<li>"IE=edge"</li>
<li>"IE=11"</li>
<li>"IE=EmulateIE11"</li>
<li>"IE=10"</li>
<li>"IE=EmulateIE10"</li>
<li>"IE=9"</li>
<li>"IE=EmulateIE9</li>
<li>"IE=8"</li>
<li>"IE=EmulateIE8"</li>
<li>"IE=7"</li>
<li>"IE=EmulateIE7"</li>
<li>"IE=5"</li>
</ul>
<p>To attempt to understand what each means, here are definitions provided by Microsoft:</p>
<blockquote>
<p>Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:</p>
</blockquote>
<blockquote>
<ul>
<li>Edge mode tells Internet Explorer to display content in the highest mode available. With Internet Explorer 9, this is equivalent to IE9 mode. If a future release of Internet Explorer supported a higher compatibility mode, pages set to edge mode would appear in the highest mode supported by that version. Those same pages would still appear in IE9 mode when viewed with Internet Explorer 9.
Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE11 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE10 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE9 mode provides the highest support available for established and emerging industry standards, including the HTML5 (Working Draft), W3C Cascading Style Sheets Level 3 Specification (Working Draft), Scalable Vector Graphics (SVG) 1.0 Specification, and others. [Editor Note: IE 9 <em>does not</em> support CSS3 animations].</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE8 mode supports many established standards, including the W3C Cascading Style Sheets Level 2.1 Specification and the W3C Selectors API; it also provides limited support for the W3C Cascading Style Sheets Level 3 Specification (Working Draft) and other emerging standards.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE7 mode renders content as if it were displayed in standards mode by Internet Explorer 7, whether or not the page contains a <!DOCTYPE> directive.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Emulate IE9 mode tells Internet Explorer to use the <!DOCTYPE> directive to determine how to render content. Standards mode directives are displayed in IE9 mode and quirks mode directives are displayed in IE5 mode. Unlike IE9 mode, Emulate IE9 mode respects the <!DOCTYPE> directive.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Emulate IE8 mode tells Internet Explorer to use the <!DOCTYPE> directive to determine how to render content. Standards mode directives are displayed in IE8 mode and quirks mode directives are displayed in IE5 mode. Unlike IE8 mode, Emulate IE8 mode respects the <!DOCTYPE> directive.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Emulate IE7 mode tells Internet Explorer to use the <!DOCTYPE> directive to determine how to render content. Standards mode directives are displayed in Internet Explorer 7 standards mode and quirks mode directives are displayed in IE5 mode. Unlike IE7 mode, Emulate IE7 mode respects the <!DOCTYPE> directive. For many web sites, this is the preferred compatibility mode.</li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>IE5 mode renders content as if it were displayed in quirks mode by Internet Explorer 7, which is very similar to the way content was displayed in Microsoft Internet Explorer 5.</li>
</ul>
</blockquote>
<p><em><strong>IE10 NOTE:</strong></em> As of IE10, quirks mode behaves differently than it did in earlier versions of the browser. In IE9 and earlier versions, quirks mode restricted the webpage to the features supported by IE5.5. In IE10, quirks mode conforms to the differences specified in the HTML5 specification.</p>
<p>Personally, I always choose the <code>http-equiv="X-UA-Compatible" content="IE=edge"</code> meta tag, as older versions have plenty of bugs, and I do not want IE to decide to go into "Compatibility mode" and show my site as IE7 vs IE8 or 9. I always prefer the latest version of IE.</p>
<p><em><strong>IE11</strong></em></p>
<p>From <a href="https://docs.microsoft.com/previous-versions/windows/internet-explorer/ie-developer/dev-guides/bg182625(v=vs.85)#document-mode-changes" rel="noreferrer">Microsoft</a>:</p>
<blockquote>
<p>Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.</p>
</blockquote>
<blockquote>
<p>Use the HTML5 document type declaration to enable edge mode:</p>
</blockquote>
<blockquote>
<p><code><!doctype html></code></p>
</blockquote>
<blockquote>
<p>Edge mode was introduced in Internet Explorer 8 and has been available in each subsequent release. Note that the features supported by edge mode are limited to those supported by the specific version of the browser rendering the content.</p>
</blockquote>
<blockquote>
<p>Starting with IE11, document modes are deprecated and should no longer be used, except on a temporary basis. Make sure to update sites that rely on legacy features and document modes to reflect modern standards.</p>
</blockquote>
<blockquote>
<p>If you must target a specific document mode so that your site functions while you rework it to support modern standards and features, be aware that you're using a transitional feature, one that may not be available in future versions.</p>
</blockquote>
<blockquote>
<p>If you currently use the x-ua-compatible header to target a legacy document mode, it's possible your site won't reflect the best experience available with IE11.</p>
</blockquote>
<p><em><strong><a href="https://www.microsoft.com/windows/browser-for-doing" rel="noreferrer">Microsoft Edge</a> (Replacement for Internet Explorer that comes bundled with Windows 10)</strong></em></p>
<p>Information on <code>X-UA-Compatible</code> meta tag for the "Edge" version of IE. <a href="https://docs.microsoft.com/archive/blogs/ie/living-on-the-edge-our-next-step-in-helping-the-web-just-work" rel="noreferrer">From Microsoft</a>:</p>
<blockquote>
<p><strong>Introducing the “living” Edge document mode</strong></p>
</blockquote>
<blockquote>
<p>As we announced in August 2013, we are deprecating document modes as of IE11. With our latest platform updates, the need for legacy document modes is primarily limited to Enterprise legacy web apps. With new architectural changes, these legacy document modes will be isolated from changes in the “living” Edge mode, which will help to guarantee a much higher level of compatibility for customers who depend on those modes and help us move even faster on improvements in Edge. IE will still honor document modes served by intranet sites, sites on the Compatibility View list, and when used with Enterprise Mode only.</p>
</blockquote>
<blockquote>
<p>Public Internet sites will be rendered with the new Edge mode platform (ignoring X-UA-Compatible). It is our goal that Edge is the "living" document mode from here out and no further document modes will be introduced going forward.</p>
</blockquote>
<p>With the changes in Microsoft Edge to no longer support document modes in most cases, Microsoft has a <a href="https://github.com/MicrosoftEdge/static-code-scan" rel="noreferrer">tool</a> to scan your site to check and see if it has code that is not compatible with Edge.</p>
<p><em><strong>Chrome=1 Info for IE</strong></em></p>
<p>There is also <code>chrome=1</code> that you can use or use together with one of the above options like: <code><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"></code>. <code>chrome=1</code> is for Google's Chrome Frame which is defined as:</p>
<blockquote>
<p>Google Chrome Frame is an open source browser plug-in. Users who have the plug-in installed have access to Google Chrome's open web technologies and speedy JavaScript engine when they open pages in the browser.</p>
</blockquote>
<blockquote>
<p>Google Chrome Frame seamlessly enhances your browsing experience in Internet Explorer. It displays Google Chrome Frame enabled sites using Google Chrome’s rendering technology, giving you access to the latest HTML5 features as well as Google Chrome’s performance and security features without in any way interrupting your usual browser usage.</p>
</blockquote>
<blockquote>
<p>When Google Chrome Frame is installed, the web just gets better without you having to think about it.</p>
</blockquote>
<p>But for that plug-in to work you must use <code>chrome=1</code> in the <code>X-UA-Compatible</code> meta tag.</p>
<p>More info on Chrome Frame can be found <a href="https://www.chromium.org/developers/how-tos/chrome-frame-getting-started" rel="noreferrer">here</a>.</p>
<p><strong>Note:</strong> Google Chrome Frame only works for <a href="https://www.chromium.org/developers/how-tos/chrome-frame-getting-started" rel="noreferrer">IE6 through IE9</a>, and was retired on February 25, 2014. More info can be found <a href="https://blog.chromium.org/2013/06/retiring-chrome-frame.html" rel="noreferrer">here</a>. Thanks to @mck for the link.</p>
<p><em><strong>Validation:</strong></em></p>
<p><strong>HTML5</strong>:</p>
<p>The page will validate using the <a href="https://validator.w3.org/" rel="noreferrer">W3 Validator</a> only when using <code><meta http-equiv="X-UA-Compatible" content="IE=Edge"></code>. For other values it will throw the error: <code>A meta element with an http-equiv attribute whose value is X-UA-Compatible must have a content attribute with the value IE=edge.</code> In other words, if you have <code>IE=edge,chrome=1</code> it will not validate. I ignore this error completely as modern browsers simply ignore this line of code.</p>
<p>If you must have completely valid code then consider doing this on the server level by setting HTTP header. As a note, Microsoft says, <code>If both of these instructions are sent (meta and HTTP), the developer's preference (meta element) takes precedence over the web server setting (HTTP header).</code> See <a href="https://stackoverflow.com/a/8942455/825757">olibre's answer</a> or <a href="https://stackoverflow.com/a/15106164/825757">bitinn's answer</a> for more details on how to set an HTTP header.</p>
<p><strong>XHTML</strong></p>
<p>There isn't an issue with validation when using <code><meta http-equiv="X-UA-Compatible" content="IE=Edge" /></code> as long as the tag is properly closed (i.e. <code>/></code> vs <code>></code>).</p>
<p><strong>Twitter Bootstrap (V3 and below)</strong></p>
<p>This tag has been strongly recommended by the Bootstrap team since at least 2014, and <a href="https://github.com/twbs/bootlint" rel="noreferrer">Bootlint</a>, the linter authored by the twbs team continues to throw a <a href="https://github.com/twbs/bootlint/wiki/W002" rel="noreferrer">warning</a> when the tag is omitted. The linter distinguishes between warnings and errors, and as such the severity of omitting this tag may be considered minor.</p>
<hr />
<p>For more information on <code>X-UA-Compatible</code> see Microsoft's <a href="https://docs.microsoft.com/previous-versions/windows/internet-explorer/ie-developer/compatibility/cc288325(v=vs.85)" rel="noreferrer">Website Defining Document Compatibility</a>.</p>
<p>For more information on what IE supports see <a href="https://caniuse.com/" rel="noreferrer">caniuse.com</a>.</p>
<p>For more information on Twitter Bootstrap requirements, see the bootlint project <a href="https://github.com/twbs/bootlint/wiki/" rel="noreferrer">wiki page</a>.</p> | {
"question_id": 6771258,
"question_date": "2011-07-21T04:29:43.113Z",
"question_score": 1655,
"tags": "html|internet-explorer|browser|x-ua-compatible",
"answer_id": 6771584,
"answer_date": "2011-07-21T05:22:20.820Z",
"answer_score": 1883
} |
Please answer the following Stack Overflow question:
Title: Warning: push.default is unset; its implicit value is changing in Git 2.0
<p>I've been using Git for a while now and have recently downloaded an update only to find this warning message come up when I try to <code>push</code>.</p>
<pre><code>warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
</code></pre>
<p>I can obviously set it to one of the values mentioned, but what do they mean? What's the difference between <code>simple</code> and <code>matching</code>?</p>
<p>If I change it on one client will I need to do anything on other clients that I share repos with?</p> | <p>It's explained in great detail in <a href="https://git-scm.com/docs/git-config.html#git-config-pushdefault" rel="noreferrer">the docs</a>, but I'll try to summarize:</p>
<ul>
<li><p><code>matching</code> means <code>git push</code> will <strong>push all your local branches</strong> to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to. </p></li>
<li><p><code>simple</code> means <code>git push</code> will <strong>push only the current branch to the one that <code>git pull</code> would pull from</strong>, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.</p></li>
</ul>
<p>This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, <strong>it only affects what happens when you don't specify which branches you want to push</strong>.</p> | {
"question_id": 13148066,
"question_date": "2012-10-30T21:48:16.023Z",
"question_score": 1654,
"tags": "git|version-control|git-push",
"answer_id": 13148313,
"answer_date": "2012-10-30T22:11:49.733Z",
"answer_score": 2165
} |
Please answer the following Stack Overflow question:
Title: Random string generation with upper case letters and digits
<p>How do I generate a string of size N, made of numbers and uppercase English letters such as:</p>
<ul>
<li>6U1S75</li>
<li>4Z4UKK</li>
<li>U911K4</li>
</ul> | <p><strong>Answer in one line:</strong></p>
<pre><code>''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
</code></pre>
<p>or even shorter starting with Python 3.6 using <a href="https://docs.python.org/3/library/random.html#random.choices" rel="noreferrer"><code>random.choices()</code></a>:</p>
<pre><code>''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
</code></pre>
<p><strong>A cryptographically more secure version:</strong> <a href="https://stackoverflow.com/a/23728630/2213647">see this post</a></p>
<pre><code>''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
</code></pre>
<p><strong>In details, with a clean function for further reuse:</strong></p>
<pre><code>>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
</code></pre>
<p><strong>How does it work ?</strong></p>
<p>We import <code>string</code>, a module that contains sequences of common ASCII characters, and <code>random</code>, a module that deals with random generation.</p>
<p><code>string.ascii_uppercase + string.digits</code> just concatenates the list of characters representing uppercase ASCII chars and digits:</p>
<pre><code>>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
</code></pre>
<p>Then we use a list comprehension to create a list of 'n' elements:</p>
<pre><code>>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
</code></pre>
<p>In the example above, we use <code>[</code> to create the list, but we don't in the <code>id_generator</code> function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this <a href="https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/231855#231855">here</a>).</p>
<p>Instead of asking to create 'n' times the string <code>elem</code>, we will ask Python to create 'n' times a random character, picked from a sequence of characters:</p>
<pre><code>>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
</code></pre>
<p>Therefore <code>random.choice(chars) for _ in range(size)</code> really is creating a sequence of <code>size</code> characters. Characters that are randomly picked from <code>chars</code>:</p>
<pre><code>>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
</code></pre>
<p>Then we just join them with an empty string so the sequence becomes a string:</p>
<pre><code>>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
</code></pre> | {
"question_id": 2257441,
"question_date": "2010-02-13T12:23:58.213Z",
"question_score": 1651,
"tags": "python|string|random",
"answer_id": 2257449,
"answer_date": "2010-02-13T12:26:22.120Z",
"answer_score": 3086
} |
Please answer the following Stack Overflow question:
Title: How do I get the row count of a Pandas DataFrame?
<p>How do I get the number of rows of a pandas dataframe <code>df</code>?</p> | <p>For a dataframe <code>df</code>, one can use any of the following:</p>
<ul>
<li><code>len(df.index)</code></li>
<li><code>df.shape[0]</code></li>
<li><code>df[df.columns[0]].count()</code> (== <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.count.html" rel="noreferrer">number of non-NaN values</a> in first column)</li>
</ul>
<p><a href="https://i.stack.imgur.com/wEzue.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wEzue.png" alt="Performance plot" /></a></p>
<hr />
<p>Code to reproduce the plot:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
import perfplot
perfplot.save(
"out.png",
setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),
n_range=[2**k for k in range(25)],
kernels=[
lambda df: len(df.index),
lambda df: df.shape[0],
lambda df: df[df.columns[0]].count(),
],
labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"],
xlabel="Number of rows",
)
</code></pre> | {
"question_id": 15943769,
"question_date": "2013-04-11T08:14:08.400Z",
"question_score": 1646,
"tags": "python|pandas|dataframe",
"answer_id": 15943975,
"answer_date": "2013-04-11T08:24:29.633Z",
"answer_score": 2438
} |
Please answer the following Stack Overflow question:
Title: How does the vim "write with sudo" trick work?
<p>Many of you have probably seen the command that allows you to write on a file that needs root permission, even when you forgot to open vim with sudo:</p>
<pre><code>:w !sudo tee %
</code></pre>
<p>The thing is that I don't get what is exactly happening here.</p>
<p>I have already figured this:
<code>w</code> is for this</p>
<pre><code> *:w_c* *:write_c*
:[range]w[rite] [++opt] !{cmd}
Execute {cmd} with [range] lines as standard input
(note the space in front of the '!'). {cmd} is
executed like with ":!{cmd}", any '!' is replaced with
the previous command |:!|.
</code></pre>
<p>so it passes all the lines as standard input.</p>
<p>The <code>!sudo tee</code> part calls <code>tee</code> with administrator privileges.</p>
<p>For all to make sense, the <code>%</code> should output the filename (as a parameter for <code>tee</code>), but I can't find references on the help for this behavior.</p>
<p><strong>tl;dr</strong> Could someone help me dissect this command?</p> | <p>In <code>:w !sudo tee %</code>...</p>
<h2><code>%</code> means "the current file"</h2>
<p>As <a href="https://stackoverflow.com/a/2600852/211563">eugene y pointed out</a>, <code>%</code> does indeed mean "the current file name", which is passed to <code>tee</code> so that it knows which file to overwrite.</p>
<p>(In substitution commands, it's slightly different; as <code>:help :%</code> shows, it's <code>equal to 1,$ (the entire file)</code> (thanks to @Orafu for pointing out that this does not evaluate to the filename). For example, <code>:%s/foo/bar</code> means "<strong>in the current file</strong>, replace occurrences of <code>foo</code> with <code>bar</code>." If you highlight some text before typing <code>:s</code>, you'll see that the highlighted lines take the place of <code>%</code> as your substitution range.)</p>
<h2><code>:w</code> isn't updating your file</h2>
<p>One confusing part of this trick is that you might think <code>:w</code> is modifying your file, but it isn't. If you opened and modified <code>file1.txt</code>, then ran <code>:w file2.txt</code>, it would be a "save as"; <code>file1.txt</code> wouldn't be modified, but the current buffer contents would be sent to <code>file2.txt</code>.</p>
<p>Instead of <code>file2.txt</code>, you can <strong>substitute a shell command to receive the buffer contents</strong>. For instance, <code>:w !cat</code> will just display the contents.</p>
<p>If Vim wasn't run with sudo access, its <code>:w</code> can't modify a protected file, but if it passes the buffer contents to the shell, <strong>a command in the shell <em>can</em> be run with sudo</strong>. In this case, we use <code>tee</code>.</p>
<h2>Understanding tee</h2>
<p>As for <code>tee</code>, picture the <code>tee</code> command as a T-shaped pipe in a normal bash piping situation: it directs output to specified file(s) and <strong>also sends it to standard output</strong>, which can be captured by the next piped command. </p>
<p>For example, in <code>ps -ax | tee processes.txt | grep 'foo'</code>, the list of processes will be written to a text file <strong>and</strong> passed along to <code>grep</code>.</p>
<pre><code> +-----------+ tee +------------+
| | -------- | |
| ps -ax | -------- | grep 'foo' |
| | || | |
+-----------+ || +------------+
||
+---------------+
| |
| processes.txt |
| |
+---------------+
</code></pre>
<p>(Diagram created with <a href="http://www.asciiflow.com/" rel="noreferrer">Asciiflow</a>.)</p>
<p>See the <a href="http://ss64.com/bash/tee.html" rel="noreferrer"><code>tee</code> man page</a> for more info.</p>
<h2>Tee as a hack</h2>
<p>In the situation your question describes, <strong>using <code>tee</code> is a hack because we're ignoring half of what it does</strong>. <code>sudo tee</code> writes to our file and also sends the buffer contents to standard output, but <strong>we ignore standard output</strong>. We don't need to pass anything to another piped command in this case; we're just using <code>tee</code> as an alternate way of writing a file and so that we can call it with <code>sudo</code>.</p>
<h2>Making this trick easy</h2>
<p>You can add this to your <code>.vimrc</code> to make this trick easy-to-use: just type <code>:w!!</code>.</p>
<pre><code>" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %
</code></pre>
<p>The <code>> /dev/null</code> part <strong>explicitly</strong> throws away the standard output, since, as I said, we don't need to pass anything to another piped command.</p> | {
"question_id": 2600783,
"question_date": "2010-04-08T14:36:50.627Z",
"question_score": 1646,
"tags": "vim|sudo",
"answer_id": 7078429,
"answer_date": "2011-08-16T12:49:09.663Z",
"answer_score": 1866
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of the var keyword and when should I use it (or omit it)?
<blockquote>
<p><strong><em>NOTE</strong>: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.</em></p>
</blockquote>
<p>What exactly is the function of the <code>var</code> keyword in JavaScript, and what is the difference between</p>
<pre><code>var someNumber = 2;
var someFunction = function() { doSomething; }
var someObject = { }
var someObject.someProperty = 5;
</code></pre>
<p>and</p>
<pre><code>someNumber = 2;
someFunction = function() { doSomething; }
someObject = { }
someObject.someProperty = 5;
</code></pre>
<p>?</p>
<p>When would you use either one, and why/what does it do?</p> | <p>If you're in the global scope then there's not much difference. Read <a href="https://stackoverflow.com/a/1471738/1541051">Kangax's</a> answer for explanation</p>
<p>If you're in a function then <strong><code>var</code></strong> will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):</p>
<pre><code>// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
</code></pre>
<p>If you're not doing an assignment then you need to use <code>var</code>:</p>
<pre><code>var x; // Declare x
</code></pre> | {
"question_id": 1470488,
"question_date": "2009-09-24T08:54:04.117Z",
"question_score": 1645,
"tags": "javascript|keyword|ecmascript-5",
"answer_id": 1470494,
"answer_date": "2009-09-24T08:55:47.283Z",
"answer_score": 1407
} |
Please answer the following Stack Overflow question:
Title: Why not inherit from List<T>?
<p>When planning out my programs, I often start with a chain of thought like so:</p>
<blockquote>
<p>A football team is just a list of football players. Therefore, I should represent it with:</p>
<pre><code>var football_team = new List<FootballPlayer>();
</code></pre>
<p>The ordering of this list represent the order in which the players are listed in the roster.</p>
</blockquote>
<p>But I realize later that teams also have other properties, besides the mere list of players, that must be recorded. For example, the running total of scores this season, the current budget, the uniform colors, a <code>string</code> representing the name of the team, etc..</p>
<p>So then I think:</p>
<blockquote>
<p>Okay, a football team is just like a list of players, but additionally, it has a name (a <code>string</code>) and a running total of scores (an <code>int</code>). .NET does not provide a class for storing football teams, so I will make my own class. The most similar and relevant existing structure is <code>List<FootballPlayer></code>, so I will inherit from it:</p>
<pre><code>class FootballTeam : List<FootballPlayer>
{
public string TeamName;
public int RunningTotal
}
</code></pre>
</blockquote>
<p>But it turns out that <a href="https://stackoverflow.com/a/5376343/1042555">a guideline says you shouldn't inherit from <code>List<T></code></a>. I'm thoroughly confused by this guideline in two respects.</p>
<h2>Why not?</h2>
<p>Apparently <a href="https://stackoverflow.com/a/5376358/1042555"><code>List</code> is somehow optimized for performance</a>. How so? What performance problems will I cause if I extend <code>List</code>? What exactly will break?</p>
<p>Another reason I've seen is that <code>List</code> is provided by Microsoft, and I have no control over it, so <a href="https://stackoverflow.com/questions/5376203/inherit-listt#comment6077237_5376343">I cannot change it later, after exposing a "public API"</a>. But I struggle to understand this. What is a public API and why should I care? If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from <code>List</code> <em>and</em> it turns out I need a public API, what difficulties will I have?</p>
<p>Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?</p>
<p>And lastly, if Microsoft did not want me to inherit from <code>List</code>, why didn't they make the class <code>sealed</code>?</p>
<h2>What else am I supposed to use?</h2>
<p>Apparently, for custom collections, Microsoft has provided a <code>Collection</code> class which should be extended instead of <code>List</code>. But this class is very bare, and does not have many useful things, <a href="https://stackoverflow.com/questions/1474863/addrange-to-a-collection">such as <code>AddRange</code></a>, for instance. <a href="https://stackoverflow.com/a/12039943/1042555">jvitor83's answer</a> provides a performance rationale for that particular method, but how is a slow <code>AddRange</code> not better than no <code>AddRange</code>?</p>
<p>Inheriting from <code>Collection</code> is way more work than inheriting from <code>List</code>, and I see no benefit. Surely Microsoft wouldn't tell me to do extra work for no reason, so I can't help feeling like I am somehow misunderstanding something, and inheriting <code>Collection</code> is actually not the right solution for my problem.</p>
<p>I've seen suggestions such as implementing <code>IList</code>. Just no. This is dozens of lines of boilerplate code which gains me nothing.</p>
<p>Lastly, some suggest wrapping the <code>List</code> in something: </p>
<pre><code>class FootballTeam
{
public List<FootballPlayer> Players;
}
</code></pre>
<p>There are two problems with this:</p>
<ol>
<li><p>It makes my code needlessly verbose. I must now call <code>my_team.Players.Count</code> instead of just <code>my_team.Count</code>. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal <code>List</code>... But that's a lot of code! What do I get for all that work?</p></li>
<li><p>It just plain doesn't make any sense. A football team doesn't "have" a list of players. It <em>is</em> the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.</p></li>
</ol>
<p>I realize that what happens "under the hood" can be said to be "adding X to Y's internal list", but this seems like a very counter-intuitive way of thinking about the world.</p>
<h2>My question (summarized)</h2>
<p>What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a <code>list</code> of <code>things</code> with a few bells and whistles?</p>
<p>Is inheriting from <code>List<T></code> always unacceptable? When is it acceptable? Why/why not? What must a programmer consider, when deciding whether to inherit from <code>List<T></code> or not?</p> | <p>There are some good answers here. I would add to them the following points.</p>
<blockquote>
<p>What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?</p>
</blockquote>
<p>Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:</p>
<blockquote>
<p>A football team is a particular kind of _____</p>
</blockquote>
<p>Did <em>anyone</em> say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"? Your notion that a football team is <em>a particular kind of list of players</em> is in your human mind and your human mind alone.</p>
<p><code>List<T></code> is a <em>mechanism</em>. Football team is a <em>business object</em> -- that is, an object that represents some concept that is in the <em>business domain</em> of the program. Don't mix those! A football team <em>is a kind of</em> team; it <em>has a</em> roster, a roster <em>is a list of players</em>. A roster is not a <em>particular kind of list of players</em>. A roster <em>is</em> a list of players. So make a property called <code>Roster</code> that is a <code>List<Player></code>. And make it <code>ReadOnlyList<Player></code> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.</p>
<blockquote>
<p>Is inheriting from <code>List<T></code> always unacceptable?</p>
</blockquote>
<p>Unacceptable to whom? Me? No.</p>
<blockquote>
<p>When is it acceptable?</p>
</blockquote>
<p>When you're building a mechanism that <em>extends the <code>List<T></code> mechanism</em>.</p>
<blockquote>
<p>What must a programmer consider, when deciding whether to inherit from <code>List<T></code> or not?</p>
</blockquote>
<p>Am I building a <em>mechanism</em> or a <em>business object</em>?</p>
<blockquote>
<p>But that's a lot of code! What do I get for all that work?</p>
</blockquote>
<p>You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of <code>List<T></code> fifty times over. You're clearly not afraid of verbosity, and we are talking about a very small amount of code here; this is a few minutes work.</p>
<h2>UPDATE</h2>
<p>I gave it some more thought and there is another reason to not model a football team as a list of players. In fact it might be a bad idea to model a football team as <em>having</em> a list of players too. The problem with a team as/having a list of players is that what you've got is a <em>snapshot</em> of the team <em>at a moment in time</em>. I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?" or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?" or "<a href="http://theoatmeal.com/comics/working_home" rel="noreferrer">Did the Piggers go all the way this year?</a>"</p>
<p>That is, a football team seems to me to be well modeled as <em>a collection of historical facts</em> such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.</p> | {
"question_id": 21692193,
"question_date": "2014-02-11T03:01:36.297Z",
"question_score": 1643,
"tags": "c#|.net|list|oop|inheritance",
"answer_id": 21694054,
"answer_date": "2014-02-11T05:43:29.297Z",
"answer_score": 1768
} |
Please answer the following Stack Overflow question:
Title: How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)
<p>My version of node is always v0.6.1-pre even after I install brew node and NVM install v0.6.19.</p>
<p>My node version is:</p>
<pre class="lang-none prettyprint-override"><code>node -v
v0.6.1-pre
</code></pre>
<p>NVM says this (after I install a version of node for the first time in one bash terminal):</p>
<pre class="lang-none prettyprint-override"><code>nvm ls
v0.6.19
current: v0.6.19
</code></pre>
<p>But when I restart bash, this is what I see:</p>
<pre class="lang-none prettyprint-override"><code>nvm ls
v0.6.19
current: v0.6.1-pre
default -> 0.6.19 (-> v0.6.19)
</code></pre>
<p>So where is this phantom node 0.6.1-pre version and how can I get rid of it? I'm trying to install libraries via NPM so that I can work on a project.</p>
<p>I tried using BREW to update before NVM, using <code>brew update</code> and <code>brew install node</code>.
I've tried deleting the "node" directory in my <code>/usr/local/include</code> and the "node" and "node_modules" in my <code>/usr/local/lib</code>.
I've tried uninstalling npm and reinstalling it following <a href="https://superuser.com/questions/268946/uninstall-node-js">these</a> instructions.</p>
<p>All of this because I was trying to update an older version of node to install the "zipstream" library. Now there's folders in my users directory, and the node version STILL isn't up to date, even though NVM says it's using 0.6.19.</p>
<p><strong>Ideally, I'd like to uninstall nodejs, npm, and nvm, and just reinstall the entire thing from scratch on my system.</strong></p> | <p>Apparently, there was a <code>/Users/myusername/local</code> folder that contained a <code>include</code> with <code>node</code> and <code>lib</code> with <code>node</code> and <code>node_modules</code>. How and why this was created instead of in my <code>/usr/local</code> folder, I do not know.</p>
<p>Deleting these local references fixed the phantom v0.6.1-pre. If anyone has an explanation, I'll choose that as the correct answer.</p>
<p><strong>EDIT:</strong></p>
<p>You may need to do the additional instructions as well:</p>
<pre><code>sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
</code></pre>
<p>which is the equivalent of (same as above)...</p>
<pre><code>sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp
</code></pre>
<p>or (same as above) broken down...</p>
<p>To completely uninstall node + npm is to do the following:</p>
<ol>
<li>go to <strong>/usr/local/lib</strong> and delete any <strong>node</strong> and <strong>node_modules</strong></li>
<li>go to <strong>/usr/local/include</strong> and delete any <strong>node</strong> and <strong>node_modules</strong> directory </li>
<li>if you installed with <strong>brew install node</strong>, then run <strong>brew uninstall node</strong> in your terminal</li>
<li>check your Home directory for any <strong>local</strong> or <strong>lib</strong> or <strong>include</strong> folders, and delete any <strong>node</strong> or <strong>node_modules</strong> from there</li>
<li>go to <strong>/usr/local/bin</strong> and delete any <strong>node</strong> executable</li>
</ol>
<p>You may also need to do:</p>
<pre><code>sudo rm -rf /opt/local/bin/node /opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node.1 /usr/local/lib/dtrace/node.d
</code></pre>
<p>Additionally, NVM modifies the PATH variable in <code>$HOME/.bashrc</code>, which must be <a href="https://github.com/creationix/nvm#removal" rel="noreferrer">reverted manually</a>.</p>
<p>Then download <strong>nvm</strong> and follow the instructions to install node. The latest versions of node come with <strong>npm</strong>, I believe, but you can also reinstall that as well.</p> | {
"question_id": 11177954,
"question_date": "2012-06-24T13:40:56.310Z",
"question_score": 1639,
"tags": "javascript|node.js|npm",
"answer_id": 11178106,
"answer_date": "2012-06-24T14:04:58.760Z",
"answer_score": 1933
} |
Please answer the following Stack Overflow question:
Title: How do you access the matched groups in a JavaScript regular expression?
<p>I want to match a portion of a string using a <a href="https://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> and then access that parenthesized substring:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)</code></pre>
</div>
</div>
</p>
<p>What am I doing wrong?</p>
<hr />
<p>I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:</p>
<pre><code>"date format_%A"
</code></pre>
<p>Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, <em><a href="https://stackoverflow.com/questions/432826/why-is-a-matched-substring-returning-undefined-in-javascript">Why is a matched substring returning "undefined" in JavaScript?</a></em>.</p>
<hr />
<p>The issue was that <code>console.log</code> takes its parameters like a <code>printf</code> statement, and since the string I was logging (<code>"%A"</code>) had a special value, it was trying to find the value of the next parameter.</p> | <p>You can access capturing groups like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
var myRegexp = new RegExp("(?:^|\s)format_(.*?)(?:\s|$)", "g");
var match = myRegexp.exec(myString);
console.log(match[1]); // abc</code></pre>
</div>
</div>
</p>
<p>And if there are multiple matches you can iterate over them:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myString = "something format_abc";
var myRegexp = new RegExp("(?:^|\s)format_(.*?)(?:\s|$)", "g");
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}</code></pre>
</div>
</div>
</p>
<h2>Edit: 2019-09-10</h2>
<p>As you can see the way to iterate over multiple matches was not very intuitive. This lead to the proposal of the <a href="https://github.com/tc39/proposal-string-matchall" rel="noreferrer"><code>String.prototype.matchAll</code></a> method. This new method is expected to ship in the <a href="https://tc39.es/ecma262/#sec-string.prototype.matchall" rel="noreferrer">ECMAScript 2020 specification</a>. It gives us a clean API and solves multiple problems. It has been started to land on major browsers and JS engines as <a href="https://v8.dev/features/string-matchall" rel="noreferrer">Chrome 73+ / Node 12+</a> and Firefox 67+.</p>
<p>The method returns an iterator and is used as follows:</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 string = "something format_abc";
const regexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
const matches = string.matchAll(regexp);
for (const match of matches) {
console.log(match);
console.log(match.index)
}</code></pre>
</div>
</div>
</p>
<p>As it returns an iterator, we can say it's lazy, this is useful when handling particularly large numbers of capturing groups, or very large strings. But if you need, the result can be easily transformed into an Array by using the <em>spread syntax</em> or the <code>Array.from</code> method:</p>
<pre><code>function getFirstGroup(regexp, str) {
const array = [...str.matchAll(regexp)];
return array.map(m => m[1]);
}
// or:
function getFirstGroup(regexp, str) {
return Array.from(str.matchAll(regexp), m => m[1]);
}
</code></pre>
<p>In the meantime, while this proposal gets more wide support, you can use the <a href="https://www.npmjs.com/package/string.prototype.matchall" rel="noreferrer">official shim package</a>.</p>
<p>Also, the internal workings of the method are simple. An equivalent implementation using a generator function would be as follows:</p>
<pre><code>function* matchAll(str, regexp) {
const flags = regexp.global ? regexp.flags : regexp.flags + "g";
const re = new RegExp(regexp, flags);
let match;
while (match = re.exec(str)) {
yield match;
}
}
</code></pre>
<p>A copy of the original regexp is created; this is to avoid side-effects due to the mutation of the <code>lastIndex</code> property when going through the multple matches.</p>
<p>Also, we need to ensure the regexp has the <em>global</em> flag to avoid an infinite loop.</p>
<p>I'm also happy to see that even this StackOverflow question was referenced in the <a href="https://github.com/tc39/proposal-string-matchall#previous-discussions" rel="noreferrer">discussions of the proposal</a>.</p> | {
"question_id": 432493,
"question_date": "2009-01-11T07:21:20.460Z",
"question_score": 1639,
"tags": "javascript|regex",
"answer_id": 432503,
"answer_date": "2009-01-11T07:26:02.697Z",
"answer_score": 1920
} |
Please answer the following Stack Overflow question:
Title: How to convert a string to lower case in Bash
<p>Is there a way in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged 'bash'" rel="tag">bash</a> to convert a string into a lower case string?</p>
<p>For example, if I have:</p>
<pre><code>a="Hi all"
</code></pre>
<p>I want to convert it to:</p>
<pre><code>"hi all"
</code></pre> | <p>The are various ways:</p>
<h2><a href="https://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX standard</a></h2>
<h3><a href="http://en.wikipedia.org/wiki/Tr_%28Unix%29" rel="noreferrer">tr</a></h3>
<pre><code>$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
</code></pre>
<h3><a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a></h3>
<pre><code>$ echo "$a" | awk '{print tolower($0)}'
hi all
</code></pre>
<h2>Non-POSIX</h2>
<p>You may run into portability issues with the following examples:</p>
<h3><a href="https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash 4.0</a></h3>
<pre><code>$ echo "${a,,}"
hi all
</code></pre>
<h3><a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a></h3>
<pre><code>$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all
</code></pre>
<h3><a href="http://en.wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a></h3>
<pre><code>$ echo "$a" | perl -ne 'print lc'
hi all
</code></pre>
<h3><a href="https://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a></h3>
<pre><code>lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf \\$(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done
</code></pre>
<p>Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using <code>shopt -u nocasematch;</code>. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)</p> | {
"question_id": 2264428,
"question_date": "2010-02-15T07:02:56.790Z",
"question_score": 1636,
"tags": "string|bash|shell|lowercase",
"answer_id": 2264537,
"answer_date": "2010-02-15T07:43:20.533Z",
"answer_score": 2772
} |
Please answer the following Stack Overflow question:
Title: How can I replace each newline (\n) with a space using sed?
<p>How can I replace a newline ("<code>\n</code>") with a space ("<code></code>") using the <code>sed</code> command?</p>
<p>I unsuccessfully tried: </p>
<pre><code>sed 's#\n# #g' file
sed 's#^$# #g' file
</code></pre>
<p>How do I fix it?</p> | <p>Use this solution with GNU <code>sed</code>:</p>
<pre><code>sed ':a;N;$!ba;s/\n/ /g' file
</code></pre>
<p>This will read the whole file in a loop (<code>':a;N;$!ba</code>), then replaces the newline(s) with a space (<code>s/\n/ /g</code>). Additional substitutions can be simply appended if needed.</p>
<p>Explanation:</p>
<ol start="0">
<li><code>sed</code> starts by reading the first line excluding the newline into the pattern space.</li>
<li>Create a label via <code>:a</code>.</li>
<li>Append a newline and next line to the pattern space via <code>N</code>.</li>
<li>If we are before the last line, branch to the created label <code>$!ba</code> (<code>$!</code> means not to do it on the last line. This is necessary to avoid executing <code>N</code> again, which would terminate the script if there is no more input!).</li>
<li>Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).</li>
</ol>
<p>Here is cross-platform compatible syntax which works with BSD and OS X's <code>sed</code> (as per <a href="https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed?page=1&tab=votes#comment9175314_1252191">@Benjie comment</a>):</p>
<pre><code>sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' file
</code></pre>
<p>As you can see, using <code>sed</code> for this otherwise simple problem is problematic. For a simpler and adequate solution see <a href="https://stackoverflow.com/a/1252010/1638350">this answer</a>.</p> | {
"question_id": 1251999,
"question_date": "2009-08-09T19:10:10.467Z",
"question_score": 1635,
"tags": "sed",
"answer_id": 1252191,
"answer_date": "2009-08-09T20:26:21.843Z",
"answer_score": 1731
} |
Please answer the following Stack Overflow question:
Title: Why does changing 0.1f to 0 slow down performance by 10x?
<p>Why does this bit of code,</p>
<pre><code>const float x[16] = { 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8,
1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6};
const float z[16] = {1.123, 1.234, 1.345, 156.467, 1.578, 1.689, 1.790, 1.812,
1.923, 2.034, 2.145, 2.256, 2.367, 2.478, 2.589, 2.690};
float y[16];
for (int i = 0; i < 16; i++)
{
y[i] = x[i];
}
for (int j = 0; j < 9000000; j++)
{
for (int i = 0; i < 16; i++)
{
y[i] *= x[i];
y[i] /= z[i];
y[i] = y[i] + 0.1f; // <--
y[i] = y[i] - 0.1f; // <--
}
}
</code></pre>
<p>run more than 10 times faster than the following bit (identical except where noted)?</p>
<pre><code>const float x[16] = { 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8,
1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6};
const float z[16] = {1.123, 1.234, 1.345, 156.467, 1.578, 1.689, 1.790, 1.812,
1.923, 2.034, 2.145, 2.256, 2.367, 2.478, 2.589, 2.690};
float y[16];
for (int i = 0; i < 16; i++)
{
y[i] = x[i];
}
for (int j = 0; j < 9000000; j++)
{
for (int i = 0; i < 16; i++)
{
y[i] *= x[i];
y[i] /= z[i];
y[i] = y[i] + 0; // <--
y[i] = y[i] - 0; // <--
}
}
</code></pre>
<p>when compiling with Visual Studio 2010 SP1.
The optimization level was <code>-02</code> with <code>sse2</code> enabled.
I haven't tested with other compilers.</p> | <p><strong>Welcome to the world of <a href="http://en.wikipedia.org/wiki/Denormal_number" rel="noreferrer">denormalized floating-point</a>!</strong> They can wreak havoc on performance!!!</p>
<p>Denormal (or subnormal) numbers are kind of a hack to get some extra values very close to zero out of the floating point representation. Operations on denormalized floating-point can be <strong><em>tens to hundreds of times slower</em></strong> than on normalized floating-point. This is because many processors can't handle them directly and must trap and resolve them using microcode.</p>
<p>If you print out the numbers after 10,000 iterations, you will see that they have converged to different values depending on whether <code>0</code> or <code>0.1</code> is used.</p>
<p>Here's the test code compiled on x64:</p>
<pre><code>int main() {
double start = omp_get_wtime();
const float x[16]={1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6};
const float z[16]={1.123,1.234,1.345,156.467,1.578,1.689,1.790,1.812,1.923,2.034,2.145,2.256,2.367,2.478,2.589,2.690};
float y[16];
for(int i=0;i<16;i++)
{
y[i]=x[i];
}
for(int j=0;j<9000000;j++)
{
for(int i=0;i<16;i++)
{
y[i]*=x[i];
y[i]/=z[i];
#ifdef FLOATING
y[i]=y[i]+0.1f;
y[i]=y[i]-0.1f;
#else
y[i]=y[i]+0;
y[i]=y[i]-0;
#endif
if (j > 10000)
cout << y[i] << " ";
}
if (j > 10000)
cout << endl;
}
double end = omp_get_wtime();
cout << end - start << endl;
system("pause");
return 0;
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>#define FLOATING
1.78814e-007 1.3411e-007 1.04308e-007 0 7.45058e-008 6.70552e-008 6.70552e-008 5.58794e-007 3.05474e-007 2.16067e-007 1.71363e-007 1.49012e-007 1.2666e-007 1.11759e-007 1.04308e-007 1.04308e-007
1.78814e-007 1.3411e-007 1.04308e-007 0 7.45058e-008 6.70552e-008 6.70552e-008 5.58794e-007 3.05474e-007 2.16067e-007 1.71363e-007 1.49012e-007 1.2666e-007 1.11759e-007 1.04308e-007 1.04308e-007
//#define FLOATING
6.30584e-044 3.92364e-044 3.08286e-044 0 1.82169e-044 1.54143e-044 2.10195e-044 2.46842e-029 7.56701e-044 4.06377e-044 3.92364e-044 3.22299e-044 3.08286e-044 2.66247e-044 2.66247e-044 2.24208e-044
6.30584e-044 3.92364e-044 3.08286e-044 0 1.82169e-044 1.54143e-044 2.10195e-044 2.45208e-029 7.56701e-044 4.06377e-044 3.92364e-044 3.22299e-044 3.08286e-044 2.66247e-044 2.66247e-044 2.24208e-044
</code></pre>
<p>Note how in the second run the numbers are very close to zero.</p>
<p>Denormalized numbers are generally rare and thus most processors don't try to handle them efficiently.</p>
<hr>
<p>To demonstrate that this has everything to do with denormalized numbers, if we <strong>flush denormals to zero</strong> by adding this to the start of the code:</p>
<pre><code>_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
</code></pre>
<p>Then the version with <code>0</code> is no longer 10x slower and actually becomes faster. (This requires that the code be compiled with SSE enabled.)</p>
<p>This means that rather than using these weird lower precision almost-zero values, we just round to zero instead.</p>
<p><strong>Timings: Core i7 920 @ 3.5 GHz:</strong></p>
<pre><code>// Don't flush denormals to zero.
0.1f: 0.564067
0 : 26.7669
// Flush denormals to zero.
0.1f: 0.587117
0 : 0.341406
</code></pre>
<p>In the end, this really has nothing to do with whether it's an integer or floating-point. The <code>0</code> or <code>0.1f</code> is converted/stored into a register outside of both loops. So that has no effect on performance.</p> | {
"question_id": 9314534,
"question_date": "2012-02-16T15:58:39.667Z",
"question_score": 1635,
"tags": "c++|performance|visual-studio-2010|compilation|floating-point",
"answer_id": 9314926,
"answer_date": "2012-02-16T16:20:09.343Z",
"answer_score": 1700
} |
Please answer the following Stack Overflow question:
Title: Creating a div element in jQuery
<p>How do I create a <code>div</code> element in <strong>jQuery</strong>?</p> | <p>You can use <code>append</code> (to add at last position of parent) or <code>prepend</code> (to add at fist position of parent):</p>
<pre><code>$('#parent').append('<div>hello</div>');
// or
$('<div>hello</div>').appendTo('#parent');
</code></pre>
<p>Alternatively, you can use the <code>.html()</code> or <code>.add()</code> as mentioned in a <a href="https://stackoverflow.com/a/867941/59087">different answer</a>.</p> | {
"question_id": 867916,
"question_date": "2009-05-15T10:30:24.117Z",
"question_score": 1634,
"tags": "javascript|jquery|html|append|jquery-append",
"answer_id": 867981,
"answer_date": "2009-05-15T10:43:53.697Z",
"answer_score": 1148
} |
Please answer the following Stack Overflow question:
Title: map function for objects (instead of arrays)
<p>I have an object:</p>
<pre><code>myObject = { 'a': 1, 'b': 2, 'c': 3 }
</code></pre>
<p>I am looking for a native method, similar to <code>Array.prototype.map</code> that would be used as follows:</p>
<pre><code>newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
</code></pre>
<p>Does JavaScript have such a <code>map</code> function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)</p> | <p>There is no native <code>map</code> to the <code>Object</code> object, but how about this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).forEach(function(key, index) {
myObject[key] *= 2;
});
console.log(myObject);
// => { 'a': 2, 'b': 4, 'c': 6 }</code></pre>
</div>
</div>
</p>
<p>But you could easily iterate over an object using <code>for ... in</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = { 'a': 1, 'b': 2, 'c': 3 };
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
myObject[key] *= 2;
}
}
console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }</code></pre>
</div>
</div>
</p>
<p><strong>Update</strong></p>
<p>A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = { 'a': 1, 'b': 2, 'c': 3 };
// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
var newObject = objectMap(myObject, function(value) {
return value * 2
})
console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }
console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }</code></pre>
</div>
</div>
</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer"><code>Array.prototype.reduce</code></a> reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object <code>{}</code>. On every iteration a new key of <code>myObject</code> is added with twice the key as the value.</p>
<p><strong>Update</strong></p>
<p>With new ES6 features, there is a more elegant way to express <code>objectMap</code>.</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 objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [k, fn(v, k, i)]
)
)
const myObject = { a: 1, b: 2, c: 3 }
console.log(objectMap(myObject, v => 2 * v)) </code></pre>
</div>
</div>
</p> | {
"question_id": 14810506,
"question_date": "2013-02-11T10:41:12.630Z",
"question_score": 1633,
"tags": "javascript|node.js|functional-programming|map-function",
"answer_id": 14810722,
"answer_date": "2013-02-11T10:52:37.437Z",
"answer_score": 2316
} |
Please answer the following Stack Overflow question:
Title: How do I force a favicon refresh?
<p>I have a Grails application running locally using its own tomcat and I have just changed the favicon for a new one. Problem is that I can not see it in any browser. The old favicon shows up or I get no favicon at all, but not my new one. I do not think this is a Grails issue per se, more an issue with favicons.</p>
<p>What is supposed to happen with favicons? How are they supposed to work? I have numerous bookmarks in my browser which have the wrong icons and they never seem to get refreshed. How do I force the server/browser to stop caching them? It seems pretty silly to always cache them given they are normally only 16x16. Why not just upload them with every visit to the page? It is not exactly a huge overhead.</p> | <p>To refresh your site's favicon you can force browsers to download a new version using the link tag and a query string on your filename.<br />
This is especially helpful in production environments to make sure your users get the update.</p>
<pre class="lang-html prettyprint-override"><code><link rel="icon" href="http://www.yoursite.com/favicon.ico?v=2" />
</code></pre> | {
"question_id": 2208933,
"question_date": "2010-02-05T17:09:03.930Z",
"question_score": 1632,
"tags": "favicon",
"answer_id": 7116701,
"answer_date": "2011-08-19T03:39:56.017Z",
"answer_score": 2190
} |
Please answer the following Stack Overflow question:
Title: What is the best algorithm for overriding GetHashCode?
<p>In .NET, the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode" rel="noreferrer"><code>GetHashCode</code> method</a> is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.</p>
<p>Is there a standard algorithm or best practice on how to implement <code>GetHashCode</code> for my custom classes so I don't degrade performance?</p> | <p>I usually go with something like the implementation given in Josh Bloch's <em>fabulous</em> <a href="https://rads.stackoverflow.com/amzn/click/com/0321356683" rel="noreferrer" rel="nofollow noreferrer">Effective Java</a>. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:</p>
<pre><code>public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
}
</code></pre>
<p>As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-<a href="https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function" rel="noreferrer">FNV</a> example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant <em>is</em> prime though. I don't know quite how important that is.)</p>
<p>This is better than the common practice of <code>XOR</code>ing hashcodes for two main reasons. Suppose we have a type with two <code>int</code> fields:</p>
<pre><code>XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y
</code></pre>
<p>By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.</p>
<p><a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="noreferrer">This page</a> gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx#fnv" rel="noreferrer">FNV</a> alternative is similarly simple, but uses different constants and <code>XOR</code> instead of <code>ADD</code> as a combining operation. It looks <em>something</em> like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.</p>
<pre><code>// Note: Not quite FNV!
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = (int) 2166136261;
// Suitable nullity checks etc, of course :)
hash = (hash * 16777619) ^ field1.GetHashCode();
hash = (hash * 16777619) ^ field2.GetHashCode();
hash = (hash * 16777619) ^ field3.GetHashCode();
return hash;
}
}
</code></pre>
<p>Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.</p>
<p>As per the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode#notes-to-inheritors" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:</p>
<ul>
<li>You can compute the hash code from fields that are not mutable; or</li>
<li>You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.</li>
</ul>
</blockquote>
<p>The link to the <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="noreferrer">FNV</a> article is broken but here is a copy in the Internet Archive: <a href="https://archive.vn/KJeJy" rel="noreferrer">Eternally Confuzzled - The Art of Hashing</a></p> | {
"question_id": 263400,
"question_date": "2008-11-04T20:53:19.927Z",
"question_score": 1632,
"tags": ".net|algorithm|hashcode|gethashcode",
"answer_id": 263416,
"answer_date": "2008-11-04T20:56:17.130Z",
"answer_score": 1768
} |
Please answer the following Stack Overflow question:
Title: <meta charset="utf-8"> vs <meta http-equiv="Content-Type">
<p>In order to define charset for <strong>HTML5 Doctype</strong>, which notation should I use?</p>
<ol>
<li><p>Short:</p>
<pre><code><meta charset="utf-8" />
</code></pre></li>
<li><p>Long:</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code></pre></li>
</ol> | <p>In HTML5, they are equivalent. Use the shorter one, as it is easier to remember and type. <a href="http://code.google.com/p/doctype-mirror/wiki/MetaCharsetAttribute" rel="noreferrer">Browser support is fine</a> since it was designed for backwards compatibility.</p> | {
"question_id": 4696499,
"question_date": "2011-01-14T22:06:47.953Z",
"question_score": 1630,
"tags": "html|meta-tags|doctype",
"answer_id": 4696517,
"answer_date": "2011-01-14T22:09:46.133Z",
"answer_score": 1134
} |
Please answer the following Stack Overflow question:
Title: How can I delete using INNER JOIN with SQL Server?
<p>I want to <strong>delete</strong> using <code>INNER JOIN</code> in <strong>SQL Server 2008</strong>.</p>
<p>But I get this error:</p>
<blockquote>
<p>Msg 156, Level 15, State 1, Line 15<br />
<strong>Incorrect</strong> syntax near the <strong>keyword</strong> 'INNER'.</p>
</blockquote>
<p>My code:</p>
<pre><code>DELETE
FROM WorkRecord2
INNER JOIN Employee
ON EmployeeRun=EmployeeNo
WHERE Company = '1'
AND Date = '2013-05-06'
</code></pre> | <p>You need to specify what table you are deleting from. Here is a version with an alias:</p>
<pre><code>DELETE w
FROM WorkRecord2 w
INNER JOIN Employee e
ON EmployeeRun=EmployeeNo
WHERE Company = '1' AND Date = '2013-05-06'
</code></pre> | {
"question_id": 16481379,
"question_date": "2013-05-10T11:38:21.043Z",
"question_score": 1629,
"tags": "sql|sql-server|sql-server-2008|inner-join|sql-delete",
"answer_id": 16481475,
"answer_date": "2013-05-10T11:43:31.710Z",
"answer_score": 2802
} |
Please answer the following Stack Overflow question:
Title: How can I make a dictionary from separate lists of keys and values?
<p>I want to combine these:</p>
<pre class="lang-py prettyprint-override"><code>keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
</code></pre>
<p>Into a single dictionary:</p>
<pre class="lang-py prettyprint-override"><code>{'name': 'Monty', 'age': 42, 'food': 'spam'}
</code></pre> | <p>Like this:</p>
<pre><code>keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
</code></pre>
<p>Voila :-) The pairwise <a href="https://docs.python.org/3/library/functions.html#func-dict" rel="noreferrer"><code>dict</code></a> constructor and <a href="https://docs.python.org/3/library/functions.html#zip" rel="noreferrer"><code>zip</code></a> function are awesomely useful.</p> | {
"question_id": 209840,
"question_date": "2008-10-16T19:05:47.233Z",
"question_score": 1629,
"tags": "python|list|dictionary",
"answer_id": 209854,
"answer_date": "2008-10-16T19:09:05.400Z",
"answer_score": 2742
} |
Please answer the following Stack Overflow question:
Title: Calculate relative time in C#
<p>Given a specific <code>DateTime</code> value, how do I display relative time, like:</p>
<ul>
<li><code>2 hours ago</code></li>
<li><code>3 days ago</code></li>
<li><code>a month ago</code></li>
</ul> | <p>Jeff, <a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12">your code</a> is nice but could be clearer with constants (as suggested in Code Complete).</p>
<pre class="lang-csharp prettyprint-override"><code>const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
</code></pre> | {
"question_id": 11,
"question_date": "2008-07-31T23:55:37.967Z",
"question_score": 1629,
"tags": "c#|datetime|time|datediff|relative-time-span",
"answer_id": 1248,
"answer_date": "2008-08-04T13:57:26.097Z",
"answer_score": 1064
} |
Please answer the following Stack Overflow question:
Title: What is the difference between UNION and UNION ALL?
<p>What is the difference between <code>UNION</code> and <code>UNION ALL</code>?</p> | <p><code>UNION</code> removes duplicate records (where all columns in the results are the same), <code>UNION ALL</code> does not.</p>
<p>There is a performance hit when using <code>UNION</code> instead of <code>UNION ALL</code>, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).</p>
<p>To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE)</p>
<h3>UNION Example:</h3>
<pre><code>SELECT 'foo' AS bar UNION SELECT 'foo' AS bar
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>+-----+
| bar |
+-----+
| foo |
+-----+
1 row in set (0.00 sec)
</code></pre>
<h3>UNION ALL example:</h3>
<pre><code>SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar
</code></pre>
<p><strong>Result:</strong></p>
<pre><code>+-----+
| bar |
+-----+
| foo |
| foo |
+-----+
2 rows in set (0.00 sec)
</code></pre> | {
"question_id": 49925,
"question_date": "2008-09-08T15:19:33.263Z",
"question_score": 1628,
"tags": "sql|union|union-all",
"answer_id": 49928,
"answer_date": "2008-09-08T15:21:15.193Z",
"answer_score": 1948
} |
Please answer the following Stack Overflow question:
Title: Sorting an array of objects by property values
<p>I've got the following objects using AJAX and stored them in an array:</p>
<pre><code>var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
</code></pre>
<p>How do I create a function to sort the objects by the <code>price</code> property in <em>ascending</em> <strong>or</strong> <em>descending</em> order using JavaScript only?</p> | <p>Sort homes by price in ascending order:</p>
<pre class="lang-js prettyprint-override"><code>homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
</code></pre>
<p>Or after ES6 version:</p>
<pre><code>homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
</code></pre>
<p>Some documentation can be found <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" rel="noreferrer">here</a>.</p>
<p>For descending order, you may use </p>
<pre><code>homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
</code></pre> | {
"question_id": 979256,
"question_date": "2009-06-11T03:59:54.460Z",
"question_score": 1627,
"tags": "javascript|arrays|sorting",
"answer_id": 979289,
"answer_date": "2009-06-11T04:12:35.523Z",
"answer_score": 2102
} |
Please answer the following Stack Overflow question:
Title: Getting Chrome to accept self-signed localhost certificate
<p>I have created a self-signed SSL certificate for the localhost CN. Firefox accepts this certificate after initially complaining about it, as expected. Chrome and IE, however, refuse to accept it, even after adding the certificate to the system certificate store under Trusted Roots. Even though the certificate is listed as correctly installed when I click "View certificate information" in Chrome's HTTPS popup, it still insists the certificate cannot be trusted.</p>
<p>What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?</p> | <h4>With <strong>only <em>5</em> <code>openssl</code> commands</strong>, you can accomplish this.</h4>
<p>(<em>Please don't change your browser security settings.</em>)</p>
<p>With the following code, you can (1) become your own CA, (2) then sign your SSL certificate as a CA. (3) Then import the CA certificate (not the SSL certificate, which goes onto your server) into Chrome/Chromium. (Yes, this works even on Linux.)</p>
<p><em>NB: For Windows, some reports say that <code>openssl</code> must be run with <code>winpty</code> to avoid a crash.</em></p>
<pre class="lang-bash prettyprint-override"><code>######################
# Become a Certificate Authority
######################
# Generate private key
openssl genrsa -des3 -out myCA.key 2048
# Generate root certificate
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 825 -out myCA.pem
######################
# Create CA-signed certs
######################
NAME=mydomain.example # Use your own domain name
# Generate a private key
openssl genrsa -out $NAME.key 2048
# Create a certificate-signing request
openssl req -new -key $NAME.key -out $NAME.csr
# Create a config file for the extensions
>$NAME.ext cat <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $NAME # Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.2 = bar.$NAME # Optionally, add additional domains (I've added a subdomain here)
IP.1 = 192.168.0.13 # Optionally, add an IP address (if the connection which you have planned requires it)
EOF
# Create the signed certificate
openssl x509 -req -in $NAME.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
-out $NAME.crt -days 825 -sha256 -extfile $NAME.ext
</code></pre>
<p>To recap:</p>
<ol>
<li>Become a CA</li>
<li>Sign your certificate using your CA cert+key</li>
<li>Import <code>myCA.pem</code> as an "Authority" (<em>not</em> into "Your Certificates") in your Chrome settings (Settings > Manage certificates > Authorities > Import)</li>
<li>Use the <code>$NAME.crt</code> and <code>$NAME.key</code> files in your server</li>
</ol>
<p>Extra steps (for Mac, at least):</p>
<ol>
<li>Import the CA cert at "File > Import file", then also find it in the list, right click it, expand "> Trust", and select "Always"</li>
<li>Add <code>extendedKeyUsage=serverAuth,clientAuth</code> below <code>basicConstraints=CA:FALSE</code>, and make sure you set the "CommonName" to the same as <code>$NAME</code> when it's asking for setup</li>
</ol>
<p><strong>You can check your work</strong> to ensure that the certificate is built correctly:</p>
<pre class="lang-bash prettyprint-override"><code>openssl verify -CAfile myCA.pem -verify_hostname bar.mydomain.example mydomain.example.crt
</code></pre> | {
"question_id": 7580508,
"question_date": "2011-09-28T08:41:51.200Z",
"question_score": 1621,
"tags": "google-chrome|ssl|certificate|self-signed",
"answer_id": 60516812,
"answer_date": "2020-03-03T23:05:32.837Z",
"answer_score": 406
} |
Please answer the following Stack Overflow question:
Title: How do I import a module given the full path?
<p>How do I load a Python module given its full path?</p>
<p>Note that the file can be anywhere in the filesystem.</p> | <p>For Python 3.5+ use (<a href="https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly" rel="noreferrer">docs</a>):</p>
<pre><code>import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()
</code></pre>
<p>For Python 3.3 and 3.4 use:</p>
<pre><code>from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
</code></pre>
<p>(Although this has been deprecated in Python 3.4.)</p>
<p>For Python 2 use:</p>
<pre><code>import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
</code></pre>
<p>There are equivalent convenience functions for compiled Python files and DLLs.</p>
<p>See also <a href="http://bugs.python.org/issue21436" rel="noreferrer">http://bugs.python.org/issue21436</a>.</p> | {
"question_id": 67631,
"question_date": "2008-09-15T22:30:55.493Z",
"question_score": 1619,
"tags": "python|python-import|python-module",
"answer_id": 67692,
"answer_date": "2008-09-15T22:41:16.887Z",
"answer_score": 1644
} |
Please answer the following Stack Overflow question:
Title: Why does Java have transient fields?
<p>Why does Java have <strong>transient</strong> fields?</p> | <p>The <code>transient</code> keyword in Java is used to indicate that a field should not be part of the serialization (which means saved, like to a file) process.</p>
<p>From the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/index.html" rel="noreferrer">Java Language Specification, Java SE 7 Edition</a>, <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.3" rel="noreferrer">Section 8.3.1.3. <code>transient</code> Fields</a>:</p>
<blockquote>
<p>Variables may be marked <code>transient</code> to
indicate that they are not part of the
persistent state of an object.</p>
</blockquote>
<p>For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.</p>
<p>Here's a <code>GalleryImage</code> class which contains an image and a thumbnail derived from the image:</p>
<pre><code>class GalleryImage implements Serializable
{
private Image image;
private transient Image thumbnailImage;
private void generateThumbnail()
{
// Generate thumbnail.
}
private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
generateThumbnail();
}
}
</code></pre>
<p>In this example, the <code>thumbnailImage</code> is a thumbnail image that is generated by invoking the <code>generateThumbnail</code> method.</p>
<p>The <code>thumbnailImage</code> field is marked as <code>transient</code>, so only the original <code>image</code> is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. (Of course, this may or may not be desirable depending on the requirements of the system -- this is just an example.)</p>
<p>At the time of deserialization, the <a href="http://java.sun.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()" rel="noreferrer"><code>readObject</code></a> method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. Here, the thumbnail needs to be generated, so the <code>readObject</code> method is overridden so that the thumbnail will be generated by calling the <code>generateThumbnail</code> method.</p>
<p>For additional information, the article <a href="http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html" rel="noreferrer">Discover the secrets of the Java Serialization API</a> (which was originally available on the Sun Developer Network) has a section which discusses the use of and presents a scenario where the <code>transient</code> keyword is used to prevent serialization of certain fields.</p> | {
"question_id": 910374,
"question_date": "2009-05-26T12:11:36.673Z",
"question_score": 1616,
"tags": "java|field|transient",
"answer_id": 910522,
"answer_date": "2009-05-26T12:53:22.953Z",
"answer_score": 1802
} |
Please answer the following Stack Overflow question:
Title: What is the difference between const and readonly in C#?
<p>What is the difference between <strong><code>const</code></strong> and <strong><code>readonly</code></strong> in C#? </p>
<p>When would you use one over the other?</p> | <p>Apart from the apparent difference of</p>
<ul>
<li>having to declare the value at the time of a definition for a <code>const</code> VS <code>readonly</code> values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen.</li>
<li><code>const</code>'s are implicitly <code>static</code>. You use a <code>ClassName.ConstantName</code> notation to access them.</li>
</ul>
<p>There is a subtle difference. Consider a class defined in <code>AssemblyA</code>.</p>
<pre><code>public class Const_V_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_V_Readonly()
{
I_RO_VALUE = 3;
}
}
</code></pre>
<p><code>AssemblyB</code> references <code>AssemblyA</code> and uses these values in code. When this is compiled:</p>
<ul>
<li>in the case of the <code>const</code> value, it is like a find-replace. The value 2 is 'baked into' the <code>AssemblyB</code>'s IL. This means that if tomorrow I update <code>I_CONST_VALUE</code> to 20, <em><code>AssemblyB</code> would still have 2 till I recompile it</em>.</li>
<li>in the case of the <code>readonly</code> value, it is like a <code>ref</code> to a memory location. The value is not baked into <code>AssemblyB</code>'s IL. This means that if the memory location is updated, <code>AssemblyB</code> gets the new value without recompilation. So if <code>I_RO_VALUE</code> is updated to 30, you only need to build <code>AssemblyA</code> and all clients do not need to be recompiled.</li>
</ul>
<p>So if you are confident that the value of the constant won't change, use a <code>const</code>.</p>
<pre><code>public const int CM_IN_A_METER = 100;
</code></pre>
<p>But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a <code>readonly</code>.</p>
<pre><code>public readonly float PI = 3.14;
</code></pre>
<p><em>Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: <a href="https://rads.stackoverflow.com/amzn/click/com/0321245660" rel="noreferrer" rel="nofollow noreferrer">Effective C# - Bill Wagner</a></em></p> | {
"question_id": 55984,
"question_date": "2008-09-11T08:02:19.297Z",
"question_score": 1615,
"tags": "c#|.net|constants|readonly",
"answer_id": 56024,
"answer_date": "2008-09-11T08:24:41.770Z",
"answer_score": 1494
} |
Please answer the following Stack Overflow question:
Title: What is the difference between varchar and nvarchar?
<p>Is it just that <code>nvarchar</code> supports multibyte characters? If that is the case, is there really any point, other than storage concerns, to using <code>varchars</code>?</p> | <p>An <code>nvarchar</code> column can store any Unicode data. A <code>varchar</code> column is restricted to an 8-bit codepage. Some people think that <code>varchar</code> should be used because it takes up less space. I believe this is not the correct answer. Codepage incompatabilities are a pain, and Unicode is the cure for codepage problems. With cheap disk and memory nowadays, there is really no reason to waste time mucking around with code pages anymore.</p>
<p>All modern operating systems and development platforms use Unicode internally. By using <code>nvarchar</code> rather than <code>varchar</code>, you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors. And recovery from conversion errors is a non-trivial problem.</p>
<p>If you are interfacing with an application that uses only ASCII, I would still recommend using Unicode in the database. The OS and database collation algorithms will work better with Unicode. Unicode avoids conversion problems when interfacing with <em>other</em> systems. And you will be preparing for the future. And you can always validate that your data is restricted to 7-bit ASCII for whatever legacy system you're having to maintain, even while enjoying some of the benefits of full Unicode storage.</p> | {
"question_id": 144283,
"question_date": "2008-09-27T19:34:00.273Z",
"question_score": 1614,
"tags": "sql-server|varchar|nvarchar",
"answer_id": 147302,
"answer_date": "2008-09-29T02:16:22.780Z",
"answer_score": 2002
} |
Please answer the following Stack Overflow question:
Title: How to measure time taken by a function to execute
<p>I need to get execution time in milliseconds.</p>
<blockquote>
<p>I originally asked this question back in 2008. The accepted answer then was to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>new Date().getTime()</code></a> However, we can all agree now that using the standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance.now" rel="noreferrer"><code>performance.now()</code></a> API is more appropriate. I am therefore changing the accepted answer to this one.</p>
</blockquote> | <h2>Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance.now" rel="noreferrer"><strong>performance.now()</strong></a>:</h2>
<pre class="lang-js prettyprint-override"><code>var startTime = performance.now()
doSomething() // <---- measured code goes between startTime and endTime
var endTime = performance.now()
console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)
</code></pre>
<blockquote>
<p>In <code>Node.js</code> it is required to import the <a href="https://nodejs.org/api/perf_hooks.html#perf_hooks_class_performance" rel="noreferrer"><code>performance</code></a> class</p>
</blockquote>
<p>importing performance</p>
<pre class="lang-js prettyprint-override"><code>const { performance } = require('perf_hooks');
</code></pre>
<hr />
<h2>Using <strong><a href="https://developer.mozilla.org/en-US/docs/DOM/console.time" rel="noreferrer">console.time</a></strong>: (<a href="https://console.spec.whatwg.org/#time" rel="noreferrer">living standard</a>)</h2>
<pre class="lang-js prettyprint-override"><code>console.time('doSomething')
doSomething() // <---- The function you're measuring time for
console.timeEnd('doSomething')
</code></pre>
<p><em><strong>Note:</strong></em> <br>The string being passed to the <code>time()</code> and <code>timeEnd()</code> methods must match<br>(<em>for the timer to finish as expected</em>).</p>
<blockquote>
<h3><code>console.time()</code> documentations:</h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/time" rel="noreferrer">MDN documentation</a></li>
<li><a href="https://nodejs.org/api/console.html#console_console_timeend_label" rel="noreferrer">Node.js documentation</a></li>
</ul>
</blockquote> | {
"question_id": 313893,
"question_date": "2008-11-24T11:09:14.010Z",
"question_score": 1614,
"tags": "javascript|profiling",
"answer_id": 1975103,
"answer_date": "2009-12-29T15:05:42.183Z",
"answer_score": 2524
} |
Please answer the following Stack Overflow question:
Title: Why is it important to override GetHashCode when Equals method is overridden?
<p>Given the following class</p>
<pre><code>public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
</code></pre>
<p>I have overridden the <code>Equals</code> method because <code>Foo</code> represent a row for the <code>Foo</code>s table. Which is the preferred method for overriding the <code>GetHashCode</code>?</p>
<p>Why is it important to override <code>GetHashCode</code>?</p> | <p>Yes, it is important if your item will be used as a key in a dictionary, or <code>HashSet<T></code>, etc - since this is used (in the absence of a custom <code>IEqualityComparer<T></code>) to group items into buckets. If the hash-code for two items does not match, they may <em>never</em> be considered equal (<a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.equals?view=netframework-4.8" rel="noreferrer">Equals</a> will simply never be called).</p>
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8" rel="noreferrer">GetHashCode()</a> method should reflect the <code>Equals</code> logic; the rules are:</p>
<ul>
<li>if two things are equal (<code>Equals(...) == true</code>) then they <em>must</em> return the same value for <code>GetHashCode()</code></li>
<li>if the <code>GetHashCode()</code> is equal, it is <em>not</em> necessary for them to be the same; this is a collision, and <code>Equals</code> will be called to see if it is a real equality or not.</li>
</ul>
<p>In this case, it looks like "<code>return FooId;</code>" is a suitable <code>GetHashCode()</code> implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that <code>new Foo(3,5)</code> has a different hash-code to <code>new Foo(5,3)</code>):</p>
<p>In modern frameworks, the <code>HashCode</code> type has methods to help you create a hashcode from multiple values; on older frameworks, you'd need to go without, so something like:</p>
<pre><code>unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
int hash = 13;
hash = (hash * 7) + field1.GetHashCode();
hash = (hash * 7) + field2.GetHashCode();
...
return hash;
}
</code></pre>
<p>Oh - for convenience, you might also consider providing <code>==</code> and <code>!=</code> operators when overriding <code>Equals</code> and <code>GetHashCode</code>.</p>
<hr />
<p>A demonstration of what happens when you get this wrong is <a href="https://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array/639098#639098">here</a>.</p> | {
"question_id": 371328,
"question_date": "2008-12-16T13:41:18.283Z",
"question_score": 1612,
"tags": "c#|overriding|hashcode",
"answer_id": 371348,
"answer_date": "2008-12-16T13:47:48.673Z",
"answer_score": 1444
} |
Please answer the following Stack Overflow question:
Title: Break a previous commit into multiple commits
<p>Without creating a branch and doing a bunch of funky work on a new branch, is it possible to break a single commit into a few different commits after it's been committed to the local repository?</p> | <p><a href="http://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#_changing_multiple" rel="noreferrer"><code>git rebase -i</code></a> will do it.</p>
<p>First, start with a clean working directory: <code>git status</code> should show no pending modifications, deletions, or additions.</p>
<p>Now, you have to decide which commit(s) you want to split.</p>
<h3>A) Splitting the most recent commit</h3>
<p>To split apart your most recent commit, first:</p>
<pre><code>$ git reset HEAD~
</code></pre>
<p>Now commit the pieces individually in the usual way, producing as many commits as you need.</p>
<h3>B) Splitting a commit farther back</h3>
<p>This requires <em>rebasing</em>, that is, rewriting history. To specify the correct commit, you have several choices:</p>
<ul>
<li><p>If it is three commits back, then</p>
<pre><code> $ git rebase -i HEAD~3
</code></pre>
<p>where <code>3</code> is how many commits back it is.</p>
</li>
<li><p>If it is farther back in the tree than you want to count, then</p>
<pre><code> $ git rebase -i 123abcd~
</code></pre>
<p>where <code>123abcd</code> is the SHA1 of the commit you want to split up.</p>
</li>
<li><p>If you are on a different branch (e.g., a feature branch) that you want to merge into <code>master</code>:</p>
<pre><code> $ git rebase -i master
</code></pre>
</li>
</ul>
<p>When you get the rebase edit screen, find the commit you want to break apart. At the beginning of that line, replace <code>pick</code> with <code>edit</code> (<code>e</code> for short). Save the buffer and exit. Rebase will now stop just after the commit you want to edit. Then:</p>
<pre><code>$ git reset HEAD~
</code></pre>
<p>Commit the pieces individually in the usual way, producing as many commits as you need.</p>
<p>Finally</p>
<pre><code>$ git rebase --continue
</code></pre> | {
"question_id": 6217156,
"question_date": "2011-06-02T16:11:12.183Z",
"question_score": 1612,
"tags": "git",
"answer_id": 6217314,
"answer_date": "2011-06-02T16:26:02.943Z",
"answer_score": 2254
} |
Please answer the following Stack Overflow question:
Title: How can I get the ID of an element using jQuery?
<pre><code><div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
</code></pre>
<p>Why doesn't the above work, and how should I do this?</p> | <p>The jQuery way:</p>
<pre><code>$('#test').attr('id')
</code></pre>
<p>In your example:</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>$(document).ready(function() {
console.log($('#test').attr('id'));
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div></code></pre>
</div>
</div>
</p>
<p>Or through the DOM:</p>
<pre><code>$('#test').get(0).id;
</code></pre>
<p>or even :</p>
<pre><code>$('#test')[0].id;
</code></pre>
<p>and reason behind usage of <code>$('#test').get(0)</code> in JQuery or even <code>$('#test')[0]</code> is that <code>$('#test')</code> is a JQuery selector and <strong>returns an array() of results</strong> not a single element by its default functionality</p>
<p>an alternative for DOM selector in jquery is </p>
<pre><code>$('#test').prop('id')
</code></pre>
<p>which is different from <code>.attr()</code> and <code>$('#test').prop('foo')</code> grabs the specified DOM <code>foo</code> property, while <code>$('#test').attr('foo')</code> grabs the specified HTML <code>foo</code> attribute and you can find more details about differences <a href="https://stackoverflow.com/questions/5874652/prop-vs-attr">here</a>.</p> | {
"question_id": 3239598,
"question_date": "2010-07-13T17:11:50.287Z",
"question_score": 1610,
"tags": "jquery|jquery-selectors",
"answer_id": 3239600,
"answer_date": "2010-07-13T17:12:47.747Z",
"answer_score": 2681
} |
Please answer the following Stack Overflow question:
Title: How to fully delete a git repository created with init?
<p>I created a git repository with <code>git init</code>. I'd like to delete it entirely and init a new one.</p> | <p>Git keeps all of its files in the <code>.git</code> directory. Just remove that one and init again.</p>
<p>If you can't find it, it's because it is hidden.</p>
<ul>
<li><p>In Windows 7, you need to go to your folder, click on <kbd>Organize</kbd> on the top left, then click on <kbd>Folder and search options</kbd>, then click on the <kbd>View</kbd> tab and click on the <kbd>Show hidden files, folders and drives</kbd> radio button.</p></li>
<li><p>On a Mac OS:</p>
<ul>
<li><p>Open a Terminal (via Spotlight: press <kbd>CMD</kbd> + <kbd>SPACE</kbd>, type <code>terminal</code> and press <kbd>Enter</kbd>) and run:</p>
<pre><code>defaults write com.apple.finder AppleShowAllFiles 1 && killall Finder
</code></pre>
<p>Note: The keyboard shortcut to show hidden files in Finder is
<kbd>CMD</kbd> + <kbd>SHIFT</kbd> + <kbd>.</kbd> so it is no longer necessary to modify the
finder config this way</p></li>
<li><p>You could also type <code>cd</code> (the space is important), drag and drop your git repo folder from Finder to the terminal window, press <kbd>return</kbd>, then type <code>rm -fr .git</code>, then <kbd>return</kbd> again.</p></li>
</ul></li>
<li><p>On Ubuntu, use shortcut <kbd>Ctrl + H</kbd>.</p></li>
</ul> | {
"question_id": 1213430,
"question_date": "2009-07-31T16:06:20.493Z",
"question_score": 1610,
"tags": "git|git-init",
"answer_id": 1213446,
"answer_date": "2009-07-31T16:08:35.120Z",
"answer_score": 2032
} |
Please answer the following Stack Overflow question:
Title: Try-catch speeding up my code?
<p>I wrote some code for testing the impact of try-catch, but seeing some surprising results.</p>
<pre><code>static void Main(string[] args)
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
long start = 0, stop = 0, elapsed = 0;
double avg = 0.0;
long temp = Fibo(1);
for (int i = 1; i < 100000000; i++)
{
start = Stopwatch.GetTimestamp();
temp = Fibo(100);
stop = Stopwatch.GetTimestamp();
elapsed = stop - start;
avg = avg + ((double)elapsed - avg) / i;
}
Console.WriteLine("Elapsed: " + avg);
Console.ReadKey();
}
static long Fibo(int n)
{
long n1 = 0, n2 = 1, fibo = 0;
n++;
for (int i = 1; i < n; i++)
{
n1 = n2;
n2 = fibo;
fibo = n1 + n2;
}
return fibo;
}
</code></pre>
<p>On my computer, this consistently prints out a value around 0.96..</p>
<p>When I wrap the for loop inside Fibo() with a try-catch block like this:</p>
<pre><code>static long Fibo(int n)
{
long n1 = 0, n2 = 1, fibo = 0;
n++;
try
{
for (int i = 1; i < n; i++)
{
n1 = n2;
n2 = fibo;
fibo = n1 + n2;
}
}
catch {}
return fibo;
}
</code></pre>
<p>Now it consistently prints out 0.69... -- it actually runs faster! But why?</p>
<p>Note: I compiled this using the Release configuration and directly ran the EXE file (outside Visual Studio).</p>
<p>EDIT: <a href="https://stackoverflow.com/a/8928476/282110">Jon Skeet's <em>excellent</em> analysis</a> shows that try-catch is somehow causing the x86 CLR to use the CPU registers in a more favorable way in this specific case (and I think we're yet to understand why). I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. I also tested using <code>int</code> types inside the Fibo method instead of <code>long</code> types, and then the x86 CLR was as equally fast as the x64 CLR.</p>
<hr>
<p><strong>UPDATE:</strong> It looks like this issue has been fixed by Roslyn. Same machine, same CLR version -- the issue remains as above when compiled with VS 2013, but the problem goes away when compiled with VS 2015. </p> | <p>One of the <a href="http://en.wikipedia.org/wiki/Microsoft_Roslyn" rel="noreferrer">Roslyn</a> engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation" rel="noreferrer">JIT</a> compiler does register scheduling in the corresponding x86 code. The result is suboptimal code generation on the loads and stores of the locals.</p>
<p>For some reason unclear to all of us, the problematic code generation path is avoided when the JITter knows that the block is in a try-protected region. </p>
<p>This is pretty weird. We'll follow up with the JITter team and see whether we can get a bug entered so that they can fix this. </p>
<p>Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the JITter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.</p>
<p>Thanks for bringing this to our attention, and apologies for the odd behaviour. </p> | {
"question_id": 8928403,
"question_date": "2012-01-19T15:10:57.040Z",
"question_score": 1607,
"tags": "c#|.net|clr|try-catch|performance-testing",
"answer_id": 8947323,
"answer_date": "2012-01-20T20:14:47.813Z",
"answer_score": 1123
} |
Please answer the following Stack Overflow question:
Title: How can I vertically center a div element for all browsers using CSS?
<p>I want to center a <code>div</code> vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.</p>
<pre><code><body>
<div>Div to be aligned vertically</div>
</body>
</code></pre>
<p>How can I center a <code>div</code> vertically in all major browsers, including Internet Explorer 6?</p> | <p>Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, <strong>flexible height</strong> content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer {
display: table;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
.middle {
display: table-cell;
vertical-align: middle;
}
.inner {
margin-left: auto;
margin-right: auto;
width: 400px;
/* Whatever width you want */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
<div class="middle">
<div class="inner">
<h1>The Content</h1>
<p>Once upon a midnight dreary...</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://emergentweb.com/test/valign.html" rel="noreferrer">View A Working Example With Dynamic Content</a></p>
<p>I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.</p> | {
"question_id": 396145,
"question_date": "2008-12-28T12:57:16.377Z",
"question_score": 1601,
"tags": "html|css|alignment|vertical-alignment|centering",
"answer_id": 6182661,
"answer_date": "2011-05-31T03:13:13.010Z",
"answer_score": 1527
} |
Please answer the following Stack Overflow question:
Title: Selecting multiple columns in a Pandas dataframe
<p>How do I select columns <code>a</code> and <code>b</code> from <code>df</code>, and save them into a new dataframe <code>df1</code>?</p>
<pre class="lang-none prettyprint-override"><code>index a b c
1 2 3 4
2 3 4 5
</code></pre>
<p>Unsuccessful attempt:</p>
<pre><code>df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']
</code></pre> | <p>The column names (which are strings) cannot be sliced in the manner you tried.</p>
<p>Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#basics" rel="noreferrer"><code>__getitem__</code> syntax</a> (the []'s).</p>
<pre><code>df1 = df[['a', 'b']]
</code></pre>
<p>Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead:</p>
<pre><code>df1 = df.iloc[:, 0:2] # Remember that Python does not slice inclusive of the ending index.
</code></pre>
<p>Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices).</p>
<p>Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. This will happen with the second way of indexing, so you can modify it with the <code>.copy()</code> method to get a regular copy. When this happens, changing what you think is the sliced object can sometimes alter the original object. Always good to be on the look out for this.</p>
<pre><code>df1 = df.iloc[0, 0:2].copy() # To avoid the case where changing df1 also changes df
</code></pre>
<p>To use <code>iloc</code>, you need to know the column positions (or indices). As the column positions may change, instead of hard-coding indices, you can use <code>iloc</code> along with <code>get_loc</code> function of <code>columns</code> method of dataframe object to obtain column indices.</p>
<pre><code>{df.columns.get_loc(c): c for idx, c in enumerate(df.columns)}
</code></pre>
<p>Now you can use this dictionary to access columns through names and using <code>iloc</code>.</p> | {
"question_id": 11285613,
"question_date": "2012-07-01T21:03:16.987Z",
"question_score": 1600,
"tags": "python|pandas|dataframe|select",
"answer_id": 11287278,
"answer_date": "2012-07-02T02:43:02.740Z",
"answer_score": 2482
} |
Please answer the following Stack Overflow question:
Title: Font scaling based on width of container
<p>I'm having a hard time getting my head around font scaling.</p>
<p>I currently have a website with a body <code>font-size</code> of 100%. 100% of what though? This seems to compute out at 16 pixels.</p>
<p>I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.</p>
<p>How can I make the text on my site scale in relation to its container? I tried using <code>em</code>, but this doesn't scale either.</p>
<p>My reasoning is that things like my menu become squished when you resize, so I need to reduce the <code>px</code> <code>font-size</code> of <code>.menuItem</code> among other elements in relation to the width of the container. (For example, in the menu on a large desktop, <code>22px</code> works perfectly. Move down to tablet width and <code>16px</code> is more appropriate.)</p>
<p>I'm aware I can add breakpoints, but I really want the text to scale as <em>well</em> as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.</p> | <p>If the container is not the body, CSS Tricks covers all of your options in <em><a href="https://css-tricks.com/fitting-text-to-a-container/" rel="noreferrer">Fitting Text to a Container</a></em>.</p>
<p>If the container is the body, what you are looking for is <a href="http://dev.w3.org/csswg/css-values/#viewport-relative-lengths" rel="noreferrer">Viewport-percentage lengths</a>:</p>
<blockquote>
<p>The <strong>viewport-percentage lengths</strong> are relative to the size of the <a href="https://www.w3.org/TR/CSS21/visudet.html#containing-block-details" rel="noreferrer">initial containing block</a>. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.</p>
</blockquote>
<p>The values are:</p>
<ul>
<li><code>vw</code> (% of the viewport width)</li>
<li><code>vh</code> (% of the viewport height)</li>
<li><code>vi</code> (1% of the viewport size in the direction of the root element's inline axis)</li>
<li><code>vb</code> (1% of the viewport size in the direction of the root element's block axis)</li>
<li><code>vmin</code> (the smaller of <code>vw</code> or <code>vh</code>)</li>
<li><code>vmax</code> (the larger or <code>vw</code> or <code>vh</code>)</li>
</ul>
<p>1 v* is equal to 1% of the initial containing block.</p>
<p>Using it looks like this:</p>
<pre><code>p {
font-size: 4vw;
}
</code></pre>
<p>As you can see, when the viewport width increases, so do the <code>font-size</code>, without needing to use media queries.</p>
<p>These values are a sizing unit, just like <code>px</code> or <code>em</code>, so they can be used to size other elements as well, such as width, margin, or padding.</p>
<p>Browser support is pretty good, but you'll likely need a fallback, such as:</p>
<pre><code>p {
font-size: 16px;
font-size: 4vw;
}
</code></pre>
<p>Check out the support statistics: <a href="http://caniuse.com/#feat=viewport-units" rel="noreferrer">http://caniuse.com/#feat=viewport-units</a>.</p>
<p>Also, check out CSS-Tricks for a broader look: <em><a href="http://css-tricks.com/viewport-sized-typography/" rel="noreferrer">Viewport Sized Typography</a></em></p>
<p>Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: <em><a href="http://madebymike.com.au/writing/precise-control-responsive-typography/" rel="noreferrer">Precise control over responsive typography</a></em></p>
<p>And here's an article about setting your size using calc() so that the text fills the viewport: <a href="http://codepen.io/CrocoDillon/pen/fBJxu" rel="noreferrer">http://codepen.io/CrocoDillon/pen/fBJxu</a></p>
<p>Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. <em><a href="https://css-tricks.com/molten-leading-css/" rel="noreferrer">Molten Leading in CSS</a></em></p> | {
"question_id": 16056591,
"question_date": "2013-04-17T09:37:18.587Z",
"question_score": 1597,
"tags": "css|responsive-design|font-size",
"answer_id": 19814948,
"answer_date": "2013-11-06T14:40:46.547Z",
"answer_score": 1758
} |
Please answer the following Stack Overflow question:
Title: How can I Remove .DS_Store files from a Git repository?
<p>How can I remove those annoying Mac OS X <code>.DS_Store</code> files from a Git repository?</p> | <p>Remove existing <code>.DS_Store</code> files from the repository:</p>
<pre><code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
</code></pre>
<p>Add this line:</p>
<pre><code>.DS_Store
</code></pre>
<p>to the file <code>.gitignore</code>, which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory:</p>
<pre><code>echo .DS_Store >> .gitignore
</code></pre>
<p>Then commit the file to the repo:</p>
<pre><code>git add .gitignore
git commit -m '.DS_Store banished!'
</code></pre> | {
"question_id": 107701,
"question_date": "2008-09-20T09:15:50.033Z",
"question_score": 1595,
"tags": "macos|git|gitignore",
"answer_id": 107921,
"answer_date": "2008-09-20T11:18:06.417Z",
"answer_score": 3111
} |
Please answer the following Stack Overflow question:
Title: Why do Python classes inherit object?
<p>Why does the following class declaration inherit from <code>object</code>?</p>
<pre><code>class MyClass(object):
...
</code></pre> | <blockquote>
<h3>Is there any reason for a class declaration to inherit from <code>object</code>?</h3>
</blockquote>
<p>In Python 3, apart from compatibility between Python 2 and 3, <em>no reason</em>. In Python 2, <em>many reasons</em>. </p>
<hr>
<h3>Python 2.x story:</h3>
<p>In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of <code>object</code> as a base-class:</p>
<ol>
<li><p><strong>"classic" style</strong> classes: they don't have <code>object</code> as a base class:</p>
<pre><code>>>> class ClassicSpam: # no base class
... pass
>>> ClassicSpam.__bases__
()
</code></pre></li>
<li><p><strong>"new" style</strong> classes: they have, directly <em>or indirectly</em> (e.g inherit from a <a href="https://docs.python.org/3/library/stdtypes.html" rel="noreferrer">built-in type</a>), <code>object</code> as a base class:</p>
<pre><code>>>> class NewSpam(object): # directly inherit from object
... pass
>>> NewSpam.__bases__
(<type 'object'>,)
>>> class IntSpam(int): # indirectly inherit from object...
... pass
>>> IntSpam.__bases__
(<type 'int'>,)
>>> IntSpam.__bases__[0].__bases__ # ... because int inherits from object
(<type 'object'>,)
</code></pre></li>
</ol>
<p>Without a doubt, when writing a class you'll <em>always</em> want to go for new-style classes. The perks of doing so are numerous, to list some of them:</p>
<ul>
<li><p><a href="https://docs.python.org/3/howto/descriptor.html" rel="noreferrer">Support for descriptors</a>. Specifically, the following constructs are made possible with descriptors: </p>
<ol>
<li><a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer"><code>classmethod</code></a>: A method that receives the class as an implicit argument instead of the instance.</li>
<li><a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer"><code>staticmethod</code></a>: A method that does not receive the implicit argument <code>self</code> as a first argument.</li>
<li>properties with <a href="https://docs.python.org/3/library/functions.html#property" rel="noreferrer"><code>property</code></a>: Create functions for managing the getting, setting and deleting of an attribute. </li>
<li><a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="noreferrer"><code>__slots__</code></a>: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does <a href="https://docs.python.org/3/reference/datamodel.html#notes-on-using-slots" rel="noreferrer">impose limitations</a>.</li>
</ol></li>
<li><p>The <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="noreferrer"><code>__new__</code></a> static method: lets you customize how new class instances are created. </p></li>
<li><p><a href="https://www.python.org/download/releases/2.3/mro/" rel="noreferrer">Method resolution order (MRO)</a>: in what order the base classes of a class will be searched when trying to resolve which method to call. </p></li>
<li><p>Related to MRO, <a href="https://docs.python.org/3/library/functions.html#super" rel="noreferrer"><code>super</code> calls</a>. Also see, <a href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="noreferrer"><code>super()</code> considered super.</a></p></li>
</ul>
<p>If you don't inherit from <code>object</code>, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found <a href="https://www.python.org/download/releases/2.2.3/descrintro/" rel="noreferrer">here</a>.</p>
<p>One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.</p>
<hr>
<h3>Python 3.x story:</h3>
<p>In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding <code>object</code> is requiring you to type in 8 more characters. This:</p>
<pre><code>class ClassicSpam:
pass
</code></pre>
<p>is completely equivalent (apart from their name :-) to this:</p>
<pre><code>class NewSpam(object):
pass
</code></pre>
<p>and to this:</p>
<pre><code>class Spam():
pass
</code></pre>
<p>All have <code>object</code> in their <code>__bases__</code>.</p>
<pre><code>>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]
</code></pre>
<hr>
<h2>So, what should you do?</h2>
<p><strong>In Python 2:</strong> <em>always inherit from <code>object</code> explicitly</em>. Get the perks.</p>
<p><strong>In Python 3:</strong> inherit from <code>object</code> if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.</p> | {
"question_id": 4015417,
"question_date": "2010-10-25T14:15:26.433Z",
"question_score": 1593,
"tags": "python|class|oop|object|inheritance",
"answer_id": 45062077,
"answer_date": "2017-07-12T15:34:59.537Z",
"answer_score": 1135
} |
Please answer the following Stack Overflow question:
Title: Cycles in family tree software
<p>I am the developer of some family tree software (written in C++ and Qt). I had no problems until one of my customers mailed me a bug report. The problem is that the customer has two children with their own daughter, and, as a result, he can't use my software because of errors.</p>
<p>Those errors are the result of my various assertions and invariants about the family graph being processed (for example, after walking a cycle, the program states that X can't be both father and grandfather of Y).</p>
<p>How can I resolve those errors without removing all data assertions?</p> | <p>It seems you (and/or your company) have a fundamental misunderstanding of what a family tree is supposed to be. </p>
<p>Let me clarify, I also work for a company that has (as one of its products) a family tree in its portfolio, and we have been struggling with similar problems.</p>
<p>The problem, in our case, and I assume your case as well, comes from the <a href="http://en.wikipedia.org/wiki/GEDCOM" rel="noreferrer">GEDCOM</a> format that is extremely opinionated about what a family should be. However this format contains some severe misconceptions about what a family tree really looks like.</p>
<p>GEDCOM has many issues, such as incompatibility with same sex relations, incest, etc... Which in real life happens more often than you'd imagine (especially when going back in time to the 1700-1800).</p>
<p>We have modeled our family tree to what happens in the real world: Events (for example, births, weddings, engagement, unions, deaths, adoptions, etc.). We do not put any restrictions on these, except for logically impossible ones (for example, one can't be one's own parent, relations need two individuals, etc...)</p>
<p>The lack of validations gives us a more "real world", simpler and more flexible solution.</p>
<p>As for this specific case, I would suggest removing the assertions as they do not hold universally.</p>
<p>For displaying issues (that will arise) I would suggest drawing the same node as many times as needed, hinting at the duplication by lighting up all the copies on selecting one of them.</p> | {
"question_id": 6163683,
"question_date": "2011-05-28T18:39:28.277Z",
"question_score": 1590,
"tags": "c++|graph|cycle|assertions|family-tree",
"answer_id": 6198257,
"answer_date": "2011-06-01T08:25:09.467Z",
"answer_score": 726
} |
Please answer the following Stack Overflow question:
Title: Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs
<p>I was looking for the fastest way to <code>popcount</code> large arrays of data. I encountered a <em>very weird</em> effect: Changing the loop variable from <code>unsigned</code> to <code>uint64_t</code> made the performance drop by 50% on my PC.</p>
<h2>The Benchmark</h2>
<pre><code>#include <iostream>
#include <chrono>
#include <x86intrin.h>
int main(int argc, char* argv[]) {
using namespace std;
if (argc != 2) {
cerr << "usage: array_size in MB" << endl;
return -1;
}
uint64_t size = atol(argv[1])<<20;
uint64_t* buffer = new uint64_t[size/8];
char* charbuffer = reinterpret_cast<char*>(buffer);
for (unsigned i=0; i<size; ++i)
charbuffer[i] = rand()%256;
uint64_t count,duration;
chrono::time_point<chrono::system_clock> startP,endP;
{
startP = chrono::system_clock::now();
count = 0;
for( unsigned k = 0; k < 10000; k++){
// Tight unrolled loop with unsigned
for (unsigned i=0; i<size/8; i+=4) {
count += _mm_popcnt_u64(buffer[i]);
count += _mm_popcnt_u64(buffer[i+1]);
count += _mm_popcnt_u64(buffer[i+2]);
count += _mm_popcnt_u64(buffer[i+3]);
}
}
endP = chrono::system_clock::now();
duration = chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "unsigned\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
{
startP = chrono::system_clock::now();
count=0;
for( unsigned k = 0; k < 10000; k++){
// Tight unrolled loop with uint64_t
for (uint64_t i=0;i<size/8;i+=4) {
count += _mm_popcnt_u64(buffer[i]);
count += _mm_popcnt_u64(buffer[i+1]);
count += _mm_popcnt_u64(buffer[i+2]);
count += _mm_popcnt_u64(buffer[i+3]);
}
}
endP = chrono::system_clock::now();
duration = chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "uint64_t\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
free(charbuffer);
}
</code></pre>
<p>As you see, we create a buffer of random data, with the size being <code>x</code> megabytes where <code>x</code> is read from the command line. Afterwards, we iterate over the buffer and use an unrolled version of the x86 <code>popcount</code> intrinsic to perform the popcount. To get a more precise result, we do the popcount 10,000 times. We measure the times for the popcount. In the upper case, the inner loop variable is <code>unsigned</code>, in the lower case, the inner loop variable is <code>uint64_t</code>. I thought that this should make no difference, but the opposite is the case.</p>
<h2>The (absolutely crazy) results</h2>
<p>I compile it like this (g++ version: Ubuntu 4.8.2-19ubuntu1):</p>
<pre><code>g++ -O3 -march=native -std=c++11 test.cpp -o test
</code></pre>
<p>Here are the results on my <a href="http://en.wikipedia.org/wiki/Haswell_%28microarchitecture%29" rel="noreferrer">Haswell</a> <a href="http://en.wikipedia.org/wiki/Haswell_%28microarchitecture%29#Desktop_processors" rel="noreferrer">Core i7-4770K</a> CPU @ 3.50 GHz, running <code>test 1</code> (so 1 MB random data):</p>
<ul>
<li>unsigned 41959360000 0.401554 sec <strong>26.113 GB/s</strong></li>
<li>uint64_t 41959360000 0.759822 sec <strong>13.8003 GB/s</strong></li>
</ul>
<p>As you see, the throughput of the <code>uint64_t</code> version is <strong>only half</strong> the one of the <code>unsigned</code> version! The problem seems to be that different assembly gets generated, but why? First, I thought of a compiler bug, so I tried <code>clang++</code> (Ubuntu <a href="http://en.wikipedia.org/wiki/Clang" rel="noreferrer">Clang</a> version 3.4-1ubuntu3):</p>
<pre><code>clang++ -O3 -march=native -std=c++11 teest.cpp -o test
</code></pre>
<p>Result: <code>test 1</code></p>
<ul>
<li>unsigned 41959360000 0.398293 sec <strong>26.3267 GB/s</strong></li>
<li>uint64_t 41959360000 0.680954 sec <strong>15.3986 GB/s</strong></li>
</ul>
<p>So, it is almost the same result and is still strange. <em>But now it gets super strange.</em> I replace the buffer size that was read from input with a constant <code>1</code>, so I change:</p>
<pre><code>uint64_t size = atol(argv[1]) << 20;
</code></pre>
<p>to</p>
<pre><code>uint64_t size = 1 << 20;
</code></pre>
<p>Thus, the compiler now knows the buffer size at compile time. Maybe it can add some optimizations! Here are the numbers for <code>g++</code>:</p>
<ul>
<li>unsigned 41959360000 0.509156 sec <strong>20.5944 GB/s</strong></li>
<li>uint64_t 41959360000 0.508673 sec <strong>20.6139 GB/s</strong></li>
</ul>
<p>Now, both versions are equally fast. However, the <code>unsigned</code> <strong>got even slower</strong>! It dropped from <code>26</code> to <code>20 GB/s</code>, thus replacing a non-constant by a constant value lead to a <strong>deoptimization</strong>. Seriously, I have no clue what is going on here! But now to <code>clang++</code> with the new version:</p>
<ul>
<li>unsigned 41959360000 0.677009 sec <strong>15.4884 GB/s</strong></li>
<li>uint64_t 41959360000 0.676909 sec <strong>15.4906 GB/s</strong></li>
</ul>
<p><em>Wait, what?</em> Now, both versions dropped to the <strong>slow</strong> number of 15 GB/s. Thus, replacing a non-constant by a constant value even lead to slow code in <strong>both</strong> cases for Clang!</p>
<p>I asked a colleague with an <a href="http://en.wikipedia.org/wiki/Ivy_Bridge_%28microarchitecture%29" rel="noreferrer">Ivy Bridge</a> CPU to compile my benchmark. He got similar results, so it does not seem to be Haswell. Because two compilers produce strange results here, it also does not seem to be a compiler bug. We do not have an AMD CPU here, so we could only test with Intel.</p>
<h2>More madness, please!</h2>
<p>Take the first example (the one with <code>atol(argv[1])</code>) and put a <code>static</code> before the variable, i.e.:</p>
<pre><code>static uint64_t size=atol(argv[1])<<20;
</code></pre>
<p>Here are my results in g++:</p>
<ul>
<li>unsigned 41959360000 0.396728 sec <strong>26.4306 GB/s</strong></li>
<li>uint64_t 41959360000 0.509484 sec <strong>20.5811 GB/s</strong></li>
</ul>
<p><em>Yay, yet another alternative</em>. We still have the fast 26 GB/s with <code>u32</code>, but we managed to get <code>u64</code> at least from the 13 GB/s to the 20 GB/s version! <strong>On my collegue's PC, the <code>u64</code> version became even faster than the <code>u32</code> version, yielding the fastest result of all.</strong> Sadly, this only works for <code>g++</code>, <code>clang++</code> does not seem to care about <code>static</code>.</p>
<h2>My question</h2>
<p>Can you explain these results? Especially:</p>
<ul>
<li>How can there be such a difference between <code>u32</code> and <code>u64</code>?</li>
<li>How can replacing a non-constant by a constant buffer size trigger <em>less optimal code</em>?</li>
<li>How can the insertion of the <code>static</code> keyword make the <code>u64</code> loop faster? Even faster than the original code on my collegue's computer!</li>
</ul>
<p>I know that optimization is a tricky territory, however, I never thought that such small changes can lead to a <strong>100% difference</strong> in execution time and that small factors like a constant buffer size can again mix results totally. Of course, I always want to have the version that is able to popcount 26 GB/s. The only reliable way I can think of is copy paste the assembly for this case and use inline assembly. This is the only way I can get rid of compilers that seem to go mad on small changes. What do you think? Is there another way to reliably get the code with most performance?</p>
<h2>The Disassembly</h2>
<p>Here is the disassembly for the various results:</p>
<p>26 GB/s version from <strong>g++ / u32 / non-const bufsize</strong>:</p>
<pre><code>0x400af8:
lea 0x1(%rdx),%eax
popcnt (%rbx,%rax,8),%r9
lea 0x2(%rdx),%edi
popcnt (%rbx,%rcx,8),%rax
lea 0x3(%rdx),%esi
add %r9,%rax
popcnt (%rbx,%rdi,8),%rcx
add $0x4,%edx
add %rcx,%rax
popcnt (%rbx,%rsi,8),%rcx
add %rcx,%rax
mov %edx,%ecx
add %rax,%r14
cmp %rbp,%rcx
jb 0x400af8
</code></pre>
<p>13 GB/s version from <strong>g++ / u64 / non-const bufsize</strong>:</p>
<pre><code>0x400c00:
popcnt 0x8(%rbx,%rdx,8),%rcx
popcnt (%rbx,%rdx,8),%rax
add %rcx,%rax
popcnt 0x10(%rbx,%rdx,8),%rcx
add %rcx,%rax
popcnt 0x18(%rbx,%rdx,8),%rcx
add $0x4,%rdx
add %rcx,%rax
add %rax,%r12
cmp %rbp,%rdx
jb 0x400c00
</code></pre>
<p>15 GB/s version from <strong>clang++ / u64 / non-const bufsize</strong>:</p>
<pre><code>0x400e50:
popcnt (%r15,%rcx,8),%rdx
add %rbx,%rdx
popcnt 0x8(%r15,%rcx,8),%rsi
add %rdx,%rsi
popcnt 0x10(%r15,%rcx,8),%rdx
add %rsi,%rdx
popcnt 0x18(%r15,%rcx,8),%rbx
add %rdx,%rbx
add $0x4,%rcx
cmp %rbp,%rcx
jb 0x400e50
</code></pre>
<p>20 GB/s version from <strong>g++ / u32&u64 / const bufsize</strong>:</p>
<pre><code>0x400a68:
popcnt (%rbx,%rdx,1),%rax
popcnt 0x8(%rbx,%rdx,1),%rcx
add %rax,%rcx
popcnt 0x10(%rbx,%rdx,1),%rax
add %rax,%rcx
popcnt 0x18(%rbx,%rdx,1),%rsi
add $0x20,%rdx
add %rsi,%rcx
add %rcx,%rbp
cmp $0x100000,%rdx
jne 0x400a68
</code></pre>
<p>15 GB/s version from <strong>clang++ / u32&u64 / const bufsize</strong>:</p>
<pre><code>0x400dd0:
popcnt (%r14,%rcx,8),%rdx
add %rbx,%rdx
popcnt 0x8(%r14,%rcx,8),%rsi
add %rdx,%rsi
popcnt 0x10(%r14,%rcx,8),%rdx
add %rsi,%rdx
popcnt 0x18(%r14,%rcx,8),%rbx
add %rdx,%rbx
add $0x4,%rcx
cmp $0x20000,%rcx
jb 0x400dd0
</code></pre>
<p>Interestingly, the fastest (26 GB/s) version is also the longest! It seems to be the only solution that uses <code>lea</code>. Some versions use <code>jb</code> to jump, others use <code>jne</code>. But apart from that, all versions seem to be comparable. I don't see where a 100% performance gap could originate from, but I am not too adept at deciphering assembly. The slowest (13 GB/s) version looks even very short and good. Can anyone explain this?</p>
<h2>Lessons learned</h2>
<p>No matter what the answer to this question will be; I have learned that in really hot loops <em>every</em> detail can matter, <em>even details that do not seem to have any association to the hot code</em>. I have never thought about what type to use for a loop variable, but as you see such a minor change can make a <em>100%</em> difference! Even the storage type of a buffer can make a huge difference, as we saw with the insertion of the <code>static</code> keyword in front of the size variable! In the future, I will always test various alternatives on various compilers when writing really tight and hot loops that are crucial for system performance.</p>
<p>The interesting thing is also that the performance difference is still so high although I have already unrolled the loop four times. So even if you unroll, you can still get hit by major performance deviations. Quite interesting.</p> | <p><strong>Culprit: False Data Dependency</strong> (and the compiler isn't even aware of it)</p>
<p>On Sandy/Ivy Bridge and Haswell processors, the instruction:</p>
<pre><code>popcnt src, dest
</code></pre>
<p>appears to have a false dependency on the destination register <code>dest</code>. Even though the instruction only writes to it, the instruction will wait until <code>dest</code> is ready before executing. This false dependency is (now) documented by Intel as erratum <a href="https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/4th-gen-core-family-desktop-specification-update.pdf" rel="noreferrer">HSD146 (Haswell)</a> and <a href="https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/desktop-6th-gen-core-family-spec-update.pdf" rel="noreferrer">SKL029 (Skylake)</a></p>
<p><a href="https://stackoverflow.com/questions/21390165/why-does-breaking-the-output-dependency-of-lzcnt-matter">Skylake fixed this for <code>lzcnt</code> and <code>tzcnt</code></a>.<br>
Cannon Lake (and Ice Lake) fixed this for <code>popcnt</code>.<br>
<code>bsf</code>/<code>bsr</code> have a true output dependency: output unmodified for input=0. (But <a href="https://stackoverflow.com/questions/41351564/vs-unexpected-optimization-behavior-with-bitscanreverse64-intrinsic/41352456#41352456">no way to take advantage of that with intrinsics</a> - only AMD documents it and compilers don't expose it.)</p>
<p>(Yes, these instructions all run <a href="https://stackoverflow.com/questions/28802692/how-is-popcnt-implemented-in-hardware">on the same execution unit</a>).</p>
<hr>
<p>This dependency doesn't just hold up the 4 <code>popcnt</code>s from a single loop iteration. It can carry across loop iterations making it impossible for the processor to parallelize different loop iterations.</p>
<p>The <code>unsigned</code> vs. <code>uint64_t</code> and other tweaks don't directly affect the problem. But they influence the register allocator which assigns the registers to the variables.</p>
<p>In your case, the speeds are a direct result of what is stuck to the (false) dependency chain depending on what the register allocator decided to do.</p>
<ul>
<li>13 GB/s has a chain: <code>popcnt</code>-<code>add</code>-<code>popcnt</code>-<code>popcnt</code> → next iteration</li>
<li>15 GB/s has a chain: <code>popcnt</code>-<code>add</code>-<code>popcnt</code>-<code>add</code> → next iteration</li>
<li>20 GB/s has a chain: <code>popcnt</code>-<code>popcnt</code> → next iteration</li>
<li>26 GB/s has a chain: <code>popcnt</code>-<code>popcnt</code> → next iteration</li>
</ul>
<p>The difference between 20 GB/s and 26 GB/s seems to be a minor artifact of the indirect addressing. Either way, the processor starts to hit other bottlenecks once you reach this speed.</p>
<hr>
<p>To test this, I used inline assembly to bypass the compiler and get exactly the assembly I want. I also split up the <code>count</code> variable to break all other dependencies that might mess with the benchmarks.</p>
<p>Here are the results:</p>
<p><strong>Sandy Bridge Xeon @ 3.5 GHz:</strong> (full test code can be found at the bottom)</p>
<ul>
<li>GCC 4.6.3: <code>g++ popcnt.cpp -std=c++0x -O3 -save-temps -march=native</code></li>
<li>Ubuntu 12</li>
</ul>
<p>Different Registers: <strong>18.6195 GB/s</strong></p>
<pre><code>.L4:
movq (%rbx,%rax,8), %r8
movq 8(%rbx,%rax,8), %r9
movq 16(%rbx,%rax,8), %r10
movq 24(%rbx,%rax,8), %r11
addq $4, %rax
popcnt %r8, %r8
add %r8, %rdx
popcnt %r9, %r9
add %r9, %rcx
popcnt %r10, %r10
add %r10, %rdi
popcnt %r11, %r11
add %r11, %rsi
cmpq $131072, %rax
jne .L4
</code></pre>
<p>Same Register: <strong>8.49272 GB/s</strong></p>
<pre><code>.L9:
movq (%rbx,%rdx,8), %r9
movq 8(%rbx,%rdx,8), %r10
movq 16(%rbx,%rdx,8), %r11
movq 24(%rbx,%rdx,8), %rbp
addq $4, %rdx
# This time reuse "rax" for all the popcnts.
popcnt %r9, %rax
add %rax, %rcx
popcnt %r10, %rax
add %rax, %rsi
popcnt %r11, %rax
add %rax, %r8
popcnt %rbp, %rax
add %rax, %rdi
cmpq $131072, %rdx
jne .L9
</code></pre>
<p>Same Register with broken chain: <strong>17.8869 GB/s</strong></p>
<pre><code>.L14:
movq (%rbx,%rdx,8), %r9
movq 8(%rbx,%rdx,8), %r10
movq 16(%rbx,%rdx,8), %r11
movq 24(%rbx,%rdx,8), %rbp
addq $4, %rdx
# Reuse "rax" for all the popcnts.
xor %rax, %rax # Break the cross-iteration dependency by zeroing "rax".
popcnt %r9, %rax
add %rax, %rcx
popcnt %r10, %rax
add %rax, %rsi
popcnt %r11, %rax
add %rax, %r8
popcnt %rbp, %rax
add %rax, %rdi
cmpq $131072, %rdx
jne .L14
</code></pre>
<hr>
<p><strong>So what went wrong with the compiler?</strong></p>
<p>It seems that neither GCC nor Visual Studio are aware that <code>popcnt</code> has such a false dependency. Nevertheless, these false dependencies aren't uncommon. It's just a matter of whether the compiler is aware of it.</p>
<p><code>popcnt</code> isn't exactly the most used instruction. So it's not really a surprise that a major compiler could miss something like this. There also appears to be no documentation anywhere that mentions this problem. If Intel doesn't disclose it, then nobody outside will know until someone runs into it by chance.</p>
<p>(<strong>Update:</strong> <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011#c13" rel="noreferrer">As of version 4.9.2</a>, GCC is aware of this false-dependency and generates code to compensate it when optimizations are enabled. Major compilers from other vendors, including Clang, MSVC, and even Intel's own ICC are not yet aware of this microarchitectural erratum and will not emit code that compensates for it.)</p>
<p><strong>Why does the CPU have such a false dependency?</strong></p>
<p>We can speculate: it runs on the same execution unit as <code>bsf</code> / <code>bsr</code> which <em>do</em> have an output dependency. (<a href="https://stackoverflow.com/questions/28802692/how-is-popcnt-implemented-in-hardware">How is POPCNT implemented in hardware?</a>). For those instructions, Intel documents the integer result for input=0 as "undefined" (with ZF=1), but Intel hardware actually gives a stronger guarantee to avoid breaking old software: output unmodified. AMD documents this behaviour.</p>
<p>Presumably it was somehow inconvenient to make some uops for this execution unit dependent on the output but others not.</p>
<p>AMD processors do not appear to have this false dependency.</p>
<hr>
<p>The full test code is below for reference:</p>
<pre><code>#include <iostream>
#include <chrono>
#include <x86intrin.h>
int main(int argc, char* argv[]) {
using namespace std;
uint64_t size=1<<20;
uint64_t* buffer = new uint64_t[size/8];
char* charbuffer=reinterpret_cast<char*>(buffer);
for (unsigned i=0;i<size;++i) charbuffer[i]=rand()%256;
uint64_t count,duration;
chrono::time_point<chrono::system_clock> startP,endP;
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"popcnt %6, %6 \n\t"
"add %6, %2 \n\t"
"popcnt %7, %7 \n\t"
"add %7, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "No Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"popcnt %4, %%rax \n\t"
"add %%rax, %0 \n\t"
"popcnt %5, %%rax \n\t"
"add %%rax, %1 \n\t"
"popcnt %6, %%rax \n\t"
"add %%rax, %2 \n\t"
"popcnt %7, %%rax \n\t"
"add %%rax, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
: "rax"
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "Chain 4 \t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"xor %%rax, %%rax \n\t" // <--- Break the chain.
"popcnt %4, %%rax \n\t"
"add %%rax, %0 \n\t"
"popcnt %5, %%rax \n\t"
"add %%rax, %1 \n\t"
"popcnt %6, %%rax \n\t"
"add %%rax, %2 \n\t"
"popcnt %7, %%rax \n\t"
"add %%rax, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
: "rax"
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "Broken Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
free(charbuffer);
}
</code></pre>
<hr>
<p>An equally interesting benchmark can be found here: <a href="http://pastebin.com/kbzgL8si" rel="noreferrer">http://pastebin.com/kbzgL8si</a>
<br>
This benchmark varies the number of <code>popcnt</code>s that are in the (false) dependency chain.</p>
<pre><code>False Chain 0: 41959360000 0.57748 sec 18.1578 GB/s
False Chain 1: 41959360000 0.585398 sec 17.9122 GB/s
False Chain 2: 41959360000 0.645483 sec 16.2448 GB/s
False Chain 3: 41959360000 0.929718 sec 11.2784 GB/s
False Chain 4: 41959360000 1.23572 sec 8.48557 GB/s
</code></pre> | {
"question_id": 25078285,
"question_date": "2014-08-01T10:33:29.093Z",
"question_score": 1589,
"tags": "c++|performance|assembly|x86|compiler-optimization",
"answer_id": 25089720,
"answer_date": "2014-08-01T22:41:20.200Z",
"answer_score": 1699
} |
Please answer the following Stack Overflow question:
Title: How do I profile a Python script?
<p><a href="http://en.wikipedia.org/wiki/Project_Euler" rel="noreferrer">Project Euler</a> and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to <code>__main__</code>.</p>
<p>What is a good way to profile how long a Python program takes to run?</p> | <p>Python includes a profiler called <a href="https://docs.python.org/3/library/profile.html#module-cProfile" rel="noreferrer">cProfile</a>. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.</p>
<p>You can call it from within your code, or from the interpreter, like this:</p>
<pre><code>import cProfile
cProfile.run('foo()')
</code></pre>
<p>Even more usefully, you can invoke the cProfile when running a script:</p>
<pre><code>python -m cProfile myscript.py
</code></pre>
<p>To make it even easier, I made a little batch file called 'profile.bat':</p>
<pre><code>python -m cProfile %1
</code></pre>
<p>So all I have to do is run:</p>
<pre><code>profile euler048.py
</code></pre>
<p>And I get this:</p>
<pre class="lang-none prettyprint-override"><code>1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
</code></pre>
<p>EDIT: Updated link to a good video resource from PyCon 2013 titled
<a href="https://web.archive.org/web/20170318204046/http://lanyrd.com/2013/pycon/scdywg/" rel="noreferrer"><strong><em>Python Profiling</em></strong></a><br>
<a href="https://www.youtube.com/watch?v=QJwVYlDzAXs" rel="noreferrer">Also via YouTube</a>.</p> | {
"question_id": 582336,
"question_date": "2009-02-24T16:01:26.610Z",
"question_score": 1587,
"tags": "python|performance|optimization|time-complexity|profiling",
"answer_id": 582337,
"answer_date": "2009-02-24T16:01:40.570Z",
"answer_score": 1640
} |
Please answer the following Stack Overflow question:
Title: Get size of all tables in database
<p>I have inherited a fairly large SQL Server database. It seems to take up more space than I would expect, given the data it contains.</p>
<p>Is there an easy way to determine how much space on disk each table is consuming?</p> | <pre><code>SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
TotalSpaceMB DESC, t.Name
</code></pre> | {
"question_id": 7892334,
"question_date": "2011-10-25T16:14:34.197Z",
"question_score": 1585,
"tags": "sql-server|tsql",
"answer_id": 7892349,
"answer_date": "2011-10-25T16:16:02.473Z",
"answer_score": 3194
} |
Please answer the following Stack Overflow question:
Title: How do I migrate an SVN repository with history to a new Git repository?
<p>I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:</p>
<p>SVN repository in: <code>svn://myserver/path/to/svn/repos</code></p>
<p>Git repository in: <code>git://myserver/path/to/git/repos</code></p>
<pre><code>git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos
</code></pre>
<p>I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.</p> | <p>Magic:</p>
<pre><code>$ git svn clone http://svn/repo/here/trunk
</code></pre>
<p>Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn <code>git-svn</code>. The <code>git-svn</code> <a href="https://git-scm.com/docs/git-svn" rel="noreferrer">main page has a good examples section</a>:</p>
<pre><code>$ git svn --help
</code></pre> | {
"question_id": 79165,
"question_date": "2008-09-17T02:04:20.853Z",
"question_score": 1585,
"tags": "svn|git|version-control|git-svn",
"answer_id": 79178,
"answer_date": "2008-09-17T02:08:25.197Z",
"answer_score": 548
} |
Please answer the following Stack Overflow question:
Title: Reverse a string in Python
<p>There is no built in <code>reverse</code> function for Python's <code>str</code> object. What is the best way of implementing this method?</p>
<p>If supplying a very concise answer, please elaborate on its efficiency. For example, whether the <code>str</code> object is converted to a different object, etc. </p> | <p>Using <a href="https://stackoverflow.com/questions/509211/understanding-slicing">slicing</a>:</p>
<pre><code>>>> 'hello world'[::-1]
'dlrow olleh'
</code></pre>
<hr />
<p>Slice notation takes the form <code>[start:stop:step]</code>. In this case, we omit the <code>start</code> and <code>stop</code> positions since we want the whole string. We also use <code>step = -1</code>, which means, "repeatedly step from right to left by 1 character".</p> | {
"question_id": 931092,
"question_date": "2009-05-31T02:10:10.377Z",
"question_score": 1584,
"tags": "python|string",
"answer_id": 931095,
"answer_date": "2009-05-31T02:11:46.380Z",
"answer_score": 2989
} |
Please answer the following Stack Overflow question:
Title: Compiling an application for use in highly radioactive environments
<p>We are compiling an embedded C++ application that is deployed in a shielded device in an environment bombarded with <a href="https://en.wikipedia.org/wiki/Ionizing_radiation" rel="noreferrer">ionizing radiation</a>. We are using GCC and cross-compiling for ARM. When deployed, our application generates some erroneous data and crashes more often than we would like. The hardware is designed for this environment, and our application has run on this platform for several years.</p>
<p>Are there changes we can make to our code, or compile-time improvements that can be made to identify/correct <a href="https://en.wikipedia.org/wiki/Soft_error" rel="noreferrer">soft errors</a> and memory-corruption caused by <a href="https://en.wikipedia.org/wiki/Single_event_upset" rel="noreferrer">single event upsets</a>? Have any other developers had success in reducing the harmful effects of soft errors on a long-running application?</p> | <p>Working for about 4-5 years with software/firmware development and environment testing of <a href="https://en.wikipedia.org/wiki/Miniaturized_satellite">miniaturized satellites</a>*, I would like to share my experience here.</p>
<p>*(<em>miniaturized satellites are a lot more prone to single event upsets than bigger satellites due to its relatively small, limited sizes for its electronic components</em>)</p>
<blockquote>
<p>To be very concise and direct: there is no mechanism to recover from <em>detectable, erroneous
situation</em> by the software/firmware itself <em>without</em>, at least, one
<em>copy</em> of <em>minimum working version</em> of the software/firmware <em>somewhere</em> for <em>recovery</em> purpose - and with the <em>hardware supporting the recovery</em> (functional).</p>
</blockquote>
<p>Now, this situation is normally handled both in the hardware and software level. Here, as you request, I will share what we can do in the software level.</p>
<ol>
<li><p><strong>...recovery purpose...</strong>. Provide ability to update/recompile/reflash your software/firmware in real environment. This is an <em>almost must-have</em> feature for any software/firmware in highly ionized environment. Without this, you <em>could</em> have redundant software/hardware as many as you want but at one point, they are all going to blow up. So, prepare this feature!</p></li>
<li><p><strong>...minimum working version...</strong> Have responsive, multiple copies, minimum version of the software/firmware in your code. This is like Safe mode in Windows. Instead of having only one, fully functional version of your software, have multiple copies of the minimum version of your software/firmware. The minimum copy will usually having much less size than the full copy and almost always have <em>only</em> the following two or three features: </p>
<ol>
<li>capable of listening to command from external system, </li>
<li>capable of updating the current software/firmware, </li>
<li>capable of monitoring the basic operation's housekeeping data.</li>
</ol></li>
<li><p><strong>...copy... somewhere...</strong> Have redundant software/firmware somewhere. </p>
<ol>
<li><p>You could, with <em>or</em> without redundant hardware, try to have redundant software/firmware in your ARM uC. This is normally done by having two or more identical software/firmware <em>in separate addresses</em> which sending heartbeat to each other - but only one will be active at a time. If one or more software/firmware is known to be unresponsive, switch to the other software/firmware. The benefit of using this approach is we can have functional replacement immediately after an error occurs - without any contact with whatever external system/party who is responsible to detect and to repair the error (in satellite case, it is usually the Mission Control Centre (MCC)). </p>
<p>Strictly speaking, without redundant hardware, the disadvantage of doing this is you actually <em>cannot</em> eliminate <em>all</em> single point of failures. At the very least, you will still have <em>one</em> single point of failure, which is <em>the switch itself</em> (or often the beginning of the code). Nevertheless, for a device limited by size in a highly ionized environment (such as pico/femto satellites), the reduction of the single point of failures to one point <em>without</em> additional hardware will still be worth considering. Somemore, the piece of code for the switching would certainly be much less than the code for the whole program - significantly reducing the risk of getting Single Event in it.</p></li>
<li><p>But if you are not doing this, you should have at least one copy in your external system which can come in contact with the device and update the software/firmware (in the satellite case, it is again the mission control centre). </p></li>
<li>You could also have the copy in your permanent memory storage in your device which can be triggered to restore the running system's software/firmware</li>
</ol></li>
<li><p><strong>...detectable erroneous situation..</strong> The error must be <em>detectable</em>, usually by the hardware <em>error correction/detection circuit</em> or by a small piece of code for error correction/detection. It is best to put such code small, multiple, and <em>independent</em> from the main software/firmware. Its main task is <em>only</em> for checking/correcting. If the hardware circuit/firmware is <em>reliable</em> (such as it is more radiation hardened than the rests - or having multiple circuits/logics), then you might consider making error-correction with it. But if it is not, it is better to make it as error-detection. The correction can be by external system/device. For the error correction, you could consider making use of a basic error correction algorithm like Hamming/Golay23, because they can be implemented more easily both in the circuit/software. But it ultimately depends on your team's capability. For error detection, normally CRC is used.</p></li>
<li><p><strong>...hardware supporting the recovery</strong> Now, comes to the most difficult aspect on this issue. Ultimately, the recovery requires the hardware which is responsible for the recovery to be <em>at least</em> functional. If the hardware is permanently broken (normally happen after its <strong>Total ionizing dose</strong> reaches certain level), then there is (sadly) no way for the software to help in recovery. Thus, hardware is rightly the utmost importance concern for a device exposed to high radiation level (such as satellite). </p></li>
</ol>
<p>In addition to the suggestion for above anticipating firmware's error due to single event upset, I would also like to suggest you to have:</p>
<ol>
<li><p>Error detection and/or error correction algorithm in the inter-subsystem communication protocol. This is another almost must have in order to avoid incomplete/wrong signals received from other system</p></li>
<li><p>Filter in your ADC reading. Do <em>not</em> use the ADC reading directly. Filter it by median filter, mean filter, or any other filters - <em>never</em> trust single reading value. Sample more, not less - reasonably.</p></li>
</ol> | {
"question_id": 36827659,
"question_date": "2016-04-24T19:09:40.713Z",
"question_score": 1584,
"tags": "c++|c|gcc|embedded|fault-tolerance",
"answer_id": 36831344,
"answer_date": "2016-04-25T02:58:30.850Z",
"answer_score": 875
} |
Please answer the following Stack Overflow question:
Title: How to specify the private SSH-key to use when executing shell command on Git?
<p>A rather unusual situation perhaps, but I want to specify a private SSH-key to use when executing a shell (<code>git</code>) command from the local computer.</p>
<p>Basically like this:</p>
<pre><code>git clone [email protected]:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"
</code></pre>
<p>Or even better (in Ruby):</p>
<pre><code>with_key("/home/christoffer/ssh_keys/theuser") do
sh("git clone [email protected]:TheUser/TheProject.git")
end
</code></pre>
<p>I have seen examples of connecting to a remote server with <code>Net::SSH</code> that uses a specified private key, but this is a local command. Is it possible?</p> | <p>Something like this should work (suggested by orip):</p>
<pre><code>ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'
</code></pre>
<p>if you prefer subshells, you could try the following (though it is more fragile):</p>
<pre><code>ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)
</code></pre>
<p>Git will invoke SSH which will find its agent by environment variable; this will, in turn, have the key loaded.</p>
<p>Alternatively, setting <code>HOME</code> may also do the trick, provided you are willing to setup a directory that contains only a <code>.ssh</code> directory as <code>HOME</code>; this may either contain an identity.pub, or a <a href="http://linux.die.net/man/5/ssh_config" rel="noreferrer">config file</a> setting IdentityFile.</p> | {
"question_id": 4565700,
"question_date": "2010-12-30T19:42:01.800Z",
"question_score": 1583,
"tags": "git|bash|shell|ssh",
"answer_id": 4565746,
"answer_date": "2010-12-30T19:48:28.153Z",
"answer_score": 1066
} |
Please answer the following Stack Overflow question:
Title: How do I style a <select> dropdown with only CSS?
<p>Is there a CSS-only way to style a <code><select></code> dropdown?</p>
<p>I need to style a <code><select></code> form as much as humanly possible, without any JavaScript. What are the properties I can use to do so in CSS?</p>
<p>This code needs to be compatible with all major browsers:</p>
<ul>
<li>Internet Explorer 6, 7, and 8</li>
<li>Firefox</li>
<li>Safari</li>
</ul>
<p>I know I can make it with JavaScript: <a href="http://www.queness.com/post/204/25-jQuery-plugins-that-enhance-and-beautify-html-form-elements" rel="noreferrer">Example</a>.</p>
<p>And I'm not talking about simple styling. I want to know, what the best we can do with CSS only.</p>
<p>I found <a href="https://stackoverflow.com/questions/1072239/is-it-possible-to-style-a-select-box">similar questions</a> on Stack Overflow.</p>
<p>And <a href="http://doctype.com/style-select" rel="noreferrer">this one</a> on Doctype.com.</p> | <p>Here are three solutions:</p>
<p>Solution #1 - appearance: none - with Internet Explorer 10 - 11 workaround (<a href="http://codepen.io/danield770/pen/bgJOyV?editors=1100" rel="noreferrer">Demo</a>)</p>
<p>--</p>
<p>To hide the default arrow set <code>appearance: none</code> on the select element, then add your own custom arrow with <code>background-image</code></p>
<pre><code>select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none; /* Remove default arrow */
background-image: url(...); /* Add custom arrow */
}
</code></pre>
<p><strong>Browser Support:</strong></p>
<p><code>appearance: none</code> has very good browser support (<a href="http://caniuse.com/#feat=css-appearance" rel="noreferrer">caniuse</a>) - except for Internet Explorer.</p>
<p>We can improve this technique and add support for Internet Explorer 10 and Internet Explorer 11 by adding</p>
<pre><code>select::-ms-expand {
display: none; /* Hide the default arrow in Internet Explorer 10 and Internet Explorer 11 */
}
</code></pre>
<p>If Internet Explorer 9 is a concern, we have no way of removing the default arrow (which would mean that we would now have two arrows), but, we could use a funky Internet Explorer 9 selector.</p>
<p>To at least undo our custom arrow - leaving the default select arrow intact.</p>
<pre><code>/* Target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {
select {
background-image:none\9;
padding: 5px\9;
}
}
</code></pre>
<h2>All together:</h2>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>select {
margin: 50px;
width: 150px;
padding: 5px 35px 5px 5px;
font-size: 16px;
border: 1px solid #CCC;
height: 34px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: url(https://stackoverflow.com/favicon.ico) 96% / 15% no-repeat #EEE;
}
/* CAUTION: Internet Explorer hackery ahead */
select::-ms-expand {
display: none; /* Remove default arrow in Internet Explorer 10 and 11 */
}
/* Target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {
select {
background: none\9;
padding: 5px\9;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
<option>Apples</option>
<option selected>Pineapples</option>
<option>Chocklate</option>
<option>Pancakes</option>
</select></code></pre>
</div>
</div>
</p>
<p>This solution is easy and has good browser support - it should generally suffice.</p>
<hr>
<p>If browser support for Internet Explorer is needed, read ahead.</p>
<p>Solution #2 Truncate the select element to hide the default arrow (<a href="http://jsfiddle.net/danield770/YvCHW/10613/" rel="noreferrer">demo</a>)</p>
<p>--</p>
<p><a href="http://bavotasan.com/2011/style-select-box-using-only-css/" rel="noreferrer">(Read more here)</a></p>
<p>Wrap the <code>select</code> element in a div with a <em>fixed width</em> and <code>overflow:hidden</code>.</p>
<p>Then give the <code>select</code> element a width of about <em>20 pixels greater than the div</em>.</p>
<p>The result is that the default drop-down arrow of the <code>select</code> element will be hidden (due to the <code>overflow:hidden</code> on the container), and you can place any background image you want on the right-hand-side of the div.</p>
<p>The <strong>advantage</strong> of this approach is that it is cross-browser (Internet Explorer 8 and later, <a href="http://en.wikipedia.org/wiki/WebKit" rel="noreferrer">WebKit</a>, and <a href="http://en.wikipedia.org/wiki/Gecko_%28layout_engine%29" rel="noreferrer">Gecko</a>). However, the <strong>disadvantage</strong> of this approach is that the options drop-down juts out on the right-hand-side (by the 20 pixels which we hid... because the option elements take the width of the select element).</p>
<p><img src="https://i.stack.imgur.com/Wyf6w.png" alt="Enter image description here" /></p>
<p>[It should be noted, however, that if the custom select element is necessary only for <strong>mobile</strong> devices - then the above problem doesn't apply - because of the way each phone natively opens the select element. So for mobile, this may be the best solution.]</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.styled select {
background: transparent;
width: 150px;
font-size: 16px;
border: 1px solid #CCC;
height: 34px;
}
.styled {
margin: 50px;
width: 120px;
height: 34px;
border: 1px solid #111;
border-radius: 3px;
overflow: hidden;
background: url(https://stackoverflow.com/favicon.ico) 96% / 20% no-repeat #EEE;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="styled">
<select>
<option>Pineapples</option>
<option selected>Apples</option>
<option>Chocklate</option>
<option>Pancakes</option>
</select>
</div></code></pre>
</div>
</div>
</p>
<hr/>
<p>If the custom arrow is necessary on Firefox - prior to <a href="https://developer.mozilla.org/en-US/Firefox/Releases/35" rel="noreferrer">Version 35</a> - but you don't need to support old versions of Internet Explorer - then keep reading...</p>
<p>Solution #3 - Use the <code>pointer-events</code> property (<a href="http://jsfiddle.net/danield770/sNwrs/3158/" rel="noreferrer">demo</a>)</p>
<p>--</p>
<p><a href="http://lea.verou.me/2011/03/custom-select-drop-downs-with-css3/" rel="noreferrer">(Read more here)</a></p>
<p>The idea here is to overlay an element over the native drop down arrow (to create our custom one) and then disallow pointer events on it.</p>
<p><strong>Advantage:</strong> It works well in WebKit and Gecko. It looks good too (no jutting out <code>option</code> elements).</p>
<p><strong>Disadvantage:</strong> Internet Explorer (Internet Explorer 10 and down) doesn't support <code>pointer-events</code>, which means you can't click the custom arrow. Also, another (obvious) disadvantage with this method is that you can't target your new arrow image with a hover effect or hand cursor, because we have just disabled pointer events on them!</p>
<p>However, with this method you can use Modernizer or conditional comments to make Internet Explorer revert to the standard built in arrow.</p>
<p><strong>NB:</strong> Being that Internet Explorer 10 doesn't support <code>conditional comments</code> anymore: If you want to use this approach, you should probably use <strong>Modernizr</strong>. However, it is still possible to exclude the pointer-events CSS from Internet Explorer 10 with a CSS hack described <a href="https://stackoverflow.com/a/14916454/703717">here</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.notIE {
position: relative;
display: inline-block;
}
select {
display: inline-block;
height: 30px;
width: 150px;
outline: none;
color: #74646E;
border: 1px solid #C8BFC4;
border-radius: 4px;
box-shadow: inset 1px 1px 2px #DDD8DC;
background: #FFF;
}
/* Select arrow styling */
.notIE .fancyArrow {
width: 23px;
height: 28px;
position: absolute;
display: inline-block;
top: 1px;
right: 3px;
background: url(https://stackoverflow.com/favicon.ico) right / 90% no-repeat #FFF;
pointer-events: none;
}
/*target Internet Explorer 9 and Internet Explorer 10:*/
@media screen and (min-width: 0\0) {
.notIE .fancyArrow {
display: none;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--[if !IE]> -->
<div class="notIE">
<!-- <![endif]-->
<span class="fancyArrow"></span>
<select>
<option>Apples</option>
<option selected>Pineapples</option>
<option>Chocklate</option>
<option>Pancakes</option>
</select>
<!--[if !IE]> -->
</div>
<!-- <![endif]--></code></pre>
</div>
</div>
</p> | {
"question_id": 1895476,
"question_date": "2009-12-13T03:33:56.377Z",
"question_score": 1579,
"tags": "html|css|combobox|cross-browser|skinning",
"answer_id": 13968900,
"answer_date": "2012-12-20T09:27:15.030Z",
"answer_score": 1178
} |
Please answer the following Stack Overflow question:
Title: Fastest way to determine if an integer's square root is an integer
<p>I'm looking for the fastest way to determine if a <code>long</code> value is a perfect square (i.e. its square root is another integer): </p>
<ol>
<li>I've done it the easy way, by using the built-in <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#sqrt(double)" rel="noreferrer"><code>Math.sqrt()</code></a>
function, but I'm wondering if there is a way to do it faster by
restricting yourself to integer-only domain.</li>
<li>Maintaining a lookup table is impractical (since there are about
2<sup>31.5</sup> integers whose square is less than 2<sup>63</sup>).</li>
</ol>
<p>Here is the very simple and straightforward way I'm doing it now:</p>
<pre><code>public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
</code></pre>
<p><sub>Note: I'm using this function in many <a href="http://projecteuler.net/" rel="noreferrer">Project Euler</a> problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.</sub></p>
<hr>
<p>I've tried the different solutions to the problem:</p>
<ul>
<li>After exhaustive testing, I found that adding <code>0.5</code> to the result of Math.sqrt() is not necessary, at least not on my machine.</li>
<li>The <a href="https://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="noreferrer">fast inverse square root</a> was faster, but it gave incorrect results for n >= 410881. However, as suggested by <a href="https://stackoverflow.com/users/38426/bobbyshaftoe">BobbyShaftoe</a>, we can use the FISR hack for n < 410881.</li>
<li>Newton's method was a good bit slower than <code>Math.sqrt()</code>. This is probably because <code>Math.sqrt()</code> uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles.</li>
<li>A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than <code>Math.sqrt()</code>.</li>
<li>Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.</li>
<li>According to John's tests, using <code>or</code> statements is faster in C++ than using a <code>switch</code>, but in Java and C# there appears to be no difference between <code>or</code> and <code>switch</code>.</li>
<li>I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or <code>or</code> statement, I would just say <code>if(lookup[(int)(n&0x3F)]) { test } else return false;</code>. To my surprise, this was (just slightly) slower. This is because <a href="https://stackoverflow.com/questions/299079/why-is-this-code-with-several-or-statements-slightly-faster-than-using-a-lookup-t#299205">array bounds are checked in Java</a>. </li>
</ul> | <p>I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don't know how the Java factor will play out.</p>
<p>My approach is threefold:</p>
<ol>
<li>First, filter out obvious answers. This includes negative numbers and looking at the last 4 bits. (I found looking at the last six didn't help.) I also answer yes for 0. (In reading the code below, note that my input is <code>int64 x</code>.)
<pre><code>if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )
return false;
if( x == 0 )
return true;</code></pre>
</li>
<li>Next, check if it's a square modulo 255 = 3 * 5 * 17. Because that's a product of three distinct primes, only about 1/8 of the residues mod 255 are squares. However, in my experience, calling the modulo operator (%) costs more than the benefit one gets, so I use bit tricks involving 255 = 2^8-1 to compute the residue. (For better or worse, I am not using the trick of reading individual bytes out of a word, only bitwise-and and shifts.)
<pre><code>int64 y = x;
y = (y & 4294967295LL) + (y >> 32);
y = (y & 65535) + (y >> 16);
y = (y & 255) + ((y >> 8) & 255) + (y >> 16);
// At this point, y is between 0 and 511. More code can reduce it farther.
</pre></code>
To actually check if the residue is a square, I look up the answer in a precomputed table.
<pre><code>if( bad255[y] )
return false;
// However, I just use a table of size 512
</code></pre>
</li>
<li>Finally, try to compute the square root using a method similar to <a href="http://en.wikipedia.org/wiki/Hensel%27s_lemma" rel="noreferrer">Hensel's lemma</a>. (I don't think it's applicable directly, but it works with some modifications.) Before doing that, I divide out all powers of 2 with a binary search:
<pre><code>if((x & 4294967295LL) == 0)
x >>= 32;
if((x & 65535) == 0)
x >>= 16;
if((x & 255) == 0)
x >>= 8;
if((x & 15) == 0)
x >>= 4;
if((x & 3) == 0)
x >>= 2;</code></pre>
At this point, for our number to be a square, it must be 1 mod 8.
<pre><code>if((x & 7) != 1)
return false;</code></pre>
The basic structure of Hensel's lemma is the following. (Note: untested code; if it doesn't work, try t=2 or 8.)
<pre><code>int64 t = 4, r = 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
t <<= 1; r += ((x - r * r) & t) >> 1;
// Repeat until t is 2^33 or so. Use a loop if you want.</code></pre>
The idea is that at each iteration, you add one bit onto r, the "current" square root of x; each square root is accurate modulo a larger and larger power of 2, namely t/2. At the end, r and t/2-r will be square roots of x modulo t/2. (Note that if r is a square root of x, then so is -r. This is true even modulo numbers, but beware, modulo some numbers, things can have even more than 2 square roots; notably, this includes powers of 2.) Because our actual square root is less than 2^32, at that point we can actually just check if r or t/2-r are real square roots. In my actual code, I use the following modified loop:
<pre><code>int64 r, t, z;
r = start[(x >> 3) & 1023];
do {
z = x - r * r;
if( z == 0 )
return true;
if( z < 0 )
return false;
t = z & (-z);
r += (z & t) >> 1;
if( r > (t >> 1) )
r = t - r;
} while( t <= (1LL << 33) );</code></pre>
The speedup here is obtained in three ways: precomputed start value (equivalent to ~10 iterations of the loop), earlier exit of the loop, and skipping some t values. For the last part, I look at <code>z = r - x * x</code>, and set t to be the largest power of 2 dividing z with a bit trick. This allows me to skip t values that wouldn't have affected the value of r anyway. The precomputed start value in my case picks out the "smallest positive" square root modulo 8192.
</li>
</ol>
<p>Even if this code doesn't work faster for you, I hope you enjoy some of the ideas it contains. Complete, tested code follows, including the precomputed tables.</p>
<pre><code>typedef signed long long int int64;
int start[1024] =
{1,3,1769,5,1937,1741,7,1451,479,157,9,91,945,659,1817,11,
1983,707,1321,1211,1071,13,1479,405,415,1501,1609,741,15,339,1703,203,
129,1411,873,1669,17,1715,1145,1835,351,1251,887,1573,975,19,1127,395,
1855,1981,425,453,1105,653,327,21,287,93,713,1691,1935,301,551,587,
257,1277,23,763,1903,1075,1799,1877,223,1437,1783,859,1201,621,25,779,
1727,573,471,1979,815,1293,825,363,159,1315,183,27,241,941,601,971,
385,131,919,901,273,435,647,1493,95,29,1417,805,719,1261,1177,1163,
1599,835,1367,315,1361,1933,1977,747,31,1373,1079,1637,1679,1581,1753,1355,
513,1539,1815,1531,1647,205,505,1109,33,1379,521,1627,1457,1901,1767,1547,
1471,1853,1833,1349,559,1523,967,1131,97,35,1975,795,497,1875,1191,1739,
641,1149,1385,133,529,845,1657,725,161,1309,375,37,463,1555,615,1931,
1343,445,937,1083,1617,883,185,1515,225,1443,1225,869,1423,1235,39,1973,
769,259,489,1797,1391,1485,1287,341,289,99,1271,1701,1713,915,537,1781,
1215,963,41,581,303,243,1337,1899,353,1245,329,1563,753,595,1113,1589,
897,1667,407,635,785,1971,135,43,417,1507,1929,731,207,275,1689,1397,
1087,1725,855,1851,1873,397,1607,1813,481,163,567,101,1167,45,1831,1205,
1025,1021,1303,1029,1135,1331,1017,427,545,1181,1033,933,1969,365,1255,1013,
959,317,1751,187,47,1037,455,1429,609,1571,1463,1765,1009,685,679,821,
1153,387,1897,1403,1041,691,1927,811,673,227,137,1499,49,1005,103,629,
831,1091,1449,1477,1967,1677,697,1045,737,1117,1737,667,911,1325,473,437,
1281,1795,1001,261,879,51,775,1195,801,1635,759,165,1871,1645,1049,245,
703,1597,553,955,209,1779,1849,661,865,291,841,997,1265,1965,1625,53,
1409,893,105,1925,1297,589,377,1579,929,1053,1655,1829,305,1811,1895,139,
575,189,343,709,1711,1139,1095,277,993,1699,55,1435,655,1491,1319,331,
1537,515,791,507,623,1229,1529,1963,1057,355,1545,603,1615,1171,743,523,
447,1219,1239,1723,465,499,57,107,1121,989,951,229,1521,851,167,715,
1665,1923,1687,1157,1553,1869,1415,1749,1185,1763,649,1061,561,531,409,907,
319,1469,1961,59,1455,141,1209,491,1249,419,1847,1893,399,211,985,1099,
1793,765,1513,1275,367,1587,263,1365,1313,925,247,1371,1359,109,1561,1291,
191,61,1065,1605,721,781,1735,875,1377,1827,1353,539,1777,429,1959,1483,
1921,643,617,389,1809,947,889,981,1441,483,1143,293,817,749,1383,1675,
63,1347,169,827,1199,1421,583,1259,1505,861,457,1125,143,1069,807,1867,
2047,2045,279,2043,111,307,2041,597,1569,1891,2039,1957,1103,1389,231,2037,
65,1341,727,837,977,2035,569,1643,1633,547,439,1307,2033,1709,345,1845,
1919,637,1175,379,2031,333,903,213,1697,797,1161,475,1073,2029,921,1653,
193,67,1623,1595,943,1395,1721,2027,1761,1955,1335,357,113,1747,1497,1461,
1791,771,2025,1285,145,973,249,171,1825,611,265,1189,847,1427,2023,1269,
321,1475,1577,69,1233,755,1223,1685,1889,733,1865,2021,1807,1107,1447,1077,
1663,1917,1129,1147,1775,1613,1401,555,1953,2019,631,1243,1329,787,871,885,
449,1213,681,1733,687,115,71,1301,2017,675,969,411,369,467,295,693,
1535,509,233,517,401,1843,1543,939,2015,669,1527,421,591,147,281,501,
577,195,215,699,1489,525,1081,917,1951,2013,73,1253,1551,173,857,309,
1407,899,663,1915,1519,1203,391,1323,1887,739,1673,2011,1585,493,1433,117,
705,1603,1111,965,431,1165,1863,533,1823,605,823,1179,625,813,2009,75,
1279,1789,1559,251,657,563,761,1707,1759,1949,777,347,335,1133,1511,267,
833,1085,2007,1467,1745,1805,711,149,1695,803,1719,485,1295,1453,935,459,
1151,381,1641,1413,1263,77,1913,2005,1631,541,119,1317,1841,1773,359,651,
961,323,1193,197,175,1651,441,235,1567,1885,1481,1947,881,2003,217,843,
1023,1027,745,1019,913,717,1031,1621,1503,867,1015,1115,79,1683,793,1035,
1089,1731,297,1861,2001,1011,1593,619,1439,477,585,283,1039,1363,1369,1227,
895,1661,151,645,1007,1357,121,1237,1375,1821,1911,549,1999,1043,1945,1419,
1217,957,599,571,81,371,1351,1003,1311,931,311,1381,1137,723,1575,1611,
767,253,1047,1787,1169,1997,1273,853,1247,413,1289,1883,177,403,999,1803,
1345,451,1495,1093,1839,269,199,1387,1183,1757,1207,1051,783,83,423,1995,
639,1155,1943,123,751,1459,1671,469,1119,995,393,219,1743,237,153,1909,
1473,1859,1705,1339,337,909,953,1771,1055,349,1993,613,1393,557,729,1717,
511,1533,1257,1541,1425,819,519,85,991,1693,503,1445,433,877,1305,1525,
1601,829,809,325,1583,1549,1991,1941,927,1059,1097,1819,527,1197,1881,1333,
383,125,361,891,495,179,633,299,863,285,1399,987,1487,1517,1639,1141,
1729,579,87,1989,593,1907,839,1557,799,1629,201,155,1649,1837,1063,949,
255,1283,535,773,1681,461,1785,683,735,1123,1801,677,689,1939,487,757,
1857,1987,983,443,1327,1267,313,1173,671,221,695,1509,271,1619,89,565,
127,1405,1431,1659,239,1101,1159,1067,607,1565,905,1755,1231,1299,665,373,
1985,701,1879,1221,849,627,1465,789,543,1187,1591,923,1905,979,1241,181};
bool bad255[512] =
{0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,
1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,
0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,
1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,
1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,
1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,
0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,
1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,
0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,
1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,
1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,
1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,
0,0};
inline bool square( int64 x ) {
// Quickfail
if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )
return false;
if( x == 0 )
return true;
// Check mod 255 = 3 * 5 * 17, for fun
int64 y = x;
y = (y & 4294967295LL) + (y >> 32);
y = (y & 65535) + (y >> 16);
y = (y & 255) + ((y >> 8) & 255) + (y >> 16);
if( bad255[y] )
return false;
// Divide out powers of 4 using binary search
if((x & 4294967295LL) == 0)
x >>= 32;
if((x & 65535) == 0)
x >>= 16;
if((x & 255) == 0)
x >>= 8;
if((x & 15) == 0)
x >>= 4;
if((x & 3) == 0)
x >>= 2;
if((x & 7) != 1)
return false;
// Compute sqrt using something like Hensel's lemma
int64 r, t, z;
r = start[(x >> 3) & 1023];
do {
z = x - r * r;
if( z == 0 )
return true;
if( z < 0 )
return false;
t = z & (-z);
r += (z & t) >> 1;
if( r > (t >> 1) )
r = t - r;
} while( t <= (1LL << 33) );
return false;
}</code></pre> | {
"question_id": 295579,
"question_date": "2008-11-17T13:43:21.907Z",
"question_score": 1578,
"tags": "java|math|optimization|perfect-square",
"answer_id": 424936,
"answer_date": "2009-01-08T16:32:42.587Z",
"answer_score": 808
} |
Please answer the following Stack Overflow question:
Title: Why do we need virtual functions in C++?
<p>I'm learning C++ and I'm just getting into virtual functions.</p>
<p>From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.</p>
<p>But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using <code>virtual</code>.</p>
<p>So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straightforward answer online.</p> | <p>Without "virtual" you get "early binding". Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through.</p>
<p>With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.</p>
<pre><code>class Base
{
public:
void Method1 () { std::cout << "Base::Method1" << std::endl; }
virtual void Method2 () { std::cout << "Base::Method2" << std::endl; }
};
class Derived : public Base
{
public:
void Method1 () { std::cout << "Derived::Method1" << std::endl; }
void Method2 () { std::cout << "Derived::Method2" << std::endl; }
};
Base* basePtr = new Derived ();
// Note - constructed as Derived, but pointer stored as Base*
basePtr->Method1 (); // Prints "Base::Method1"
basePtr->Method2 (); // Prints "Derived::Method2"
</code></pre>
<p><strong>EDIT</strong> - see <a href="https://stackoverflow.com/questions/10580/what-are-early-and-late-binding">this question</a>.</p>
<p>Also - <a href="http://www.learncpp.com/cpp-tutorial/124-early-binding-and-late-binding/" rel="noreferrer">this tutorial</a> covers early and late binding in C++.</p> | {
"question_id": 2391679,
"question_date": "2010-03-06T07:10:35.910Z",
"question_score": 1574,
"tags": "c++|polymorphism|virtual-functions",
"answer_id": 2391781,
"answer_date": "2010-03-06T07:56:18.250Z",
"answer_score": 786
} |
Please answer the following Stack Overflow question:
Title: How do I find Waldo with Mathematica?
<p>This was bugging me over the weekend: What is a good way to solve those <a href="https://en.wikipedia.org/wiki/Where%27s_Wally%3F" rel="noreferrer"><em>Where's Waldo?</em></a> [<em>'Wally'</em> outside of North America] puzzles, using Mathematica (image-processing and other functionality)?</p>
<p>Here is what I have so far, a function which reduces the visual complexity a little bit by dimming
some of the non-red colors:</p>
<pre><code>whereIsWaldo[url_] := Module[{waldo, waldo2, waldoMask},
waldo = Import[url];
waldo2 = Image[ImageData[
waldo] /. {{r_, g_, b_} /;
Not[r > .7 && g < .3 && b < .3] :> {0, 0,
0}, {r_, g_, b_} /; (r > .7 && g < .3 && b < .3) :> {1, 1,
1}}];
waldoMask = Closing[waldo2, 4];
ImageCompose[waldo, {waldoMask, .5}]
]
</code></pre>
<p>And an example of a URL where this 'works':</p>
<pre><code>whereIsWaldo["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"]
</code></pre>
<p>(Waldo is by the cash register):</p>
<p><img src="https://i.stack.imgur.com/reNlF.jpg" alt="Original image"></p>
<p><img src="https://i.stack.imgur.com/5IDuu.jpg" alt="Mathematica graphic"></p> | <p>I've found Waldo!</p>
<p><img src="https://i.stack.imgur.com/UYMae.jpg" alt="waldo had been found"></p>
<p><strong>How I've done it</strong></p>
<p>First, I'm filtering out all colours that aren't red</p>
<pre><code>waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];
</code></pre>
<p>Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt. </p>
<pre><code>corr = ImageCorrelate[red,
Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]],
NormalizedSquaredEuclideanDistance];
</code></pre>
<p>I use <code>Binarize</code> to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using <code>Dilation</code></p>
<pre><code>pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];
</code></pre>
<p>I had to play around a little with the level. If the level is too high, too many false positives are picked out. </p>
<p>Finally I'm combining this result with the original image to get the result above</p>
<pre><code>found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]
</code></pre> | {
"question_id": 8479058,
"question_date": "2011-12-12T18:29:44.097Z",
"question_score": 1570,
"tags": "image-processing|wolfram-mathematica",
"answer_id": 8479757,
"answer_date": "2011-12-12T19:32:11.190Z",
"answer_score": 1653
} |
Please answer the following Stack Overflow question:
Title: Transport security has blocked a cleartext HTTP
<p>What setting do I need to put in my <code>info.plist</code> to enable HTTP mode as per the following error message?</p>
<blockquote>
<p>Transport security has blocked a cleartext HTTP (http://) resource
load since it is insecure. Temporary exceptions can be configured via
your app's Info.plist file.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/phCr2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/phCr2.png" alt="Xcode"></a></p>
<p>Assume that my domain is <code>example.com</code>.</p> | <p>If you are using Xcode 8.0+ and Swift 2.2+ or even Objective C:</p>
<p><a href="https://i.stack.imgur.com/8OCcm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8OCcm.png" alt="Enter image description here" /></a></p>
<p>If you want to allow HTTP connections to any site, you can use this keys:</p>
<pre><code><key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</code></pre>
<p>If you know which domains you will connect to add:</p>
<pre><code><key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
</code></pre> | {
"question_id": 31254725,
"question_date": "2015-07-06T20:10:21.103Z",
"question_score": 1568,
"tags": "ios|xcode|ios9|ios10|app-transport-security",
"answer_id": 40299837,
"answer_date": "2016-10-28T07:06:57.187Z",
"answer_score": 585
} |
Please answer the following Stack Overflow question:
Title: What is the Python 3 equivalent of "python -m SimpleHTTPServer"
<p>What is the Python 3 equivalent of <code>python -m SimpleHTTPServer</code>?</p> | <p>From <a href="https://docs.python.org/2/library/simplehttpserver.html" rel="noreferrer">the docs</a>:</p>
<blockquote>
<p>The <code>SimpleHTTPServer</code> module has been merged into <code>http.server</code> in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.</p>
</blockquote>
<p>So, your command is <code>python -m http.server</code>, or depending on your installation, it can be:</p>
<pre><code>python3 -m http.server
</code></pre> | {
"question_id": 7943751,
"question_date": "2011-10-30T07:22:49.040Z",
"question_score": 1567,
"tags": "python|python-3.x|httpserver|simplehttpserver",
"answer_id": 7943768,
"answer_date": "2011-10-30T07:28:58.020Z",
"answer_score": 2208
} |
Please answer the following Stack Overflow question:
Title: Save plot to image file instead of displaying it using Matplotlib
<p>This displays the figure in a GUI:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
</code></pre>
<p>But how do I instead save the figure to a file (e.g. foo.png)?</p> | <p>When using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html" rel="noreferrer"><code>matplotlib.pyplot.savefig</code></a>, the file format can be specified by the extension:</p>
<pre><code>from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
</code></pre>
<p>That gives a rasterized or vectorized output respectively.
In addition, there is sometimes undesirable whitespace around the image, which can be removed with:</p>
<pre><code>plt.savefig('foo.png', bbox_inches='tight')
</code></pre>
<p>Note that if showing the plot, <code>plt.show()</code> should follow <code>plt.savefig()</code>; otherwise, the file image will be blank.</p> | {
"question_id": 9622163,
"question_date": "2012-03-08T17:38:10.927Z",
"question_score": 1565,
"tags": "python|matplotlib|plot",
"answer_id": 9890599,
"answer_date": "2012-03-27T13:35:44.493Z",
"answer_score": 1983
} |
Please answer the following Stack Overflow question:
Title: A potentially dangerous Request.Form value was detected from the client
<p>Every time a user posts something containing <code><</code> or <code>></code> in a page in my web application, I get this exception thrown.</p>
<p>I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.</p>
<p>Trapping the exception and showing</p>
<blockquote>
<p>An error has occurred please go back and re-type your entire form again, but this time please do not use <</p>
</blockquote>
<p>doesn't seem professional enough to me.</p>
<p>Disabling post validation (<code>validateRequest="false"</code>) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.</p>
<p>Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.
So the <code>.Text</code> property of my text-box will be <code>something & lt; html & gt;</code></p>
<p>Is there a way I can do this from a handler?</p> | <p>I think you are attacking it from the wrong angle by trying to encode all posted data.</p>
<p>Note that a "<code><</code>" could also come from other outside sources, like a database field, a configuration, a file, a feed and so on.</p>
<p>Furthermore, "<code><</code>" is not inherently dangerous. It's only dangerous in a specific context: when writing strings that haven't been encoded to HTML output (because of XSS).</p>
<p>In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string "<code>javascript:</code>" may be dangerous. The single quote character on the other hand is dangerous when interpolating strings in SQL queries, but perfectly safe if it is a part of a name submitted from a form or read from a database field.</p>
<p>The bottom line is: you can't filter random input for dangerous characters, because any character may be dangerous under the right circumstances. You should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning. When you write a string to HTML, you should encode characters that have special meaning in HTML, using Server.HtmlEncode. If you pass a string to a dynamic SQL statement, you should encode different characters (or better, let the framework do it for you by using prepared statements or the like)..</p>
<p><em>When</em> you are sure you HTML-encode everywhere you pass strings to HTML, then set <code>ValidateRequest="false"</code> in the <code><%@ Page ... %></code> directive in your <code>.aspx</code> file(s).</p>
<p>In .NET 4 you may need to do a little more. Sometimes it's necessary to also add <code><httpRuntime requestValidationMode="2.0" /></code> to web.config (<a href="http://www.asp.net/%28S%28ywiyuluxr3qb2dfva1z5lgeg%29%29/learn/whitepapers/aspnet4/breaking-changes/" rel="noreferrer">reference</a>).</p> | {
"question_id": 81991,
"question_date": "2008-09-17T10:58:14.253Z",
"question_score": 1565,
"tags": "asp.net|asp.net-mvc|validation|html-encode|request.form",
"answer_id": 82170,
"answer_date": "2008-09-17T11:26:23.030Z",
"answer_score": 1135
} |
Please answer the following Stack Overflow question:
Title: How can I install packages using pip according to the requirements.txt file from a local directory?
<p>Here is the problem:</p>
<p>I have a <em>requirements.txt</em> file that looks like:</p>
<pre class="lang-none prettyprint-override"><code>BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
</code></pre>
<p>I have a local archive directory containing all the packages + others.</p>
<p>I have created a new <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> with</p>
<pre class="lang-none prettyprint-override"><code>bin/virtualenv testing
</code></pre>
<p>Upon activating it, I tried to install the packages according to <em>requirements.txt</em> from the local archive directory.</p>
<pre class="lang-none prettyprint-override"><code>source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/
</code></pre>
<p>I got some output that seems to indicate that the installation is fine:</p>
<pre class="lang-none prettyprint-override"><code>Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
Running setup.py egg_info for package Fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
Running setup.py egg_info for package South
....
</code></pre>
<p>But a later check revealed that none of the packages are installed properly. I cannot import the packages, and none are found in the site-packages directory of my virtualenv. So what went wrong?</p> | <p>This works for me:</p>
<pre><code>$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages
</code></pre>
<p><code>--no-index</code> - Ignore package index (only looking at <code>--find-links</code> URLs instead).</p>
<p><code>-f, --find-links <URL></code> - If a URL or path to an HTML file, then parse for links to archives.</p>
<p>If a local path or <code>file://</code> URL that's a directory, then look for archives in the directory listing.</p> | {
"question_id": 7225900,
"question_date": "2011-08-29T03:53:04.027Z",
"question_score": 1564,
"tags": "python|virtualenv|pip",
"answer_id": 10429168,
"answer_date": "2012-05-03T10:04:39.030Z",
"answer_score": 1076
} |
Please answer the following Stack Overflow question:
Title: How do you convert a byte array to a hexadecimal string, and vice versa?
<p>How can you convert a byte array to a hexadecimal string and vice versa?</p> | <p>You can use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.convert.tohexstring" rel="noreferrer"><code>Convert.ToHexString</code></a> starting with .NET 5. <br />
There's also a method for the reverse operation: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring" rel="noreferrer"><code>Convert.FromHexString</code></a>.</p>
<hr />
<p>For older versions of .NET you can either use:</p>
<pre class="lang-cs prettyprint-override"><code>public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
</code></pre>
<p>or:</p>
<pre class="lang-cs prettyprint-override"><code>public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-","");
}
</code></pre>
<p>There are even more variants of doing it, for example <a href="https://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3928b8cb-3703-4672-8ccd-33718148d1e3/" rel="noreferrer">here</a>.</p>
<p>The reverse conversion would go like this:</p>
<pre class="lang-cs prettyprint-override"><code>public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
</code></pre>
<hr />
<p>Using <code>Substring</code> is the best option in combination with <code>Convert.ToByte</code>. See <a href="https://stackoverflow.com/a/26304129">this answer</a> for more information. If you need better performance, you must avoid <code>Convert.ToByte</code> before you can drop <code>SubString</code>.</p> | {
"question_id": 311165,
"question_date": "2008-11-22T10:03:13.003Z",
"question_score": 1564,
"tags": "c#|arrays|hex",
"answer_id": 311179,
"answer_date": "2008-11-22T10:19:28.480Z",
"answer_score": 1618
} |
Please answer the following Stack Overflow question:
Title: Android 8: Cleartext HTTP traffic not permitted
<p>I had reports from users with Android 8 that my app (that uses back-end feed) does not show content. After investigation I found following Exception happening on Android 8:</p>
<pre><code>08-29 12:03:11.246 11285-11285/ E/: [12:03:11.245, main]: Exception: IOException java.io.IOException: Cleartext HTTP traffic to * not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.doConnection(AbstractHttpAsyncTask.java:207)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.extendedDoInBackground(AbstractHttpAsyncTask.java:102)
at com.deiw.android.generic.tasks.AbstractAsyncTask.doInBackground(AbstractAsyncTask.java:88)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
</code></pre>
<p>(I've removed package name, URL and other possible identifiers)</p>
<p>On Android 7 and lower everything works, I do not set <code>android:usesCleartextTraffic</code> in Manifest (and setting it to <code>true</code> does not help, that is the default value anyway), neither do I use Network Security Information. If I call <code>NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted()</code>, it returns <code>false</code> for Android 8, <code>true</code> for older version, using the same apk file.
I tried to find some mention of this on Google info about Android O, but without success.</p> | <p>According to <a href="https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted" rel="noreferrer">Network security configuration</a> -</p>
<blockquote>
<p>Starting with Android 9 (API level 28), cleartext support is disabled
by default.</p>
</blockquote>
<p>Also have a look at <a href="https://koz.io/android-m-and-the-war-on-cleartext-traffic/" rel="noreferrer">Android M and the war on cleartext traffic</a></p>
<p><a href="https://developer.android.com/codelabs/android-network-security-config" rel="noreferrer">Codelabs explanation</a> from Google</p>
<p><strong>Option 1 -</strong></p>
<p>First try hitting the URL with <code>https://</code> instead of <code>http://</code></p>
<p><strong>Option 2 -</strong></p>
<p>Create file <code>res/xml/network_security_config.xml</code> -</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
</domain-config>
</network-security-config>
</code></pre>
<p><code>AndroidManifest.xml</code> -</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
</manifest>
</code></pre>
<p><strong>Option 3 -</strong></p>
<p><a href="https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic" rel="noreferrer">android:usesCleartextTraffic Doc</a></p>
<p><code>AndroidManifest.xml</code> -</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
</code></pre>
<p>Also as <a href="https://stackoverflow.com/a/45955297/7599300">@david.s' answer</a> pointed out <code>android:targetSandboxVersion</code> can be a problem too -</p>
<p>According to <a href="https://developer.android.com/guide/topics/manifest/manifest-element#targetSandboxVersion" rel="noreferrer">Manifest Docs</a> -</p>
<blockquote>
<p><code>android:targetSandboxVersion</code></p>
<p>The target sandbox for this app to use. The higher the sandbox version
number, the higher the level of security. Its default value is 1; you
can also set it to 2. Setting this attribute to 2 switches the app to
a different SELinux sandbox. The following restrictions apply to a
level 2 sandbox:</p>
<ul>
<li>The default value of <code>usesCleartextTraffic</code> in the Network Security Config is false.</li>
<li>Uid sharing is not permitted.</li>
</ul>
</blockquote>
<p><strong>So Option 4 -</strong></p>
<p>If you have <code>android:targetSandboxVersion</code> in <code><manifest></code> then reduce it to <code>1</code></p>
<p><code>AndroidManifest.xml</code> -</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
</code></pre> | {
"question_id": 45940861,
"question_date": "2017-08-29T13:48:06.670Z",
"question_score": 1559,
"tags": "android|http|https",
"answer_id": 50834600,
"answer_date": "2018-06-13T10:11:09.213Z",
"answer_score": 3131
} |
Please answer the following Stack Overflow question:
Title: SQL select only rows with max value on a column
<p>I have this table for documents (simplified version here):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>rev</th>
<th>content</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>...</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>...</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>...</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
<p>How do I select one row per id and only the greatest rev?<br />
With the above data, the result should contain two rows: <code>[1, 3, ...]</code> and <code>[2, 1, ..]</code>. I'm using <em><strong>MySQL</strong></em>.</p>
<p>Currently I use checks in the <code>while</code> loop to detect and over-write old revs from the resultset. But is this the only method to achieve the result? Isn't there a <strong>SQL</strong> solution?</p> | <h2>At first glance...</h2>
<p>All you need is a <code>GROUP BY</code> clause with the <code>MAX</code> aggregate function:</p>
<pre><code>SELECT id, MAX(rev)
FROM YourTable
GROUP BY id
</code></pre>
<h2>It's never that simple, is it?</h2>
<p>I just noticed you need the <code>content</code> column as well.</p>
<p>This is a very common question in SQL: find the whole data for the row with some max value in a column per some group identifier. I heard that a lot during my career. Actually, it was one the questions I answered in my current job's technical interview.</p>
<p>It is, actually, so common that Stack Overflow community has created a single tag just to deal with questions like that: <a href="/questions/tagged/greatest-n-per-group" class="post-tag" title="show questions tagged 'greatest-n-per-group'" rel="tag">greatest-n-per-group</a>.</p>
<p>Basically, you have two approaches to solve that problem:</p>
<h2>Joining with simple <code>group-identifier, max-value-in-group</code> Sub-query</h2>
<p>In this approach, you first find the <code>group-identifier, max-value-in-group</code> (already solved above) in a sub-query. Then you join your table to the sub-query with equality on both <code>group-identifier</code> and <code>max-value-in-group</code>:</p>
<pre><code>SELECT a.id, a.rev, a.contents
FROM YourTable a
INNER JOIN (
SELECT id, MAX(rev) rev
FROM YourTable
GROUP BY id
) b ON a.id = b.id AND a.rev = b.rev
</code></pre>
<h2>Left Joining with self, tweaking join conditions and filters</h2>
<p>In this approach, you left join the table with itself. Equality goes in the <code>group-identifier</code>. Then, 2 smart moves:</p>
<ol>
<li>The second join condition is having left side value less than right value</li>
<li>When you do step 1, the row(s) that actually have the max value will have <code>NULL</code> in the right side (it's a <code>LEFT JOIN</code>, remember?). Then, we filter the joined result, showing only the rows where the right side is <code>NULL</code>.</li>
</ol>
<p>So you end up with:</p>
<pre><code>SELECT a.*
FROM YourTable a
LEFT OUTER JOIN YourTable b
ON a.id = b.id AND a.rev < b.rev
WHERE b.id IS NULL;
</code></pre>
<h2>Conclusion</h2>
<p>Both approaches bring the exact same result.</p>
<p>If you have two rows with <code>max-value-in-group</code> for <code>group-identifier</code>, both rows will be in the result in both approaches.</p>
<p>Both approaches are SQL ANSI compatible, thus, will work with your favorite RDBMS, regardless of its "flavor".</p>
<p>Both approaches are also performance friendly, however your mileage may vary (RDBMS, DB Structure, Indexes, etc.). So when you pick one approach over the other, <em>benchmark</em>. And make sure you pick the one which make most of sense to you.</p> | {
"question_id": 7745609,
"question_date": "2011-10-12T19:42:07.780Z",
"question_score": 1556,
"tags": "mysql|sql|aggregate-functions|greatest-n-per-group|groupwise-maximum",
"answer_id": 7745635,
"answer_date": "2011-10-12T19:43:53.237Z",
"answer_score": 2432
} |
Please answer the following Stack Overflow question:
Title: How can I open a URL in Android's web browser from my application?
<p>How to open an URL from code in the built-in web browser rather than within my application?</p>
<p>I tried this:</p>
<pre><code>try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
</code></pre>
<p>but I got an Exception:</p>
<pre><code>No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
</code></pre> | <p>Try this:</p>
<pre><code>Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
</code></pre>
<p>That works fine for me.</p>
<p>As for the missing "http://" I'd just do something like this:</p>
<pre><code>if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
</code></pre>
<p>I would also probably pre-populate your EditText that the user is typing a URL in with "http://".</p> | {
"question_id": 2201917,
"question_date": "2010-02-04T17:51:45.483Z",
"question_score": 1556,
"tags": "android|url|android-intent|android-browser",
"answer_id": 2201999,
"answer_date": "2010-02-04T18:01:42.133Z",
"answer_score": 2807
} |
Please answer the following Stack Overflow question:
Title: How do I revert a merge commit that has already been pushed to remote?
<p><code>git revert <commit_hash></code> alone won't work. Apparently, <code>-m</code> must be specified.</p> | <p>In <code>git revert -m</code>, the <code>-m</code> option specifies the <strong>parent number</strong>. This is needed because a merge commit has more than one parent, and Git does not know automatically which parent was the mainline, and which parent was the branch you want to un-merge.</p>
<p>When you view a merge commit in the output of <code>git log</code>, you will see its parents listed on the line that begins with <code>Merge</code>:</p>
<pre><code>commit 8f937c683929b08379097828c8a04350b9b8e183
Merge: 8989ee0 7c6b236
Author: Ben James <[email protected]>
Date: Wed Aug 17 22:49:41 2011 +0100
Merge branch 'gh-pages'
Conflicts:
README
</code></pre>
<p>In this situation, <code>git revert 8f937c6 -m 1</code> will get you the tree as it was in <code>8989ee0</code>, and <code>git revert -m 2</code> will reinstate the tree as it was in <code>7c6b236</code>.</p>
<p>To better understand the parent IDs, you can run:</p>
<pre><code>git log 8989ee0
</code></pre>
<p>and</p>
<pre><code>git log 7c6b236
</code></pre> | {
"question_id": 7099833,
"question_date": "2011-08-17T21:37:28.217Z",
"question_score": 1554,
"tags": "git",
"answer_id": 7100005,
"answer_date": "2011-08-17T21:53:14.963Z",
"answer_score": 1865
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.