input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How can I delete all of my Git stashes at once?
<p>How can I delete all of my <a href="https://en.wikipedia.org/wiki/Git" rel="noreferrer">Git</a> stashes at once?</p>
<p>Specifically I mean, with typing in one command.</p> | <p>The following command deletes all your stashes:</p>
<pre><code>git stash clear
</code></pre>
<p>From the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html" rel="noreferrer">git documentation</a>:</p>
<blockquote>
<p><strong><code>clear</code></strong></p>
<p>Remove all the stashed states.</p>
<p><strong>IMPORTANT WARNING:</strong> Those states will then be subject to pruning, and may be impossible to recover (...).</p>
</blockquote> | {
"question_id": 11369375,
"question_date": "2012-07-06T20:38:58.513Z",
"question_score": 1909,
"tags": "git|git-stash",
"answer_id": 11369406,
"answer_date": "2012-07-06T20:41:39.217Z",
"answer_score": 3289
} |
Please answer the following Stack Overflow question:
Title: How do I exclude a directory when using `find`?
<p>How do I exclude a specific directory when searching for <code>*.js</code> files using <code>find</code>?</p>
<pre><code>find . -name '*.js'
</code></pre> | <p>Use the <code>-prune</code> primary. For example, if you want to exclude <code>./misc</code>:</p>
<pre><code>find . -path ./misc -prune -o -name '*.txt' -print
</code></pre>
<p>To exclude multiple directories, OR them between parentheses.</p>
<pre><code>find . -type d \( -path ./dir1 -o -path ./dir2 -o -path ./dir3 \) -prune -o -name '*.txt' -print
</code></pre>
<p>And, to exclude directories with a specific name at any level, use the <code>-name</code> primary instead of <code>-path</code>.</p>
<pre class="lang-sh prettyprint-override"><code>find . -type d -name node_modules -prune -o -name '*.json' -print
</code></pre> | {
"question_id": 4210042,
"question_date": "2010-11-17T22:57:02.213Z",
"question_score": 1896,
"tags": "linux|shell|find",
"answer_id": 4210072,
"answer_date": "2010-11-17T23:00:42.150Z",
"answer_score": 1594
} |
Please answer the following Stack Overflow question:
Title: What is the 'new' keyword in JavaScript?
<p>The <code>new</code> keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.</p>
<ul>
<li>What is it?</li>
<li>What problems does it solve?</li>
<li>When is it appropriate and when not?</li>
</ul> | <p>It does 5 things:</p>
<ol>
<li>It creates a new object. The type of this object is simply <em>object</em>.</li>
<li>It sets this new object's internal, inaccessible, <em>[[prototype]]</em> (i.e. <strong>__proto__</strong>) property to be the constructor function's external, accessible, <em>prototype</em> object (every function object automatically has a <em>prototype</em> property).</li>
<li>It makes the <code>this</code> variable point to the newly created object.</li>
<li>It executes the constructor function, using the newly created object whenever <code>this</code> is mentioned.</li>
<li>It returns the newly created object, unless the constructor function returns a non-<code>null</code> object reference. In this case, that object reference is returned instead.</li>
</ol>
<p>Note: <em>constructor function</em> refers to the function after the <code>new</code> keyword, as in </p>
<pre><code>new ConstructorFunction(arg1, arg2)
</code></pre>
<p>Once this is done, if an undefined property of the new object is requested, the script will check the object's <em>[[prototype]]</em> object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript. </p>
<p>The most difficult part about this is point number 2. Every object (including functions) has this internal property called <em>[[prototype]]</em>. It can <em>only</em> be set at object creation time, either with <em>new</em>, with <em>Object.create</em>, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with <em>Object.getPrototypeOf(someObject)</em>. There is <em>no</em> other way to set or read this value.</p>
<p>Functions, in addition to the hidden <em>[[prototype]]</em> property, also have a property called <em>prototype</em>, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.</p>
<hr>
<p>Here is an example:</p>
<pre><code>ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes
// it a constructor.
ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that
// we can alter. I just added a property called 'b' to it. Like
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with
obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1. At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.
obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'
</code></pre>
<p>It's like class inheritance because now, any objects you make using <code>new ObjMaker()</code> will also appear to have inherited the 'b' property.</p>
<p>If you want something like a subclass, then you do this:</p>
<pre><code>SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);
SubObjMaker.prototype.c = 'third';
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype
obj2.c;
// returns 'third', from SubObjMaker.prototype
obj2.b;
// returns 'second', from ObjMaker.prototype
obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype
// was created with the ObjMaker function, which assigned a for us
</code></pre>
<hr>
<p>I read a ton of rubbish on this subject before finally finding <a href="http://joost.zeekat.nl/constructors-considered-mildly-confusing.html" rel="noreferrer">this page</a>, where this is explained very well with nice diagrams.</p> | {
"question_id": 1646698,
"question_date": "2009-10-29T21:32:45.197Z",
"question_score": 1892,
"tags": "javascript|new-operator",
"answer_id": 3658673,
"answer_date": "2010-09-07T12:30:58.123Z",
"answer_score": 2270
} |
Please answer the following Stack Overflow question:
Title: Looping through the content of a file in Bash
<p>How do I iterate through each line of a text file with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)" rel="noreferrer">Bash</a>?</p>
<p>With this script:</p>
<pre><code>echo "Start!"
for p in (peptides.txt)
do
echo "${p}"
done
</code></pre>
<p>I get this output on the screen:</p>
<pre><code>Start!
./runPep.sh: line 3: syntax error near unexpected token `('
./runPep.sh: line 3: `for p in (peptides.txt)'
</code></pre>
<p>(Later I want to do something more complicated with <code>$p</code> than just output to the screen.)</p>
<hr>
<p>The environment variable <strong>SHELL</strong> is (from env):</p>
<pre><code>SHELL=/bin/bash
</code></pre>
<p><code>/bin/bash --version</code> output:</p>
<pre><code>GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
</code></pre>
<p><code>cat /proc/version</code> output:</p>
<pre><code>Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006
</code></pre>
<p>The file peptides.txt contains:</p>
<pre><code>RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
</code></pre> | <p>One way to do it is:</p>
<pre><code>while read p; do
echo "$p"
done <peptides.txt
</code></pre>
<p>As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:</p>
<pre><code>while IFS="" read -r p || [ -n "$p" ]
do
printf '%s\n' "$p"
done < peptides.txt
</code></pre>
<hr>
<p>Exceptionally, if the <a href="https://unix.stackexchange.com/questions/107800/using-while-loop-to-ssh-to-multiple-servers">loop body may read from standard input</a>, you can open the file using a different file descriptor:</p>
<pre><code>while read -u 10 p; do
...
done 10<peptides.txt
</code></pre>
<p>Here, 10 is just an arbitrary number (different from 0, 1, 2).</p> | {
"question_id": 1521462,
"question_date": "2009-10-05T17:52:54.210Z",
"question_score": 1888,
"tags": "linux|bash|loops|unix|io",
"answer_id": 1521498,
"answer_date": "2009-10-05T18:00:20.157Z",
"answer_score": 2698
} |
Please answer the following Stack Overflow question:
Title: Scroll to the top of the page using JavaScript?
<p>How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.</p> | <p>If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript <code>window.scrollTo()</code> method -- passing in <code>0, 0</code> will scroll the page to the top left instantly.</p>
<pre><code>window.scrollTo(xCoord, yCoord);
</code></pre>
<p>Parameters</p>
<ul>
<li>xCoord is the pixel along the horizontal axis.</li>
<li>yCoord is the pixel along the vertical axis.</li>
</ul> | {
"question_id": 1144805,
"question_date": "2009-07-17T17:59:09.657Z",
"question_score": 1888,
"tags": "javascript|scroll",
"answer_id": 1145012,
"answer_date": "2009-07-17T18:42:35.653Z",
"answer_score": 2544
} |
Please answer the following Stack Overflow question:
Title: How do I make a placeholder for a 'select' box?
<p>I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:</p>
<pre><code><select>
<option value="">Select your option</option>
<option value="hurr">Durr</option>
</select>
</code></pre>
<p>But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.</p>
<p>This only makes the option grey in the dropdown (so after clicking the arrow):</p>
<pre class="lang-css prettyprint-override"><code>option:first {
color: #999;
}
</code></pre>
<p>The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.</p>
<p>And using this results in the selected value always being grey (even after selecting a real option):</p>
<pre class="lang-css prettyprint-override"><code>select {
color: #999;
}
</code></pre> | <p>A non-CSS - no JavaScript/jQuery answer:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Option name
<select>
<option value="" disabled selected>Select your option</option>
<option value="hurr">Durr</option>
</select>
</label></code></pre>
</div>
</div>
</p>
<p><strong>Update</strong> (December 2021):</p>
<p>This works for latest Firefox, Chrome, and Safari. It used to not work for many browsers in the past, as pointed out in the comments.</p> | {
"question_id": 5805059,
"question_date": "2011-04-27T13:39:15.523Z",
"question_score": 1886,
"tags": "html|css|html-select|placeholder",
"answer_id": 5859221,
"answer_date": "2011-05-02T15:45:49.407Z",
"answer_score": 3534
} |
Please answer the following Stack Overflow question:
Title: How to efficiently count the number of keys/properties of an object in JavaScript
<p>What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing:</p>
<pre><code>var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) ++count;
</code></pre>
<p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p> | <p>To do this in any <em><a href="https://en.wikipedia.org/wiki/ECMAScript#5th_Edition" rel="noreferrer">ES5</a>-compatible environment</em>, such as <a href="http://nodejs.org" rel="noreferrer">Node.js</a>, Chrome, <a href="https://en.wikipedia.org/wiki/Internet_Explorer_9" rel="noreferrer">Internet Explorer 9+</a>, Firefox 4+, or Safari 5+:</p>
<pre class="lang-js prettyprint-override"><code>Object.keys(obj).length
</code></pre>
<ul>
<li><a href="http://kangax.github.com/es5-compat-table/" rel="noreferrer">Browser compatibility</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer">Object.keys documentation</a> (includes a method you can add to non-ES5 browsers)</li>
</ul> | {
"question_id": 126100,
"question_date": "2008-09-24T08:56:21.263Z",
"question_score": 1885,
"tags": "javascript|performance|properties|count|key",
"answer_id": 4889658,
"answer_date": "2011-02-03T17:47:20.957Z",
"answer_score": 3006
} |
Please answer the following Stack Overflow question:
Title: What is TypeScript and why would I use it in place of JavaScript?
<p>Can you please describe what the TypeScript language is?</p>
<p>What can it do that JavaScript or available libraries cannot do, that would give me reason to consider it?</p> | <blockquote>
<p>I originally wrote this answer when TypeScript was still
hot-off-the-presses. Five years later, this is an OK overview, but look
at <a href="https://stackoverflow.com/a/35048303/6521">Lodewijk's answer</a> below for more depth</p>
</blockquote>
<h2>1000ft view...</h2>
<p><a href="http://www.typescriptlang.org" rel="noreferrer">TypeScript</a> is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors <em>as you type the code</em>.</p>
<p>To get an idea of what I mean, watch <a href="http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript" rel="noreferrer">Microsoft's introductory video</a> on the language.</p>
<p>For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.</p>
<p>It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from <a href="http://tirania.org/blog/archive/2012/Oct-01.html" rel="noreferrer">Miguel de Icaza</a>). These days, <a href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support" rel="noreferrer">other IDEs offer TypeScript support too</a>.</p>
<h2>Are there other technologies like it?</h2>
<p>There's <a href="http://coffeescript.org/" rel="noreferrer">CoffeeScript</a>, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for <em>tools</em> through its optional static typing (see this <a href="http://www.hanselman.com/blog/WhyDoesTypeScriptHaveToBeTheAnswerToAnything.aspx" rel="noreferrer">recent blog post</a> for a little more critique). There's also <a href="http://en.wikipedia.org/wiki/Dart_%28programming_language%29" rel="noreferrer">Dart</a> but that's a full on replacement for JavaScript (though it <a href="http://www.dartlang.org/docs/dart-up-and-running/contents/ch04-tools-dart2js.html" rel="noreferrer">can produce JavaScript code</a>)</p>
<h2>Example</h2>
<p>As an example, here's some TypeScript (you can play with this in the <a href="http://www.typescriptlang.org/Playground/" rel="noreferrer">TypeScript Playground</a>)</p>
<pre><code>class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
</code></pre>
<p>And here's the JavaScript it would produce</p>
<pre><code>var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
</code></pre>
<p>Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.</p>
<p>It's also capable of inferring types which aren't explicitly declared, for example, it would determine the <code>greet()</code> method returns a string.</p>
<h2>Debugging TypeScript</h2>
<p>Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: <a href="https://stackoverflow.com/questions/12711826/debugging-typescript-code-with-visual-studio">Debugging TypeScript code with Visual Studio</a></p>
<h2>Want to know more?</h2>
<p>I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out <a href="https://stackoverflow.com/a/35048303/6521">Lodewijk's answer</a> to this question for some more current detail.</p> | {
"question_id": 12694530,
"question_date": "2012-10-02T16:37:58.910Z",
"question_score": 1880,
"tags": "javascript|typescript",
"answer_id": 12694578,
"answer_date": "2012-10-02T16:41:28.717Z",
"answer_score": 1413
} |
Please answer the following Stack Overflow question:
Title: How to duplicate a whole line in Vim?
<p>How do I duplicate a whole line in <strong>Vim</strong> in a similar way to <kbd>Ctrl</kbd>+<kbd>D</kbd> in IntelliJ IDEA/ Resharper or <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> in <strong>Eclipse</strong>?</p> | <p><kbd>y</kbd><kbd>y</kbd> or <kbd>Y</kbd> to copy the line (mnemonic: <strong><em>y</strong>ank</em>)
<br />or
<br /><kbd>d</kbd><kbd>d</kbd> to <strong><em>d</strong>elete</em> the line (Vim copies what you deleted into a clipboard-like "register", like a <em>cut</em> operation)</p>
<p>then</p>
<p><kbd>p</kbd> to <strong><em>p</strong>aste</em> the copied or deleted text <em>after</em> the current line
<br />or
<br /><kbd>P</kbd> to <strong><em>p</strong>aste</em> the copied or deleted text <em>before</em> the current line</p> | {
"question_id": 73319,
"question_date": "2008-09-16T15:02:52.923Z",
"question_score": 1873,
"tags": "vim|editor|keyboard-shortcuts|vi",
"answer_id": 73357,
"answer_date": "2008-09-16T15:06:46.393Z",
"answer_score": 3137
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Bower and npm?
<p>What is the fundamental difference between <code>bower</code> and <code>npm</code>? Just want something plain and simple. I've seen some of my colleagues use <code>bower</code> and <code>npm</code> interchangeably in their projects.</p> | <p>All package managers have many downsides. You just have to pick which you can live with.</p>
<h2>History</h2>
<p><a href="https://www.npmjs.org" rel="noreferrer">npm</a> started out managing node.js modules (that's why packages go into <code>node_modules</code> by default), but it works for the front-end too when combined with <a href="http://browserify.org/" rel="noreferrer">Browserify</a> or <a href="https://webpack.js.org/" rel="noreferrer">webpack</a>.</p>
<p><a href="http://bower.io" rel="noreferrer">Bower</a> is created solely for the front-end and is optimized with that in mind.</p>
<h2>Size of repo</h2>
<p>npm is much, much larger than bower, including general purpose JavaScript (like <code>country-data</code> for country information or <code>sorts</code> for sorting functions that is usable on the front end or the back end).</p>
<p>Bower has a much smaller amount of packages.</p>
<h2>Handling of styles etc</h2>
<p>Bower includes styles etc.</p>
<p>npm is focused on JavaScript. Styles are either downloaded separately or required by something like <code>npm-sass</code> or <code>sass-npm</code>.</p>
<h2>Dependency handling</h2>
<p>The biggest difference is that npm does nested dependencies (but is flat by default) while Bower requires a flat dependency tree <em>(puts the burden of dependency resolution on the user)</em>.</p>
<p>A nested dependency tree means that your dependencies can have their own dependencies which can have their own, and so on. This allows for two modules to require different versions of the same dependency and still work. Note since npm v3, the dependency tree will be flat by default (saving space) and only nest where needed, e.g., if two dependencies need their own version of Underscore.</p>
<p>Some projects use both: they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.</p>
<hr />
<h2>Resources</h2>
<ul>
<li><a href="http://maxogden.com/nested-dependencies.html" rel="noreferrer">Nested Dependencies</a> - Insight into why node_modules works the way it does</li>
</ul> | {
"question_id": 18641899,
"question_date": "2013-09-05T16:53:19.613Z",
"question_score": 1873,
"tags": "javascript|npm|bower",
"answer_id": 18652918,
"answer_date": "2013-09-06T08:09:28.860Z",
"answer_score": 1969
} |
Please answer the following Stack Overflow question:
Title: Why does this code using random strings print "hello world"?
<p>The following print statement would print "hello world".
Could anyone explain this?</p>
<pre><code>System.out.println(randomString(-229985452) + " " + randomString(-147909649));
</code></pre>
<p>And <code>randomString()</code> looks like this:</p>
<pre><code>public static String randomString(int i)
{
Random ran = new Random(i);
StringBuilder sb = new StringBuilder();
while (true)
{
int k = ran.nextInt(27);
if (k == 0)
break;
sb.append((char)('`' + k));
}
return sb.toString();
}
</code></pre> | <p>When an instance of <code>java.util.Random</code> is constructed with a specific seed parameter (in this case <code>-229985452</code> or <code>-147909649</code>), it follows the random number generation algorithm <em>beginning</em> with that seed value.</p>
<p>Every <code>Random</code> constructed with the same seed will generate the same pattern of numbers every time.</p> | {
"question_id": 15182496,
"question_date": "2013-03-03T04:38:06.147Z",
"question_score": 1873,
"tags": "java|string|random",
"answer_id": 15182511,
"answer_date": "2013-03-03T04:40:52.517Z",
"answer_score": 951
} |
Please answer the following Stack Overflow question:
Title: How do I split a string in Java?
<p>I want to split the string <code>"004-034556"</code> into two strings by the delimiter <code>"-"</code>:</p>
<pre><code>part1 = "004";
part2 = "034556";
</code></pre>
<p>That means the first string will contain the characters before <code>'-'</code>, and the second string will contain the characters after <code>'-'</code>.</p>
<p>I also want to check if the string has <code>'-'</code> in it.</p> | <p>Use the appropriately named method <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String)" rel="noreferrer"><code>String#split()</code></a>.</p>
<pre><code>String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
</code></pre>
<p>Note that <code>split</code>'s argument is assumed to be a <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#sum" rel="noreferrer">regular expression</a>, so remember to escape <a href="https://www.regular-expressions.info/characters.html" rel="noreferrer">special characters</a> if necessary.</p>
<blockquote>
<p><a href="https://www.regular-expressions.info/characters.html" rel="noreferrer">there</a> are 12 characters with special meanings: the backslash <code>\</code>, the caret <code>^</code>, the dollar sign <code>$</code>, the period or dot <code>.</code>, the vertical bar or pipe symbol <code>|</code>, the question mark <code>?</code>, the asterisk or star <code>*</code>, the plus sign <code>+</code>, the opening parenthesis <code>(</code>, the closing parenthesis <code>)</code>, and the opening square bracket <code>[</code>, the opening curly brace <code>{</code>, These special characters are often called "metacharacters".</p>
</blockquote>
<p>For instance, to split on a period/dot <code>.</code> (which means "<a href="https://www.regular-expressions.info/dot.html" rel="noreferrer">any character</a>" in regex), use either <a href="https://www.regular-expressions.info/characters.html" rel="noreferrer">backslash <code>\</code></a> to escape the individual special character like so <code>split("\\.")</code>, or use <a href="https://www.regular-expressions.info/charclass.html" rel="noreferrer">character class <code>[]</code></a> to represent literal character(s) like so <code>split("[.]")</code>, or use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)" rel="noreferrer"><code>Pattern#quote()</code></a> to escape the entire string like so <code>split(Pattern.quote("."))</code>.</p>
<pre><code>String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.
</code></pre>
<p>To test beforehand if the string contains certain character(s), just use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#contains(java.lang.CharSequence)" rel="noreferrer"><code>String#contains()</code></a>.</p>
<pre><code>if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}
</code></pre>
<p>Note, this does not take a regular expression. For that, use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#matches(java.lang.String)" rel="noreferrer"><code>String#matches()</code></a> instead.</p>
<p>If you'd like to retain the split character in the resulting parts, then make use of <a href="https://www.regular-expressions.info/lookaround.html" rel="noreferrer">positive lookaround</a>. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing <code>?<=</code> group on the pattern.</p>
<pre><code>String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556
</code></pre>
<p>In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing <code>?=</code> group on the pattern.</p>
<pre><code>String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556
</code></pre>
<p>If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of <code>split()</code> method.</p>
<pre><code>String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
</code></pre> | {
"question_id": 3481828,
"question_date": "2010-08-14T03:01:53.143Z",
"question_score": 1872,
"tags": "java|string|split",
"answer_id": 3481842,
"answer_date": "2010-08-14T03:05:34.517Z",
"answer_score": 3316
} |
Please answer the following Stack Overflow question:
Title: Remove tracking branches no longer on remote
<p>Is there a simple way to delete all tracking branches whose remote equivalent no longer exists?</p>
<p>Example:</p>
<p>Branches (local and remote)</p>
<ul>
<li>master</li>
<li>origin/master</li>
<li>origin/bug-fix-a</li>
<li>origin/bug-fix-b</li>
<li>origin/bug-fix-c</li>
</ul>
<p>Locally, I only have a master branch. Now I need to work on <em>bug-fix-a</em>, so I check it out, work on it, and push changes to the remote. Next I do the same with <em>bug-fix-b</em>.</p>
<p>Branches (local and remote)</p>
<ul>
<li>master</li>
<li>bug-fix-a</li>
<li>bug-fix-b</li>
<li>origin/master</li>
<li>origin/bug-fix-a</li>
<li>origin/bug-fix-b</li>
<li>origin/bug-fix-c</li>
</ul>
<p>Now I have local branches <em>master</em>, <em>bug-fix-a</em>, <em>bug-fix-b</em>. The Master branch maintainer will merge my changes into <em>master</em> and delete all branches he has already merged.</p>
<p>So the current state is now:</p>
<p>Branches (local and remote)</p>
<ul>
<li>master</li>
<li>bug-fix-a</li>
<li>bug-fix-b</li>
<li>origin/master</li>
<li>origin/bug-fix-c</li>
</ul>
<p>Now I would like to call some command to delete branches (in this case <em>bug-fix-a</em>, <em>bug-fix-b</em>), which are no longer represented in the remote repository.</p>
<p>It would be something like the existing command <code>git remote prune origin</code>, but more like <code>git local prune origin</code>.</p> | <p><code>git remote prune origin</code> prunes tracking branches not on the remote.</p>
<p><code>git branch --merged</code> lists branches that have been merged into the current branch.</p>
<p><code>xargs git branch -d</code> deletes branches listed on standard input.</p>
<p>Be careful deleting branches listed by <code>git branch --merged</code>. The list could include <code>master</code> or other branches you'd prefer not to delete.</p>
<p>To give yourself the opportunity to edit the list before deleting branches, you could do the following in one line:</p>
<pre><code>git branch --merged >/tmp/merged-branches && \
vi /tmp/merged-branches && xargs git branch -d </tmp/merged-branches
</code></pre> | {
"question_id": 7726949,
"question_date": "2011-10-11T13:37:35.390Z",
"question_score": 1871,
"tags": "git|git-branch",
"answer_id": 28464339,
"answer_date": "2015-02-11T20:56:18.153Z",
"answer_score": 1901
} |
Please answer the following Stack Overflow question:
Title: How to move an element into another element?
<p>I would like to move one DIV element inside another. For example, I want to move this (including all children):</p>
<pre><code><div id="source">
...
</div>
</code></pre>
<p>into this:</p>
<pre><code><div id="destination">
...
</div>
</code></pre>
<p>so that I have this:</p>
<pre><code><div id="destination">
<div id="source">
...
</div>
</div>
</code></pre> | <p>You may want to use the <a href="http://api.jquery.com/appendTo/" rel="noreferrer"><code>appendTo</code></a> function (which adds to the end of the element):</p>
<pre><code>$("#source").appendTo("#destination");
</code></pre>
<p>Alternatively you could use the <a href="http://api.jquery.com/prependTo/" rel="noreferrer"><code>prependTo</code></a> function (which adds to the beginning of the element):</p>
<pre><code>$("#source").prependTo("#destination");
</code></pre>
<hr>
<p>Example:</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>$("#appendTo").click(function() {
$("#moveMeIntoMain").appendTo($("#main"));
});
$("#prependTo").click(function() {
$("#moveMeIntoMain").prependTo($("#main"));
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main {
border: 2px solid blue;
min-height: 100px;
}
.moveMeIntoMain {
border: 1px solid red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">main</div>
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>
<button id="appendTo">appendTo main</button>
<button id="prependTo">prependTo main</button></code></pre>
</div>
</div>
</p> | {
"question_id": 1279957,
"question_date": "2009-08-14T20:14:45.940Z",
"question_score": 1868,
"tags": "javascript|jquery|html",
"answer_id": 1279963,
"answer_date": "2009-08-14T20:16:45.747Z",
"answer_score": 1903
} |
Please answer the following Stack Overflow question:
Title: How do I check if a string represents a number (float or int)?
<p>How do I check if a string represents a numeric value in Python?</p>
<pre><code>def is_number(s):
try:
float(s)
return True
except ValueError:
return False
</code></pre>
<p>The above works, but it seems clunky.</p>
<hr />
<p><sub>If what you are testing comes from user input, it is <em>still</em> a string <em>even if it represents</em> an <code>int</code> or a <code>float</code>. See <a href="https://stackoverflow.com/questions/20449427/">How can I read inputs as numbers?</a> for converting the input, and <a href="https://stackoverflow.com/questions/23294658/">Asking the user for input until they give a valid response</a> for ensuring that the input represents an <code>int</code> or <code>float</code> (or other requirements) before proceeding.</sub></p> | <blockquote>
<p>Which, not only is ugly and slow</p>
</blockquote>
<p>I'd dispute both.</p>
<p>A regex or other string parsing method would be uglier and slower. </p>
<p>I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.</p>
<p>The issue is that any numeric conversion function has two kinds of results</p>
<ul>
<li>A number, if the number is valid</li>
<li>A status code (e.g., via errno) or exception to show that no valid number could be parsed.</li>
</ul>
<p>C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.</p>
<p>I think your code for doing this is perfect.</p> | {
"question_id": 354038,
"question_date": "2008-12-09T20:03:42.113Z",
"question_score": 1866,
"tags": "python|casting|floating-point|type-conversion",
"answer_id": 354130,
"answer_date": "2008-12-09T20:30:48.800Z",
"answer_score": 767
} |
Please answer the following Stack Overflow question:
Title: Why should text files end with a newline?
<p>I assume everyone here is familiar with the adage that all text files should end with a newline. I've known of this "rule" for years but I've always wondered — why?</p> | <p>Because that’s <a href="https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206" rel="noreferrer">how the POSIX standard defines a <strong>line</strong></a>:</p>
<blockquote>
<dl>
<dt><strong>3.206 Line</strong></dt>
<dd>A sequence of zero or more non- <newline> characters plus a terminating <newline> character.</dd>
</dl>
</blockquote>
<p>Therefore, lines not ending in a newline character aren't considered actual lines. That's why some programs have problems processing the last line of a file if it isn't newline terminated.</p>
<p>There's at least one hard advantage to this guideline when working on a terminal emulator: All Unix tools expect this convention and work with it. For instance, when concatenating files with <code>cat</code>, a file terminated by newline will have a different effect than one without:</p>
<pre><code><i>$</i> <b>more</b> a.txt
foo
<i>$</i> <b>more</b> b.txt
bar<i>$</i> <b>more</b> c.txt
baz
<i>$</i> <b>cat</b> {a,b,c}.txt
foo
barbaz</code></pre>
<p>And, as the previous example also demonstrates, when displaying the file on the command line (e.g. via <code>more</code>), a newline-terminated file results in a correct display. An improperly terminated file might be garbled (second line).</p>
<p>For consistency, it’s very helpful to follow this rule – doing otherwise will incur extra work when dealing with the default Unix tools.</p>
<hr />
<p>Think about it differently: If lines aren’t terminated by newline, making commands such as <code>cat</code> useful is much harder: how do you make a command to concatenate files such that</p>
<ol>
<li>it puts each file’s start on a new line, which is what you want 95% of the time; but</li>
<li>it allows merging the last and first line of two files, as in the example above between <code>b.txt</code> and <code>c.txt</code>?</li>
</ol>
<p>Of course this is <em>solvable</em> but you need to make the usage of <code>cat</code> more complex (by adding positional command line arguments, e.g. <code>cat a.txt --no-newline b.txt c.txt</code>), and now the <em>command</em> rather than each individual file controls how it is pasted together with other files. This is almost certainly not convenient.</p>
<p>… Or you need to introduce a special sentinel character to mark a line that is supposed to be continued rather than terminated. Well, now you’re stuck with the same situation as on POSIX, except inverted (line continuation rather than line termination character).</p>
<hr />
<p><sub>Now, on <em>non POSIX compliant</em> systems (nowadays that’s mostly Windows), the point is moot: files don’t generally end with a newline, and the (informal) definition of a line might for instance be “text that is <em>separated</em> by newlines” (note the emphasis). This is entirely valid. However, for structured data (e.g. programming code) it makes parsing minimally more complicated: it generally means that parsers have to be rewritten. If a parser was originally written with the POSIX definition in mind, then it might be easier to modify the token stream rather than the parser — in other words, add an “artificial newline” token to the end of the input.</sub></p> | {
"question_id": 729692,
"question_date": "2009-04-08T12:16:39.483Z",
"question_score": 1862,
"tags": "file|unix|text-files|newline",
"answer_id": 729795,
"answer_date": "2009-04-08T12:46:40.113Z",
"answer_score": 1740
} |
Please answer the following Stack Overflow question:
Title: Who is listening on a given TCP port on Mac OS X?
<p>On Linux, I can use <code>netstat -pntl | grep $PORT</code> or <code>fuser -n tcp $PORT</code> to find out which process (PID) is listening on the specified TCP port. How do I get the same information on Mac OS X?</p> | <p>On macOS <code>Big Sur</code> and later, use this command:</p>
<pre><code>sudo lsof -i -P | grep LISTEN | grep :$PORT
</code></pre>
<p>or to just see just IPv4:</p>
<pre><code>sudo lsof -nP -i4TCP:$PORT | grep LISTEN
</code></pre>
<p>On older versions, use one of the following forms:</p>
<pre><code>sudo lsof -nP -iTCP:$PORT | grep LISTEN
sudo lsof -nP -i:$PORT | grep LISTEN
</code></pre>
<p>Substitute <code>$PORT</code> with the port number or a comma-separated list of port numbers.</p>
<p>Prepend <code>sudo</code> (followed by a space) if you need information on ports below #1024.</p>
<p>The <code>-n</code> flag is for displaying IP addresses instead of host names. This makes the command execute much faster, because DNS lookups to get the host names can be slow (several seconds or a minute for many hosts).</p>
<p>The <code>-P</code> flag is for displaying raw port numbers instead of resolved names like <code>http</code>, <code>ftp</code> or more esoteric service names like <code>dpserve</code>, <code>socalia</code>.</p>
<p>See the comments for more options.</p>
<p>For completeness, because frequently used together:</p>
<p>To kill the PID:</p>
<pre><code>sudo kill -9 <PID>
# kill -9 60401
</code></pre> | {
"question_id": 4421633,
"question_date": "2010-12-12T12:30:02.463Z",
"question_score": 1857,
"tags": "macos|tcp|netstat|listen",
"answer_id": 4421674,
"answer_date": "2010-12-12T12:39:44.943Z",
"answer_score": 2868
} |
Please answer the following Stack Overflow question:
Title: How can I set the default value for an HTML <select> element?
<p>I thought that adding a <code>"value"</code> attribute set on the <code><select></code> element below would cause the <code><option></code> containing my provided <code>"value"</code> to be selected by default:</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-html lang-html prettyprint-override"><code><select name="hall" id="hall" value="3">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select></code></pre>
</div>
</div>
</p>
<p>However, this did not work as I had expected. How can I set which <code><option></code> element is selected by default?</p> | <p>Set <code>selected="selected"</code> for the option you want to be the default.</p>
<pre><code><option selected="selected">
3
</option>
</code></pre> | {
"question_id": 3518002,
"question_date": "2010-08-19T01:10:51.273Z",
"question_score": 1853,
"tags": "html|html-select",
"answer_id": 3518011,
"answer_date": "2010-08-19T01:12:33.827Z",
"answer_score": 2656
} |
Please answer the following Stack Overflow question:
Title: How to align checkboxes and their labels consistently cross-browsers
<p>This is one of the minor CSS problems that plague me constantly.</p>
<p>How do folks around Stack Overflow vertically align <em><strong><code>checkboxes</code></strong></em> and their <em><strong><code>labels</code></strong></em> consistently <strong>cross-browser</strong>?</p>
<p>Whenever I align them correctly in Safari (usually using <code>vertical-align: baseline</code> on the <code>input</code>), they're completely off in Firefox and IE.</p>
<p>Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.</p>
<p>Here's the standard code that I work with:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>I usually use Eric Meyer's reset, so form elements are relatively clean of overrides. Looking forward to any tips or tricks that you have to offer!</p> | <h1>Warning! This answer is <em><strong>too old</strong></em> and <em><strong>doesn't work</strong></em> on modern browsers.</h1>
<p><sub>
I'm not the poster of this answer, but at the time of writing this, this is the most voted answer by far in both positive and negative votes (+1035 -17), and it's still marked as accepted answer (probably because the original poster of the question is the one who wrote this answer).</sub></p>
<p>As already noted many times in the comments, this answer does not work on most browsers anymore (and seems to be failing to do that since 2013).</p>
<hr />
<p>After over an hour of tweaking, testing, and trying different styles of markup, I think I may have a decent solution. The requirements for this particular project were:</p>
<ol>
<li>Inputs must be on their own line.</li>
<li>Checkbox inputs need to align vertically with the label text similarly (if not identically) across all browsers.</li>
<li>If the label text wraps, it needs to be indented (so no wrapping down underneath the checkbox).</li>
</ol>
<p>Before I get into any explanation, I'll just give you the 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-css lang-css prettyprint-override"><code>label {
display: block;
padding-left: 15px;
text-indent: -15px;
}
input {
width: 13px;
height: 13px;
padding: 0;
margin:0;
vertical-align: bottom;
position: relative;
top: -1px;
*overflow: hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>Here is the working example in <a href="http://jsfiddle.net/t8EGn/6/" rel="noreferrer">JSFiddle</a>.</p>
<p>This code assumes that you're using a reset like Eric Meyer's that doesn't override form input margins and padding (hence putting margin and padding resets in the input CSS). Obviously in a live environment you'll probably be nesting/overriding stuff to support other input elements, but I wanted to keep things simple.</p>
<p>Things to note:</p>
<ul>
<li>The <code>*overflow</code> declaration is an inline IE hack (the star-property hack). Both IE 6 and 7 will notice it, but Safari and Firefox will properly ignore it. I think it might be valid CSS, but you're still better off with conditional comments; just used it for simplicity.</li>
<li>As best I can tell, the only <code>vertical-align</code> statement that was consistent across browsers was <code>vertical-align: bottom</code>. Setting this and then relatively positioning upwards behaved almost identically in Safari, Firefox and IE with only a pixel or two of discrepancy.</li>
<li>The major problem in working with alignment is that IE sticks a bunch of mysterious space around input elements. It isn't padding or margin, and it's damned persistent. Setting a width and height on the checkbox and then <code>overflow: hidden</code> for some reason cuts off the extra space and allows IE's positioning to act very similarly to Safari and Firefox.</li>
<li>Depending on your text sizing, you'll no doubt need to adjust the relative positioning, width, height, and so forth to get things looking right.</li>
</ul>
<p>Hope this helps someone else! I haven't tried this specific technique on any projects other than the one I was working on this morning, so definitely pipe up if you find something that works more consistently.</p>
<hr />
<h1>Warning! This answer is <em><strong>too old</strong></em> and <em><strong>doesn't work</strong></em> on modern browsers.</h1> | {
"question_id": 306252,
"question_date": "2008-11-20T18:02:01.650Z",
"question_score": 1853,
"tags": "html|css|cross-browser|alignment|forms",
"answer_id": 306593,
"answer_date": "2008-11-20T19:47:43.153Z",
"answer_score": 1034
} |
Please answer the following Stack Overflow question:
Title: How to send a header using a HTTP request through a cURL call?
<p>I wish to send a header to my Apache server on a Linux box. How can I achieve this via a cURL call?</p> | <p><strong>GET:</strong></p>
<p><em>with JSON:</em></p>
<pre><code>curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource
</code></pre>
<p><em>with XML:</em></p>
<pre><code>curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
</code></pre>
<p><strong>POST:</strong></p>
<p><em>For posting data:</em></p>
<pre><code>curl --data "param1=value1&param2=value2" http://hostname/resource
</code></pre>
<p><em>For file upload:</em></p>
<pre><code>curl --form "[email protected]" http://hostname/resource
</code></pre>
<p><em>RESTful HTTP Post:</em></p>
<pre><code>curl -X POST -d @filename http://hostname/resource
</code></pre>
<p><em>For logging into a site (auth):</em></p>
<pre><code>curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
</code></pre> | {
"question_id": 356705,
"question_date": "2008-12-10T16:38:57.003Z",
"question_score": 1848,
"tags": "curl|http-headers",
"answer_id": 19217512,
"answer_date": "2013-10-07T05:15:07.597Z",
"answer_score": 879
} |
Please answer the following Stack Overflow question:
Title: Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition
<p>One of the most interesting projects I've worked on in the past couple of years was a project about <a href="https://en.wikipedia.org/wiki/Image_processing" rel="noreferrer">image processing</a>. The goal was to develop a system to be able to recognize Coca-Cola <strong>'cans'</strong> (note that I'm stressing the word 'cans', you'll see why in a minute). You can see a sample below, with the can recognized in the <em>green rectangle</em> with scale and rotation.</p>
<p><img src="https://i.stack.imgur.com/irQtR.png" alt="Template matching"></p>
<p>Some constraints on the project:</p>
<ul>
<li>The background could be very noisy.</li>
<li>The <em>can</em> could have any <em>scale</em> or <em>rotation</em> or even orientation (within reasonable limits).</li>
<li>The image could have some degree of fuzziness (contours might not be entirely straight).</li>
<li>There could be Coca-Cola bottles in the image, and the algorithm should only detect the <em>can</em>!</li>
<li>The brightness of the image could vary a lot (so you can't rely "too much" on color detection).</li>
<li>The <em>can</em> could be partly hidden on the sides or the middle and possibly partly hidden behind a bottle.</li>
<li>There could be no <em>can</em> at all in the image, in which case you had to find nothing and write a message saying so.</li>
</ul>
<p>So you could end up with tricky things like this (which in this case had my algorithm totally fail):</p>
<p><img src="https://i.stack.imgur.com/Byw82.png" alt="Total fail"></p>
<p>I did this project a while ago, and had a lot of fun doing it, and I had a decent implementation. Here are some details about my implementation:</p>
<p><strong>Language</strong>: Done in C++ using <a href="http://opencv.org" rel="noreferrer">OpenCV</a> library.</p>
<p><strong>Pre-processing</strong>: For the image pre-processing, i.e. transforming the image into a more raw form to give to the algorithm, I used 2 methods:</p>
<ol>
<li>Changing color domain from RGB to <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" rel="noreferrer">HSV</a> and filtering based on "red" hue, saturation above a certain threshold to avoid orange-like colors, and filtering of low value to avoid dark tones. The end result was a binary black and white image, where all white pixels would represent the pixels that match this threshold. Obviously there is still a lot of crap in the image, but this reduces the number of dimensions you have to work with.
<img src="https://i.stack.imgur.com/ktdAB.png" alt="Binarized image"> </li>
<li>Noise filtering using median filtering (taking the median pixel value of all neighbors and replace the pixel by this value) to reduce noise.</li>
<li>Using <a href="http://en.wikipedia.org/wiki/Canny_edge_detector" rel="noreferrer">Canny Edge Detection Filter</a> to get the contours of all items after 2 precedent steps.
<img src="https://i.stack.imgur.com/F9319.png" alt="Contour detection"></li>
</ol>
<p><strong>Algorithm</strong>: The algorithm itself I chose for this task was taken from <a href="https://rads.stackoverflow.com/amzn/click/com/0123725380" rel="noreferrer" rel="nofollow noreferrer">this</a> awesome book on feature extraction and called <a href="http://en.wikipedia.org/wiki/Generalised_Hough_transform" rel="noreferrer">Generalized Hough Transform</a> (pretty different from the regular Hough Transform). It basically says a few things:</p>
<ul>
<li>You can describe an object in space without knowing its analytical equation (which is the case here).</li>
<li>It is resistant to image deformations such as scaling and rotation, as it will basically test your image for every combination of scale factor and rotation factor.</li>
<li>It uses a base model (a template) that the algorithm will "learn".</li>
<li>Each pixel remaining in the contour image will vote for another pixel which will supposedly be the center (in terms of gravity) of your object, based on what it learned from the model.</li>
</ul>
<p>In the end, you end up with a heat map of the votes, for example here all the pixels of the contour of the can will vote for its gravitational center, so you'll have a lot of votes in the same pixel corresponding to the center, and will see a peak in the heat map as below:</p>
<p><img src="https://i.stack.imgur.com/wxrT1.png" alt="GHT"></p>
<p>Once you have that, a simple threshold-based heuristic can give you the location of the center pixel, from which you can derive the scale and rotation and then plot your little rectangle around it (final scale and rotation factor will obviously be relative to your original template). In theory at least...</p>
<p><strong>Results</strong>: Now, while this approach worked in the basic cases, it was severely lacking in some areas:</p>
<ul>
<li>It is <strong>extremely slow</strong>! I'm not stressing this enough. Almost a full day was needed to process the 30 test images, obviously because I had a very high scaling factor for rotation and translation, since some of the cans were very small.</li>
<li>It was completely lost when bottles were in the image, and for some reason almost always found the bottle instead of the can (perhaps because bottles were bigger, thus had more pixels, thus more votes)</li>
<li>Fuzzy images were also no good, since the votes ended up in pixel at random locations around the center, thus ending with a very noisy heat map.</li>
<li>In-variance in translation and rotation was achieved, but not in orientation, meaning that a can that was not directly facing the camera objective wasn't recognized.</li>
</ul>
<p>Can you help me improve my <strong>specific</strong> algorithm, using <strong>exclusively OpenCV</strong> features, to resolve the <strong>four specific</strong> issues mentioned?</p>
<p>I hope some people will also learn something out of it as well, after all I think not only people who ask questions should learn. :)</p> | <p>An alternative approach would be to extract features (keypoints) using the <a href="https://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">scale-invariant feature transform</a> (SIFT) or <a href="https://en.wikipedia.org/wiki/Speeded_up_robust_features" rel="noreferrer">Speeded Up Robust Features</a> (SURF).</p>
<p>You can find a nice <code>OpenCV</code> code example in <code>Java</code>, <code>C++</code>, and <code>Python</code> on this page: <em><a href="https://docs.opencv.org/3.4/d7/dff/tutorial_feature_homography.html" rel="noreferrer">Features2D + Homography to find a known object</a></em></p>
<p>Both algorithms are invariant to scaling and rotation. Since they work with features, you can also handle <a href="http://en.wikipedia.org/wiki/Ambient_occlusion" rel="noreferrer">occlusion</a> (as long as enough keypoints are visible).</p>
<p><img src="https://i.stack.imgur.com/kF63R.jpg" alt="Enter image description here" /></p>
<p>Image source: tutorial example</p>
<p>The processing takes a few hundred ms for SIFT, SURF is bit faster, but it not suitable for real-time applications. ORB uses FAST which is weaker regarding rotation invariance.</p>
<h3>The original papers</h3>
<ul>
<li><a href="http://www.vision.ee.ethz.ch/%7Esurf/eccv06.pdf" rel="noreferrer">SURF: Speeded Up Robust Features</a></li>
<li><a href="http://www.cs.ubc.ca/%7Elowe/papers/ijcv04.pdf" rel="noreferrer">Distinctive Image Features
from Scale-Invariant Keypoints</a></li>
<li><a href="http://www.willowgarage.com/sites/default/files/orb_final.pdf" rel="noreferrer">ORB: an efficient alternative to SIFT or SURF</a></li>
</ul> | {
"question_id": 10168686,
"question_date": "2012-04-16T04:23:16.380Z",
"question_score": 1843,
"tags": "c++|algorithm|image-processing|opencv",
"answer_id": 10169025,
"answer_date": "2012-04-16T05:17:39.570Z",
"answer_score": 744
} |
Please answer the following Stack Overflow question:
Title: Why does ++[[]][+[]]+[+[]] return the string "10"?
<p>This is valid and returns the string <code>"10"</code> in JavaScript (<a href="http://sla.ckers.org/forum/read.php?24,33349,33405" rel="noreferrer">more examples 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-js lang-js prettyprint-override"><code>console.log(++[[]][+[]]+[+[]])</code></pre>
</div>
</div>
</p>
<p>Why? What is happening here?</p> | <p>If we split it up, the mess is equal to:</p>
<pre><code>++[[]][+[]]
+
[+[]]
</code></pre>
<p>In JavaScript, it is true that <code>+[] === 0</code>. <code>+</code> converts something into a number, and in this case it will come down to <code>+""</code> or <code>0</code> (see specification details below).</p>
<p>Therefore, we can simplify it (<code>++</code> has precendence over <code>+</code>):</p>
<pre><code>++[[]][0]
+
[0]
</code></pre>
<p>Because <code>[[]][0]</code> means: get the first element from <code>[[]]</code>, it is true that:</p>
<p><code>[[]][0]</code> returns the inner array (<code>[]</code>). Due to references it's wrong to say <code>[[]][0] === []</code>, but let's call the inner array <code>A</code> to avoid the wrong notation.</p>
<p><code>++</code> before its operand means “increment by one and return the incremented result”. So <code>++[[]][0]</code> is equivalent to <code>Number(A) + 1</code> (or <code>+A + 1</code>).</p>
<p>Again, we can simplify the mess into something more legible. Let's substitute <code>[]</code> back for <code>A</code>:</p>
<pre><code>(+[] + 1)
+
[0]
</code></pre>
<p>Before <code>+[]</code> can coerce the array into the number <code>0</code>, it needs to be coerced into a string first, which is <code>""</code>, again. Finally, <code>1</code> is added, which results in <code>1</code>.</p>
<ul>
<li><code>(+[] + 1) === (+"" + 1)</code></li>
<li><code>(+"" + 1) === (0 + 1)</code></li>
<li><code>(0 + 1) === 1</code></li>
</ul>
<p>Let's simplify it even more:</p>
<pre><code>1
+
[0]
</code></pre>
<p>Also, this is true in JavaScript: <code>[0] == "0"</code>, because it's joining an array with one element. Joining will concatenate the elements separated by <code>,</code>. With one element, you can deduce that this logic will result in the first element itself.</p>
<p>In this case, <code>+</code> sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string <code>"0"</code>, next, the number is coerced into a string (<code>"1"</code>). <em>Number <code>+</code> String <code>===</code> String</em>.</p>
<pre><code>"1" + "0" === "10" // Yay!
</code></pre>
<hr>
<p>Specification details for <code>+[]</code>:</p>
<p>This is quite a maze, but to do <code>+[]</code>, first it is being converted to a string because that's what <code>+</code> says:</p>
<blockquote>
<p>11.4.6 Unary + Operator</p>
<p>The unary + operator converts its operand to Number type.</p>
<p>The production UnaryExpression : + UnaryExpression is evaluated as follows:</p>
<ol>
<li><p>Let expr be the result of evaluating UnaryExpression.</p></li>
<li><p>Return ToNumber(GetValue(expr)).</p></li>
</ol>
</blockquote>
<p><code>ToNumber()</code> says:</p>
<blockquote>
<p>Object</p>
<p>Apply the following steps:</p>
<ol>
<li><p>Let primValue be ToPrimitive(input argument, hint String).</p></li>
<li><p>Return ToString(primValue).</p></li>
</ol>
</blockquote>
<p><code>ToPrimitive()</code> says:</p>
<blockquote>
<p>Object</p>
<p>Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.</p>
</blockquote>
<p><code>[[DefaultValue]]</code> says:</p>
<blockquote>
<p>8.12.8 [[DefaultValue]] (hint)</p>
<p>When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:</p>
<ol>
<li><p>Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".</p></li>
<li><p>If IsCallable(toString) is true then,</p></li>
</ol>
<p>a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.</p>
<p>b. If str is a primitive value, return str.</p>
</blockquote>
<p>The <code>.toString</code> of an array says:</p>
<blockquote>
<p>15.4.4.2 Array.prototype.toString ( )</p>
<p>When the toString method is called, the following steps are taken:</p>
<ol>
<li><p>Let array be the result of calling ToObject on the this value.</p></li>
<li><p>Let func be the result of calling the [[Get]] internal method of array with argument "join".</p></li>
<li><p>If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).</p></li>
<li><p>Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.</p></li>
</ol>
</blockquote>
<p>So <code>+[]</code> comes down to <code>+""</code>, because <code>[].join() === ""</code>.</p>
<p>Again, the <code>+</code> is defined as:</p>
<blockquote>
<p>11.4.6 Unary + Operator</p>
<p>The unary + operator converts its operand to Number type.</p>
<p>The production UnaryExpression : + UnaryExpression is evaluated as follows:</p>
<ol>
<li><p>Let expr be the result of evaluating UnaryExpression.</p></li>
<li><p>Return ToNumber(GetValue(expr)).</p></li>
</ol>
</blockquote>
<p><code>ToNumber</code> is defined for <code>""</code> as:</p>
<blockquote>
<p>The MV of StringNumericLiteral ::: [empty] is 0.</p>
</blockquote>
<p>So <code>+"" === 0</code>, and thus <code>+[] === 0</code>.</p> | {
"question_id": 7202157,
"question_date": "2011-08-26T08:46:14.277Z",
"question_score": 1842,
"tags": "javascript|syntax",
"answer_id": 7202287,
"answer_date": "2011-08-26T08:56:54.530Z",
"answer_score": 2234
} |
Please answer the following Stack Overflow question:
Title: Getting the class name of an instance
<p>How do I find out the name of the class used to create an instance of an object in Python?</p>
<p>I'm not sure if I should use the <a href="https://docs.python.org/2/library/inspect.html" rel="noreferrer" title="inspect — Inspect live objects"><code>inspect</code></a> module or parse the <code>__class__</code> attribute.</p> | <p>Have you tried the <a href="https://docs.python.org/library/stdtypes.html#definition.__name__" rel="noreferrer"><code>__name__</code> attribute</a> of the class? ie <code>type(x).__name__</code> will give you the name of the class, which I think is what you want.</p>
<pre><code>>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
</code></pre>
<p>If you're still using Python 2, note that the above method works with <a href="https://wiki.python.org/moin/NewClassVsClassicClass" rel="noreferrer">new-style classes</a> only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:</p>
<pre><code>x.__class__.__name__
</code></pre> | {
"question_id": 510972,
"question_date": "2009-02-04T11:37:48.407Z",
"question_score": 1836,
"tags": "python|introspection|instanceof|python-datamodel",
"answer_id": 511059,
"answer_date": "2009-02-04T12:02:12.960Z",
"answer_score": 2396
} |
Please answer the following Stack Overflow question:
Title: Why should I use a pointer rather than the object itself?
<p>I'm coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than the objects themselves, for example this declaration:</p>
<pre><code>Object *myObject = new Object;
</code></pre>
<p>rather than:</p>
<pre><code>Object myObject;
</code></pre>
<p>Or instead of using a function, let's say <code>testFunc()</code>, like this:</p>
<pre><code>myObject.testFunc();
</code></pre>
<p>we have to write:</p>
<pre><code>myObject->testFunc();
</code></pre>
<p>But I can't figure out why should we do it this way. I would assume it has to do with efficiency and speed since we get direct access to the memory address. Am I right?</p> | <p>It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.</p>
<p>In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using <code>new</code>)? The second is when should we use pointers?</p>
<p>The important take-home message is that you should <strong>always use the appropriate tool for the job</strong>. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.</p>
<h2>Dynamic allocation</h2>
<p>In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing <code>Object myObject;</code> within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do <code>new Object()</code>, the object has dynamic storage duration, which means it stays alive until you explicitly <code>delete</code> it. You should only use dynamic storage duration when you need it.
That is, <strong>you should <em>always</em> prefer creating objects with automatic storage duration when you can</strong>.</p>
<p>The main two situations in which you might require dynamic allocation:</p>
<ol>
<li><strong>You need the object to outlive the current scope</strong> - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.</li>
<li><strong>You need to allocate a lot of memory</strong>, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.</li>
</ol>
<p>When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="noreferrer"><code>std::unique_ptr</code></a> and <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>std::shared_ptr</code></a>, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the <a href="https://en.cppreference.com/w/cpp/language/rule_of_three" rel="noreferrer">Rule of Zero</a>).</p>
<h2>Pointers</h2>
<p>However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, <strong>always prefer the alternatives unless you really need pointers</strong>.</p>
<ol>
<li><p><strong>You need reference semantics</strong>. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.</p></li>
<li><p><strong>You need polymorphism</strong>. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.</p></li>
<li><p><strong>You want to represent that an object is optional</strong> by allowing a <code>nullptr</code> to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such as <code>std::optional</code> (introduced in C++17 - with earlier C++ standards, use <code>boost::optional</code>).</p></li>
<li><p><strong>You want to decouple compilation units to improve compilation time</strong>. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">Pimpl idiom</a>.</p></li>
<li><p><strong>You need to interface with a C library</strong> or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its <code>get</code> member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.</p></li>
</ol> | {
"question_id": 22146094,
"question_date": "2014-03-03T11:54:16.520Z",
"question_score": 1836,
"tags": "c++|c++11|pointers|c++-faq",
"answer_id": 22146244,
"answer_date": "2014-03-03T12:01:23.767Z",
"answer_score": 1780
} |
Please answer the following Stack Overflow question:
Title: How can I add a key/value pair to a JavaScript object?
<p>Here is my object literal:</p>
<pre><code>var obj = {key1: value1, key2: value2};
</code></pre>
<p>How can I add field <code>key3</code> with <code>value3</code> to the object?</p> | <p>There are two ways to add new <strong>properties</strong> to an object:</p>
<pre><code>var obj = {
key1: value1,
key2: value2
};
</code></pre>
<h3>Using dot notation:</h3>
<pre><code>obj.key3 = "value3";
</code></pre>
<h3>Using square bracket notation:</h3>
<pre><code>obj["key3"] = "value3";
</code></pre>
<p>The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:</p>
<pre><code>var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");
</code></pre>
<hr>
<p>A <em>real</em> JavaScript array can be constructed using either:</p>
<h3>The Array literal notation:</h3>
<pre><code>var arr = [];
</code></pre>
<h3>The Array constructor notation:</h3>
<pre><code>var arr = new Array();
</code></pre> | {
"question_id": 1168807,
"question_date": "2009-07-22T23:21:51.500Z",
"question_score": 1835,
"tags": "javascript|object-literal",
"answer_id": 1168814,
"answer_date": "2009-07-22T23:25:19.920Z",
"answer_score": 2855
} |
Please answer the following Stack Overflow question:
Title: Meaning of @classmethod and @staticmethod for beginner
<p>What do <code>@classmethod</code> and <code>@staticmethod</code> mean in Python, and how are they different? <em>When</em> should I use them, <em>why</em> should I use them, and <em>how</em> should I use them?</p>
<p>As far as I understand, <code>@classmethod</code> tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just define the class method without adding <code>@classmethod</code> or <code>@staticmethod</code> or any <code>@</code> definitions?</p> | <p>Though <code>classmethod</code> and <code>staticmethod</code> are quite similar, there's a slight difference in usage for both entities: <code>classmethod</code> must have a reference to a class object as the first parameter, whereas <code>staticmethod</code> can have no parameters at all.</p>
<h2>Example</h2>
<pre><code>class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
</code></pre>
<h2>Explanation</h2>
<p>Let's assume an example of a class, dealing with date information (this will be our boilerplate):</p>
<pre><code>class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
</code></pre>
<p>This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).</p>
<p>Here we have <code>__init__</code>, a typical initializer of Python class instances, which receives arguments as a typical instance method, having the first non-optional argument (<code>self</code>) that holds a reference to a newly created instance.</p>
<p><strong>Class Method</strong></p>
<p>We have some tasks that can be nicely done using <code>classmethod</code>s.</p>
<p><em>Let's assume that we want to create a lot of <code>Date</code> class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.</em></p>
<p>So what we must do here is:</p>
<ol>
<li>Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.</li>
<li>Instantiate <code>Date</code> by passing those values to the initialization call.</li>
</ol>
<p>This will look like:</p>
<pre><code>day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
</code></pre>
<p>For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use <code>classmethod</code>. Let's create another <em>constructor</em>.</p>
<pre><code> @classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string('11-09-2012')
</code></pre>
<p>Let's look more carefully at the above implementation, and review what advantages we have here:</p>
<ol>
<li>We've implemented date string parsing in one place and it's reusable now.</li>
<li>Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).</li>
<li><code>cls</code> is the <strong>class itself</strong>, not an instance of the class. It's pretty cool because if we inherit our <code>Date</code> class, all children will have <code>from_string</code> defined also.</li>
</ol>
<p><strong>Static method</strong></p>
<p>What about <code>staticmethod</code>? It's pretty similar to <code>classmethod</code> but doesn't take any obligatory parameters (like a class method or instance method does).</p>
<p>Let's look at the next use case.</p>
<p><em>We have a date string that we want to validate somehow. This task is also logically bound to the <code>Date</code> class we've used so far, but doesn't require instantiation of it.</em></p>
<p>Here is where <code>staticmethod</code> can be useful. Let's look at the next piece of code:</p>
<pre><code> @staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
# usage:
is_date = Date.is_date_valid('11-09-2012')
</code></pre>
<p>So, as we can see from usage of <code>staticmethod</code>, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and other methods), which <code>classmethod</code> does have.</p> | {
"question_id": 12179271,
"question_date": "2012-08-29T13:37:33.443Z",
"question_score": 1834,
"tags": "python|oop|static-methods|class-method",
"answer_id": 12179752,
"answer_date": "2012-08-29T14:03:03.613Z",
"answer_score": 2865
} |
Please answer the following Stack Overflow question:
Title: Proper use of the IDisposable interface
<p>I know from reading <a href="https://docs.microsoft.com/dotnet/api/system.idisposable" rel="noreferrer">Microsoft documentation</a> that the "primary" use of the <code>IDisposable</code> interface is to clean up unmanaged resources.</p>
<p>To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the <code>Dispose()</code> method is implemented to free <em>managed</em> resources, which seems redundant to me, since the garbage collector should take care of that for you.</p>
<p>For example:</p>
<pre class="lang-cs prettyprint-override"><code>public class MyCollection : IDisposable
{
private List<String> _theList = new List<String>();
private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();
// Die, clear it up! (free unmanaged resources)
public void Dispose()
{
_theList.clear();
_theDict.clear();
_theList = null;
_theDict = null;
}
}
</code></pre>
<p>My question is, does this make the garbage collector free memory used by <code>MyCollection</code> any faster than it normally would?</p>
<hr />
<p><strong>Edit</strong>: So far people have posted some good examples of using <code>IDisposable</code> to clean up unmanaged resources such as database connections and bitmaps. But suppose that <code>_theList</code> in the above code contained a million strings, and you wanted to free that memory <em>now</em>, rather than waiting for the garbage collector. Would the above code accomplish that?</p> | <p>The point of Dispose <strong>is</strong> to free unmanaged resources. It needs to be done at some point, otherwise they will never be cleaned up. The garbage collector doesn't know <strong>how</strong> to call <code>DeleteHandle()</code> on a variable of type <code>IntPtr</code>, it doesn't know <strong>whether</strong> or not it needs to call <code>DeleteHandle()</code>.</p>
<blockquote>
<p><strong>Note</strong>: What is an <em>unmanaged resource</em>? If you found it in the Microsoft .NET Framework: it's managed. If you went poking around MSDN yourself, it's unmanaged. Anything you've used P/Invoke calls to get outside of the nice comfy world of everything available to you in the .NET Framework is unmanaged – and you're now responsible for cleaning it up.</p>
</blockquote>
<p>The object that you've created needs to expose <em>some</em> method, that the outside world can call, in order to clean up unmanaged resources. The method can be named whatever you like:</p>
<pre><code>public void Cleanup()
</code></pre>
<p>or</p>
<pre><code>public void Shutdown()
</code></pre>
<p>But instead there is a standardized name for this method:</p>
<pre><code>public void Dispose()
</code></pre>
<p>There was even an interface created, <code>IDisposable</code>, that has just that one method:</p>
<pre><code>public interface IDisposable
{
void Dispose()
}
</code></pre>
<p>So you make your object expose the <code>IDisposable</code> interface, and that way you promise that you've written that single method to clean up your unmanaged resources:</p>
<pre><code>public void Dispose()
{
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
}
</code></pre>
<p>And you're done. <strong>Except you can do better.</strong></p>
<hr />
<p>What if your object has allocated a 250MB <strong><a href="http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx" rel="noreferrer">System.Drawing.Bitmap</a></strong> (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to <em>eventually</em> come along and free it? What if there's an <a href="http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.aspx" rel="noreferrer">open database connection</a>? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.</p>
<p>If the user has called <code>Dispose()</code> (meaning they no longer plan to use the object) why not get rid of those wasteful bitmaps and database connections?</p>
<p>So now we will:</p>
<ul>
<li>get rid of unmanaged resources (because we have to), and</li>
<li>get rid of managed resources (because we want to be helpful)</li>
</ul>
<p>So let's update our <code>Dispose()</code> method to get rid of those managed objects:</p>
<pre><code>public void Dispose()
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//Free managed resources too
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose();
this.frameBufferImage = null;
}
}
</code></pre>
<p>And all is good, <strong>except you can do better</strong>!</p>
<hr />
<p>What if the person <strong>forgot</strong> to call <code>Dispose()</code> on your object? Then they would leak some <strong>unmanaged</strong> resources!</p>
<blockquote>
<p><strong>Note:</strong> They won't leak <strong>managed</strong> resources, because eventually the garbage collector is going to run, on a background thread, and free the memory associated with any unused objects. This will include your object, and any managed objects you use (e.g. the <code>Bitmap</code> and the <code>DbConnection</code>).</p>
</blockquote>
<p>If the person forgot to call <code>Dispose()</code>, we can <em>still</em> save their bacon! We still have a way to call it <em>for</em> them: when the garbage collector finally gets around to freeing (i.e. finalizing) our object.</p>
<blockquote>
<p><strong>Note:</strong> The garbage collector will eventually free all managed objects.
When it does, it calls the <strong><code>Finalize</code></strong>
method on the object. The GC doesn't know, or
care, about <em>your</em> <strong>Dispose</strong> method.
That was just a name we chose for
a method we call when we want to get
rid of unmanaged stuff.</p>
</blockquote>
<p>The destruction of our object by the Garbage collector is the <em>perfect</em> time to free those pesky unmanaged resources. We do this by overriding the <code>Finalize()</code> method.</p>
<blockquote>
<p><strong>Note:</strong> In C#, you don't explicitly override the <code>Finalize()</code> method.
You write a method that <em>looks like</em> a <strong>C++ destructor</strong>, and the
compiler takes that to be your implementation of the <code>Finalize()</code> method:</p>
</blockquote>
<pre><code>~MyObject()
{
//we're being finalized (i.e. destroyed), call Dispose in case the user forgot to
Dispose(); //<--Warning: subtle bug! Keep reading!
}
</code></pre>
<p>But there's a bug in that code. You see, the garbage collector runs on a <strong>background thread</strong>; you don't know the order in which two objects are destroyed. It is entirely possible that in your <code>Dispose()</code> code, the <strong>managed</strong> object you're trying to get rid of (because you wanted to be helpful) is no longer there:</p>
<pre><code>public void Dispose()
{
//Free unmanaged resources
Win32.DestroyHandle(this.gdiCursorBitmapStreamFileHandle);
//Free managed resources too
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose(); //<-- crash, GC already destroyed it
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose(); //<-- crash, GC already destroyed it
this.frameBufferImage = null;
}
}
</code></pre>
<p>So what you need is a way for <code>Finalize()</code> to tell <code>Dispose()</code> that it should <strong>not touch any managed</strong> resources (because they <em>might not be there</em> anymore), while still freeing unmanaged resources.</p>
<p>The standard pattern to do this is to have <code>Finalize()</code> and <code>Dispose()</code> both call a <strong>third</strong>(!) method; where you pass a Boolean saying if you're calling it from <code>Dispose()</code> (as opposed to <code>Finalize()</code>), meaning it's safe to free managed resources.</p>
<p>This <em>internal</em> method <em>could</em> be given some arbitrary name like "CoreDispose", or "MyInternalDispose", but is tradition to call it <code>Dispose(Boolean)</code>:</p>
<pre><code>protected void Dispose(Boolean disposing)
</code></pre>
<p>But a more helpful parameter name might be:</p>
<pre><code>protected void Dispose(Boolean itIsSafeToAlsoFreeManagedObjects)
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//Free managed resources too, but only if I'm being called from Dispose
//(If I'm being called from Finalize then the objects might not exist
//anymore
if (itIsSafeToAlsoFreeManagedObjects)
{
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose();
this.frameBufferImage = null;
}
}
}
</code></pre>
<p>And you change your implementation of the <code>IDisposable.Dispose()</code> method to:</p>
<pre><code>public void Dispose()
{
Dispose(true); //I am calling you from Dispose, it's safe
}
</code></pre>
<p>and your finalizer to:</p>
<pre><code>~MyObject()
{
Dispose(false); //I am *not* calling you from Dispose, it's *not* safe
}
</code></pre>
<blockquote>
<p><strong>Note</strong>: If your object descends from an object that implements <code>Dispose</code>, then don't forget to call their <strong>base</strong> Dispose method when you override Dispose:</p>
</blockquote>
<pre><code>public override void Dispose()
{
try
{
Dispose(true); //true: safe to free managed resources
}
finally
{
base.Dispose();
}
}
</code></pre>
<p>And all is good, <strong>except you can do better</strong>!</p>
<hr />
<p>If the user calls <code>Dispose()</code> on your object, then everything has been cleaned up. Later on, when the garbage collector comes along and calls Finalize, it will then call <code>Dispose</code> again.</p>
<p>Not only is this wasteful, but if your object has junk references to objects you already disposed of from the <strong>last</strong> call to <code>Dispose()</code>, you'll try to dispose them again!</p>
<p>You'll notice in my code I was careful to remove references to objects that I've disposed, so I don't try to call <code>Dispose</code> on a junk object reference. But that didn't stop a subtle bug from creeping in.</p>
<p>When the user calls <code>Dispose()</code>: the handle <strong>CursorFileBitmapIconServiceHandle</strong> is destroyed. Later when the garbage collector runs, it will try to destroy the same handle again.</p>
<pre><code>protected void Dispose(Boolean iAmBeingCalledFromDisposeAndNotFinalize)
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle); //<--double destroy
...
}
</code></pre>
<p>The way you fix this is tell the garbage collector that it doesn't need to bother finalizing the object – its resources have already been cleaned up, and no more work is needed. You do this by calling <code>GC.SuppressFinalize()</code> in the <code>Dispose()</code> method:</p>
<pre><code>public void Dispose()
{
Dispose(true); //I am calling you from Dispose, it's safe
GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later
}
</code></pre>
<p>Now that the user has called <code>Dispose()</code>, we have:</p>
<ul>
<li>freed unmanaged resources</li>
<li>freed managed resources</li>
</ul>
<p>There's no point in the GC running the finalizer – everything's taken care of.</p>
<h2>Couldn't I use Finalize to cleanup unmanaged resources?</h2>
<p>The documentation for <a href="https://msdn.microsoft.com/en-us/library/system.object.finalize.aspx" rel="noreferrer"><code>Object.Finalize</code></a> says:</p>
<blockquote>
<p>The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed.</p>
</blockquote>
<p>But the MSDN documentation also says, for <a href="https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx" rel="noreferrer"><code>IDisposable.Dispose</code></a>:</p>
<blockquote>
<p>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</p>
</blockquote>
<p>So which is it? Which one is the place for me to cleanup unmanaged resources? The answer is:</p>
<blockquote>
<p>It's your choice! But choose <code>Dispose</code>.</p>
</blockquote>
<p>You certainly could place your unmanaged cleanup in the finalizer:</p>
<pre><code>~MyObject()
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//A C# destructor automatically calls the destructor of its base class.
}
</code></pre>
<p>The problem with that is you have no idea when the garbage collector will get around to finalizing your object. Your un-managed, un-needed, un-used native resources will stick around until the garbage collector <em>eventually</em> runs. Then it will call your finalizer method; cleaning up unmanaged resources. The documentation of <strong>Object.Finalize</strong> points this out:</p>
<blockquote>
<p>The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a <strong>Close</strong> method or provide a <a href="https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx" rel="noreferrer"><code>IDisposable.Dispose</code></a> implementation.</p>
</blockquote>
<p>This is the virtue of using <code>Dispose</code> to cleanup unmanaged resources; you get to know, and control, when unmanaged resource are cleaned up. Their destruction is <em>"deterministic"</em>.</p>
<hr />
<p>To answer your original question: Why not release memory now, rather than for when the GC decides to do it? I have a facial recognition software that <em>needs</em> to get rid of 530 MB of internal images <strong>now</strong>, since they're no longer needed. When we don't: the machine grinds to a swapping halt.</p>
<h2>Bonus Reading</h2>
<p>For anyone who likes the style of this answer (explaining the <em>why</em>, so the <em>how</em> becomes obvious), I suggest you read Chapter One of Don Box's Essential COM:</p>
<ul>
<li>Direct link: <a href="http://ptgmedia.pearsoncmg.com/images/0201634465/samplechapter/chap01.pdf" rel="noreferrer">Chapter 1 sample by Pearson Publishing</a></li>
<li>magnet: 84bf0b960936d677190a2be355858e80ef7542c0</li>
</ul>
<p>In 35 pages he explains the problems of using binary objects, and invents COM before your eyes. Once you realize the <em>why</em> of COM, the remaining 300 pages are obvious, and just detail Microsoft's implementation.</p>
<p>I think every programmer who has ever dealt with objects or COM should, at the very least, read the first chapter. It is the best explanation of anything ever.</p>
<h2>Extra Bonus Reading</h2>
<p><a href="https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/" rel="noreferrer">When everything you know is wrong</a> <sup><a href="https://archive.today/JuXpm" rel="noreferrer">archive</a></sup>by Eric Lippert</p>
<blockquote>
<p>It is therefore very difficult indeed to write a correct finalizer,
and <strong>the best advice I can give you is to not try</strong>.</p>
</blockquote> | {
"question_id": 538060,
"question_date": "2009-02-11T18:12:41.470Z",
"question_score": 1830,
"tags": "c#|.net|garbage-collection|idisposable",
"answer_id": 538238,
"answer_date": "2009-02-11T18:55:20.617Z",
"answer_score": 2847
} |
Please answer the following Stack Overflow question:
Title: How to merge two arrays in JavaScript and de-duplicate items
<p>I have two JavaScript arrays:</p>
<pre><code>var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
</code></pre>
<p>I want the output to be:</p>
<pre><code>var array3 = ["Vijendra","Singh","Shakya"];
</code></pre>
<p>The output array should have repeated words removed.</p>
<p>How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays?</p> | <p>To just merge the arrays (without removing duplicates)</p>
<h3>ES5 version use <code>Array.concat</code>:</h3>
<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 array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
array1 = array1.concat(array2);
console.log(array1);</code></pre>
</div>
</div>
</p>
<h3>ES6 version use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">destructuring</a></h3>
<pre><code>const array1 = ["Vijendra","Singh"];
const array2 = ["Singh", "Shakya"];
const array3 = [...array1, ...array2];
</code></pre>
<p>Since there is no 'built in' way to remove duplicates (<a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer">ECMA-262</a> actually has <code>Array.forEach</code> which would be great for this), we have to do it manually:</p>
<pre><code>Array.prototype.unique = function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
</code></pre>
<p>Then, to use it:</p>
<pre><code>var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = array1.concat(array2).unique();
</code></pre>
<p>This will also preserve the order of the arrays (i.e, no sorting needed).</p>
<p>Since many people are annoyed about prototype augmentation of <code>Array.prototype</code> and <code>for in</code> loops, here is a less invasive way to use it:</p>
<pre><code>function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
var array1 = ["Vijendra","Singh"];
var array2 = ["Singh", "Shakya"];
// Merges both arrays and gets unique items
var array3 = arrayUnique(array1.concat(array2));
</code></pre>
<p>For those who are fortunate enough to work with browsers where ES5 is available, you can use <code>Object.defineProperty</code> like this:</p>
<pre><code>Object.defineProperty(Array.prototype, 'unique', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
var a = this.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
}
});
</code></pre> | {
"question_id": 1584370,
"question_date": "2009-10-18T08:34:57.023Z",
"question_score": 1828,
"tags": "javascript|arrays|merge",
"answer_id": 1584377,
"answer_date": "2009-10-18T08:42:43.087Z",
"answer_score": 2175
} |
Please answer the following Stack Overflow question:
Title: How do I clone a subdirectory only of a Git repository?
<p>I have my Git repository which, at the root, has two sub directories:</p>
<pre><code>/finisht
/static
</code></pre>
<p>When this was in <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>, <code>/finisht</code> was checked out in one place, while <code>/static</code> was checked out elsewhere, like so:</p>
<pre><code>svn co svn+ssh://[email protected]/home/admin/repos/finisht/static static
</code></pre>
<p>Is there a way to do this with Git?</p> | <p><strong>EDIT</strong>: As of Git 2.19, this is finally possible, as can be seen in this <a href="https://stackoverflow.com/a/52269934/2988">answer</a>.</p>
<p>Consider upvoting that answer.</p>
<p>Note: in Git 2.19, only client-side support is implemented, server-side support is still missing, so it only works when cloning local repositories. Also note that large Git hosters, e.g. GitHub, don't actually use the Git server, they use their own implementation, so even if support shows up in the Git server, it does not automatically mean that it works on Git hosters. (OTOH, since they don't use the Git server, they could implement it faster in their own implementations before it shows up in Git server.)</p>
<hr>
<p>No, that's not possible in Git.</p>
<p>Implementing something like this in Git would be a substantial effort and it would mean that the integrity of the clientside repository could no longer be guaranteed. If you are interested, search for discussions on "sparse clone" and "sparse fetch" on the git mailinglist.</p>
<p>In general, the consensus in the Git community is that if you have several directories that are always checked out independently, then these are really two different projects and should live in two different repositories. You can glue them back together using <a href="https://book.git-scm.com/book/en/v2/Git-Tools-Submodules" rel="noreferrer">Git Submodules</a>.</p> | {
"question_id": 600079,
"question_date": "2009-03-01T16:46:32.527Z",
"question_score": 1828,
"tags": "git|repository|subdirectory|git-clone|sparse-checkout",
"answer_id": 600189,
"answer_date": "2009-03-01T18:00:23.660Z",
"answer_score": 751
} |
Please answer the following Stack Overflow question:
Title: <button> vs. <input type="button" />. Which to use?
<p>When looking at most sites (including SO), most of them use:</p>
<pre><code><input type="button" />
</code></pre>
<p>instead of:</p>
<pre><code><button></button>
</code></pre>
<ul>
<li>What are the main differences between the two, if any?</li>
<li>Are there valid reasons to use one instead of the other?</li>
<li>Are there valid reasons to use combine them?</li>
<li>Does using <code><button></code> come with compatibility issues, seeing it is not very widely used?</li>
</ul> | <ul>
<li><a href="http://web.archive.org/web/20110721191046/http://particletree.com/features/rediscovering-the-button-element/" rel="noreferrer">Here's a page</a> describing the differences (basically you can put html into a <code><button></button></code>)</li>
<li><a href="http://www.peterbe.com/plog/button-tag-in-IE" rel="noreferrer">And another page</a> describing why people avoid <code><button></button></code> (Hint: IE6)</li>
</ul>
<p>Another IE problem when using <code><button /></code>:</p>
<blockquote>
<p>And while we're talking about IE, it's
got a couple of bugs related to the
width of buttons. It'll mysteriously
add extra padding when you're trying
to add styles, meaning you have to add
a tiny hack to get things under
control.</p>
</blockquote> | {
"question_id": 469059,
"question_date": "2009-01-22T13:14:11.357Z",
"question_score": 1828,
"tags": "html|button|compatibility",
"answer_id": 469084,
"answer_date": "2009-01-22T13:20:02.687Z",
"answer_score": 714
} |
Please answer the following Stack Overflow question:
Title: Select first row in each GROUP BY group?
<p>As the title suggests, I'd like to select the first row of each set of rows grouped with a <code>GROUP BY</code>.</p>
<p>Specifically, if I've got a <code>purchases</code> table that looks like this:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM purchases;
</code></pre>
<p><strong>My Output:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>customer</th>
<th>total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Joe</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>Joe</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>Sally</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I'd like to query for the <code>id</code> of the largest purchase (<code>total</code>) made by each <code>customer</code>. Something like this:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT FIRST(id), customer, FIRST(total)
FROM purchases
GROUP BY customer
ORDER BY total DESC;
</code></pre>
<p><strong>Expected Output:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>FIRST(id)</th>
<th>customer</th>
<th>FIRST(total)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Joe</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>Sally</td>
<td>3</td>
</tr>
</tbody>
</table>
</div> | <h2>On databases that <a href="https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression" rel="noreferrer">support CTE and windowing functions</a>:</h2>
<pre><code>WITH summary AS (
SELECT p.id,
p.customer,
p.total,
ROW_NUMBER() OVER(PARTITION BY p.customer
ORDER BY p.total DESC) AS rank
FROM PURCHASES p)
SELECT *
FROM summary
WHERE rank = 1
</code></pre>
<h2>Supported by any database:</h2>
<p>But you need to add logic to break ties:</p>
<pre><code> SELECT MIN(x.id), -- change to MAX if you want the highest
x.customer,
x.total
FROM PURCHASES x
JOIN (SELECT p.customer,
MAX(total) AS max_total
FROM PURCHASES p
GROUP BY p.customer) y ON y.customer = x.customer
AND y.max_total = x.total
GROUP BY x.customer, x.total
</code></pre> | {
"question_id": 3800551,
"question_date": "2010-09-27T01:23:22.873Z",
"question_score": 1826,
"tags": "sql|sqlite|postgresql|group-by|greatest-n-per-group",
"answer_id": 3800572,
"answer_date": "2010-09-27T01:27:54.880Z",
"answer_score": 1436
} |
Please answer the following Stack Overflow question:
Title: How to get just one file from another branch?
<p>I have a <code>master</code> branch with a file called <code>app.js</code>. I made changes to this file on an <code>experiment</code> branch.</p>
<p>I want to apply only the changes made to <code>app.js</code> from <code>experiment</code> onto the <code>master</code> branch.</p> | <pre><code>git checkout master # first get back to master
git checkout experiment -- app.js # then copy the version of app.js
# from branch "experiment"
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/692246/git-how-to-undo-changes-of-one-file">git how to undo changes of one file?</a></p>
<hr />
<h3>Update August 2019, Git 2.23</h3>
<p>With the new <a href="https://stackoverflow.com/a/57066202/6309"><code>git switch</code></a> and <a href="https://stackoverflow.com/a/57066072/6309"><code>git restore</code></a> commands, that would be:</p>
<pre><code>git switch master
git restore --source experiment -- app.js
</code></pre>
<p>By default, only the working tree is restored.<br />
If you want to update the index as well (meaning restore the file content, <em>and</em> add it to the index in one command):</p>
<pre><code>git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js
</code></pre>
<hr />
<p>As <a href="https://stackoverflow.com/users/46058/jakub-narebski">Jakub Narębski</a> mentions in the comments:</p>
<pre><code>git show experiment:path/to/app.js > path/to/app.js
</code></pre>
<p>works too, except that, as detailed in the SO question "<a href="https://stackoverflow.com/questions/610208/how-to-retrieve-a-single-file-from-specific-revision-in-git/610315#610315">How to retrieve a single file from specific revision in Git?</a>", you need to use the full path from the root directory of the repo.<br />
Hence the path/to/app.js used by Jakub in his example.</p>
<p>As <a href="https://stackoverflow.com/users/7476/frosty">Frosty</a> mentions in the comment:</p>
<blockquote>
<p>you will only get the most recent state of app.js</p>
</blockquote>
<p>But, for <code>git checkout</code> or <code>git show</code>, you can actually reference any revision you want, as illustrated in the SO question "<a href="https://stackoverflow.com/questions/1507300/git-checkout-revision-of-a-file-in-git-gui/1507678#1507678">git checkout revision of a file in git gui</a>":</p>
<pre><code>$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME
</code></pre>
<p>would be the same is $FILENAME is a <strong>full path</strong> of a versioned file.</p>
<p><code>$REVISION</code> can be as shown in <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html" rel="noreferrer"><code>git rev-parse</code></a>:</p>
<pre><code>experiment@{yesterday}:app.js # app.js as it was yesterday
experiment^:app.js # app.js on the first commit parent
experiment@{2}:app.js # app.js two commits ago
</code></pre>
<p>and so on.</p>
<p><a href="https://stackoverflow.com/users/430418/schmijos">schmijos</a> adds <a href="https://stackoverflow.com/questions/2364147/how-to-get-just-one-file-from-another-branch/2364223#comment93480592_2364223">in the comments</a>:</p>
<blockquote>
<p>you also can do this from a stash:</p>
<pre><code>git checkout stash -- app.js
</code></pre>
<p>This is very useful if you're working on two branches and don't want to commit.</p>
</blockquote> | {
"question_id": 2364147,
"question_date": "2010-03-02T15:15:18.127Z",
"question_score": 1824,
"tags": "git|git-branch|git-checkout",
"answer_id": 2364223,
"answer_date": "2010-03-02T15:23:21.933Z",
"answer_score": 2240
} |
Please answer the following Stack Overflow question:
Title: Transitions on the CSS display property
<p>I'm currently designing a CSS 'mega dropdown' menu - basically a regular CSS-only dropdown menu, but one that contains different types of content.</p>
<p>At the moment, <strong>it appears that CSS 3 transitions don't apply to the 'display' property</strong>, i.e., you can't do any sort of transition from <code>display: none</code> to <code>display: block</code> (or any combination).</p>
<p>Is there a way for the second-tier menu from the above example to 'fade in' when someone hovers over one of the top level menu items?</p>
<p>I'm aware that you can use transitions on the <code>visibility:</code> property, but I can't think of a way to use that effectively.</p>
<p>I've also tried using height, but that just failed miserably.</p>
<p>I'm also aware that it's trivial to achieve this using JavaScript, but I wanted to challenge myself to use just CSS, and I think I'm coming up a little short.</p> | <p>You can concatenate two transitions or more, and <code>visibility</code> is what comes handy this time.</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>div {
border: 1px solid #eee;
}
div > ul {
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s linear;
}
div:hover > ul {
visibility: visible;
opacity: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>(Don't forget the vendor prefixes to the <code>transition</code> property.)</p>
<p>More details are in <a href="http://www.greywyvern.com/?post=337" rel="noreferrer">this article</a>.</p> | {
"question_id": 3331353,
"question_date": "2010-07-25T22:52:49.843Z",
"question_score": 1821,
"tags": "css|css-transitions",
"answer_id": 6943704,
"answer_date": "2011-08-04T14:58:25.047Z",
"answer_score": 1651
} |
Please answer the following Stack Overflow question:
Title: How to convert decimal to hexadecimal in JavaScript
<p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p> | <p>Convert a number to a hexadecimal string with:</p>
<pre><code>hexString = yourNumber.toString(16);
</code></pre>
<p>And reverse the process with:</p>
<pre><code>yourNumber = parseInt(hexString, 16);
</code></pre> | {
"question_id": 57803,
"question_date": "2008-09-11T22:26:58.453Z",
"question_score": 1821,
"tags": "javascript|hex|number-formatting|base",
"answer_id": 57805,
"answer_date": "2008-09-11T22:28:34.610Z",
"answer_score": 3043
} |
Please answer the following Stack Overflow question:
Title: How to redirect and append both standard output and standard error to a file with Bash
<p>To redirect <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> to a truncated file in Bash, I know to use:</p>
<pre><code>cmd > file.txt
</code></pre>
<p>To redirect standard output in Bash, appending to a file, I know to use:</p>
<pre><code>cmd >> file.txt
</code></pre>
<p>To redirect both standard output and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a truncated file, I know to use:</p>
<pre><code>cmd &> file.txt
</code></pre>
<p>How do I redirect both standard output and standard error appending to a file? <code>cmd &>> file.txt</code> did not work for me.</p> | <pre><code>cmd >>file.txt 2>&1
</code></pre>
<p>Bash executes the redirects from left to right as follows:</p>
<ol>
<li><code>>>file.txt</code>: Open <code>file.txt</code> in append mode and redirect <code>stdout</code> there.</li>
<li><code>2>&1</code>: Redirect <code>stderr</code> to <em>"where <code>stdout</code> is currently going"</em>. In this case, that is a file opened in append mode. In other words, the <code>&1</code> reuses the file descriptor which <code>stdout</code> currently uses.</li>
</ol> | {
"question_id": 876239,
"question_date": "2009-05-18T04:19:45.877Z",
"question_score": 1820,
"tags": "bash|append|stdout|io-redirection|stderr",
"answer_id": 876242,
"answer_date": "2009-05-18T04:23:16.287Z",
"answer_score": 2346
} |
Please answer the following Stack Overflow question:
Title: Command to collapse all sections of code?
<p>In Visual Studio is there a command to collapse/expand all the sections of code in a file?</p> | <p><kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>O</kbd> will collapse all.</p>
<p><kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>L</kbd> will expand all. (in VS 2013 - Toggle All outlining)</p>
<p><kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>P</kbd> will expand all and disable outlining.</p>
<p><kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>M</kbd> will collapse/expand the current section.</p>
<p><kbd>CTRL</kbd> + <kbd>M</kbd> + <kbd>A</kbd> will collapse all even in Html files.</p>
<p>These controls are also in the context menu under Outlining.</p>
<p>Right click in editor -> Outlining to find these controls.
(<em>After disabling outlining, use same steps to enable outlining.</em>)</p>
<p><em><strong>For outlining options</strong></em>: Go to Tools -> Options -> Text Editor -> C# -> Advanced -> Outlining for outlining options.</p>
<p><img src="https://i.stack.imgur.com/5phNu.png" alt="Tools -> Options -> Text Editor -> C# -> Advanced -> Outlining" />
<img src="https://i.stack.imgur.com/EnXSd.png" alt="Right-click > Outlining menu" /></p> | {
"question_id": 982677,
"question_date": "2009-06-11T18:05:10.133Z",
"question_score": 1820,
"tags": "visual-studio",
"answer_id": 982704,
"answer_date": "2009-06-11T18:08:24.247Z",
"answer_score": 3279
} |
Please answer the following Stack Overflow question:
Title: Get the last item in an array
<p>Here is my JavaScript code so far:</p>
<pre><code>var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
</code></pre>
<p>Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be <code>"index.html"</code> and if so, grab the third to last item instead.</p> | <pre><code>if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
</code></pre>
<p>In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: <code>.toLowerCase()</code>.</p>
<p>Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.</p>
<hr />
<p><strong>EDIT - ES-2022</strong></p>
<p>Using ES-2022 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at" rel="noreferrer"><code>Array.at()</code></a>, the above may be written like this:</p>
<pre><code>if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
</code></pre> | {
"question_id": 3216013,
"question_date": "2010-07-09T19:45:06.567Z",
"question_score": 1816,
"tags": "javascript|arrays|es2022",
"answer_id": 3216041,
"answer_date": "2010-07-09T19:48:58.323Z",
"answer_score": 2067
} |
Please answer the following Stack Overflow question:
Title: How to randomize (shuffle) a JavaScript array?
<p>I have an array like this:</p>
<pre><code>var arr1 = ["a", "b", "c", "d"];
</code></pre>
<p>How can I randomize / shuffle it?</p> | <p>The de-facto unbiased shuffle algorithm is the <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="noreferrer">Fisher-Yates (aka Knuth) Shuffle</a>.</p>
<p>You can see a <a href="http://bost.ocks.org/mike/shuffle/" rel="noreferrer">great visualization here</a> (and the original post <a href="http://sedition.com/perl/javascript-fy.html" rel="noreferrer">linked to this</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>function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);</code></pre>
</div>
</div>
</p>
<p>Some more info <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle" rel="noreferrer">about the algorithm</a> used.</p> | {
"question_id": 2450954,
"question_date": "2010-03-15T22:37:11.700Z",
"question_score": 1816,
"tags": "javascript|arrays|random|shuffle",
"answer_id": 2450976,
"answer_date": "2010-03-15T22:41:10.630Z",
"answer_score": 2222
} |
Please answer the following Stack Overflow question:
Title: Is there a reason for C#'s reuse of the variable in a foreach?
<p>When using lambda expressions or anonymous methods in C#, we have to be wary of the <em>access to modified closure</em> pitfall. For example:</p>
<pre><code>foreach (var s in strings)
{
query = query.Where(i => i.Prop == s); // access to modified closure
...
}
</code></pre>
<p>Due to the modified closure, the above code will cause all of the <code>Where</code> clauses on the query to be based on the final value of <code>s</code>.</p>
<p>As explained <a href="http://resnikb.wordpress.com/2009/06/17/c-lambda-and-foreach-variable/" rel="noreferrer">here</a>, this happens because the <code>s</code> variable declared in <code>foreach</code> loop above is translated like this in the compiler:</p>
<pre><code>string s;
while (enumerator.MoveNext())
{
s = enumerator.Current;
...
}
</code></pre>
<p>instead of like this:</p>
<pre><code>while (enumerator.MoveNext())
{
string s;
s = enumerator.Current;
...
}
</code></pre>
<p>As pointed out <a href="https://stackoverflow.com/a/2388644/120955">here</a>, there are no performance advantages to declaring a variable outside the loop, and under normal circumstances the only reason I can think of for doing this is if you plan to use the variable outside the scope of the loop:</p>
<pre><code>string s;
while (enumerator.MoveNext())
{
s = enumerator.Current;
...
}
var finalString = s;
</code></pre>
<p>However variables defined in a <code>foreach</code> loop cannot be used outside the loop:</p>
<pre><code>foreach(string s in strings)
{
}
var finalString = s; // won't work: you're outside the scope.
</code></pre>
<p>So the compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.</p>
<p>Is there something you can do with <code>foreach</code> loops this way that you couldn't if they were compiled with an inner-scoped variable, or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?</p> | <blockquote>
<p>The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.</p>
</blockquote>
<p>Your criticism is entirely justified.</p>
<p>I discuss this problem in detail here:</p>
<p><a href="http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/" rel="noreferrer">Closing over the loop variable considered harmful</a></p>
<blockquote>
<p>Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?</p>
</blockquote>
<p>The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.</p>
<p>I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and <strong>we are going to take the breaking change to fix it.</strong> In C# 5 the foreach loop variable will be logically <em>inside</em> the body of the loop, and therefore closures will get a fresh copy every time.</p>
<p>The <code>for</code> loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.</p> | {
"question_id": 8898925,
"question_date": "2012-01-17T17:21:07.257Z",
"question_score": 1816,
"tags": "c#|foreach|lambda|scope|anonymous-methods",
"answer_id": 8899347,
"answer_date": "2012-01-17T17:56:25.633Z",
"answer_score": 1492
} |
Please answer the following Stack Overflow question:
Title: How do I split the definition of a long string over multiple lines?
<p>I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a <code>+</code> operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:</p>
<pre class="lang-js prettyprint-override"><code>var long_string = 'some text not important. just garbage to' +
'illustrate my example';
</code></pre>
<p>I tried doing something similar in Python, but it didn't work, so I used <code>\</code> to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward.
Actual code:</p>
<pre class="lang-py prettyprint-override"><code>query = 'SELECT action.descr as "action", '\
'role.id as role_id,'\
'role.descr as role'\
'FROM '\
'public.role_action_def,'\
'public.role,'\
'public.record_def, '\
'public.action'\
'WHERE role.id = role_action_def.role_id AND'\
'record_def.id = role_action_def.def_id AND'\
'action.id = role_action_def.action_id AND'\
'role_action_def.account_id = ' + account_id + ' AND'\
'record_def.account_id=' + account_id + ' AND'\
'def_id=' + def_id
</code></pre> | <p>Are you talking about multi-line strings? Easy, use triple quotes to start and end them.</p>
<pre><code>s = """ this is a very
long string if I had the
energy to type more and more ..."""
</code></pre>
<p>You can use single quotes too (3 of them of course at start and end) and treat the resulting string <code>s</code> just like any other string.</p>
<p><strong>NOTE</strong>: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.</p>
<p>I.e.,:</p>
<pre><code>' this is a very\n long string if I had the\n energy to type more and more ...'
</code></pre>
<p>Finally, one can also construct long lines in Python like this:</p>
<pre><code> s = ("this is a very"
"long string too"
"for sure ..."
)
</code></pre>
<p>which will <strong>not</strong> include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):</p>
<pre><code>'this is a verylong string toofor sure ...'
</code></pre>
<p>No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.</p> | {
"question_id": 10660435,
"question_date": "2012-05-18T22:21:09.633Z",
"question_score": 1814,
"tags": "python|string|multiline|multilinestring",
"answer_id": 10660443,
"answer_date": "2012-05-18T22:22:54.710Z",
"answer_score": 3008
} |
Please answer the following Stack Overflow question:
Title: Loop inside React JSX
<p>I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):</p>
<pre><code><tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
</code></pre>
<p>I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).</p> | <p>Think of it like you're just calling JavaScript functions. You can't use a <code>for</code> loop where the arguments to a function call would go:</p>
<pre><code>return tbody(
for (let i = 0; i < numrows; i++) {
ObjectRow()
}
)
</code></pre>
<p>See how the function <code>tbody</code> is being passed a <code>for</code> loop as an argument – leading to a syntax error.</p>
<p>But you can make an array, and then pass that in as an argument:</p>
<pre><code>const rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}
return tbody(rows);
</code></pre>
<hr />
<p>You can basically use the same structure when working with JSX:</p>
<pre><code>const rows = [];
for (let i = 0; i < numrows; i++) {
// note: we are adding a key prop here to allow react to uniquely identify each
// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;
</code></pre>
<p>Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with <a href="https://babeljs.io/repl" rel="noreferrer">Babel REPL</a> to get a feel for how JSX works.</p> | {
"question_id": 22876978,
"question_date": "2014-04-05T05:29:28.190Z",
"question_score": 1814,
"tags": "javascript|reactjs|jsx",
"answer_id": 22877049,
"answer_date": "2014-04-05T05:39:46.420Z",
"answer_score": 1630
} |
Please answer the following Stack Overflow question:
Title: Why do I need to do `--set-upstream` all the time?
<p>I create a new branch in Git:</p>
<pre><code>git branch my_branch
</code></pre>
<p>Push it:</p>
<pre><code>git push origin my_branch
</code></pre>
<p>Now say someone made some changes on the server and I want to pull from <code>origin/my_branch</code>. I do:</p>
<pre><code>git pull
</code></pre>
<p>But I get:</p>
<pre><code>You asked me to pull without telling me which branch you
want to merge with, and 'branch.my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "my_branch"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
</code></pre>
<p>I learned that I can make it work with:</p>
<pre><code>git branch --set-upstream my_branch origin/my_branch
</code></pre>
<p>But why do I need to do this for every branch I create? Isn't it obvious that if I push <code>my_branch</code> into <code>origin/my_branch</code>, then I would want to pull <code>origin/my_branch</code> into <code>my_branch</code>? How can I make this the default behavior?</p> | <p>A shortcut, which doesn't depend on remembering the syntax for <code>git branch --set-upstream</code> <sup>1</sup> is to do:</p>
<pre><code>git push -u origin my_branch
</code></pre>
<p>... the first time that you push that branch. Or, to push to the current branch from a branch of the same name (handy for an alias):</p>
<pre><code>git push -u origin HEAD
</code></pre>
<p>You only need to use <code>-u</code> once, and that sets up the association between your branch and the one at <code>origin</code> in the same way as <code>git branch --set-upstream</code> does.</p>
<p>Personally, I think it's a good thing to have to set up that association between your branch and one on the remote explicitly. It's just a shame that the rules are <a href="http://longair.net/blog/2011/02/27/an-asymmetry-between-git-pull-and-git-push/" rel="nofollow noreferrer">different for <code>git push</code> and <code>git pull</code></a>.</p>
<hr />
<p><sup>1</sup> It may sound silly, but I very frequently forget to specify the current branch, assuming that's the default - it's not, and the results are most confusing.</p>
<p><em>Update 2012-10-11</em>: Apparently I'm not the only person who found it easy to get wrong! Thanks to <a href="https://stackoverflow.com/users/6309/vonc">VonC</a> for pointing out that git 1.8.0 introduces the more obvious <code>git branch --set-upstream-to</code>, which can be used as follows, if you're on the branch <code>my_branch</code>:</p>
<pre><code>git branch --set-upstream-to origin/my_branch
</code></pre>
<p>... or with the short option:</p>
<pre><code>git branch -u origin/my_branch
</code></pre>
<p>This change, and its reasoning, is described in <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.8.0.txt" rel="nofollow noreferrer">the release notes for git 1.8.0, release candidate 1</a>:</p>
<blockquote>
<p>It was tempting to say <code>git branch --set-upstream origin/master</code>, but that tells Git to arrange the local branch <code>origin/master</code> to integrate with the currently checked out branch, which is highly unlikely to be what the user meant. The option is deprecated; use the new <code>--set-upstream-to</code> (with a short-and-sweet <code>-u</code>) option instead.</p>
</blockquote> | {
"question_id": 6089294,
"question_date": "2011-05-22T16:39:49.923Z",
"question_score": 1814,
"tags": "git|git-branch",
"answer_id": 6089415,
"answer_date": "2011-05-22T16:58:56.067Z",
"answer_score": 1765
} |
Please answer the following Stack Overflow question:
Title: How can I get a list of Git branches, ordered by most recent commit?
<p>I want to get a list of all the branches in a Git repository with the "freshest" branches at the top, where the "freshest" branch is the one that's been committed to most recently (and is, therefore, more likely to be one I want to pay attention to).</p>
<p>Is there a way I can use Git to either (a) sort the list of branches by latest commit, or (b) get a list of branches together with each one's last-commit date, in some kind of machine-readable format?</p>
<p>Worst case, I could always run <code>git branch</code> to get a list of all the branches, parse its output, and then <code>git log -n 1 branchname --format=format:%ci</code> for each one, to get each branch's commit date. But this will run on a Windows box, where spinning up a new process is relatively expensive, so launching the Git executable once per branch could get slow if there are a lot of branches. Is there a way to do all this with a single command?</p> | <p>Use the <strong><code>--sort=-committerdate</code></strong> option of <a href="http://www.kernel.org/pub/software/scm/git/docs/git-for-each-ref.html" rel="noreferrer"><code>git for-each-ref</code></a>;</p>
<p>Also available <a href="https://git-blame.blogspot.com/" rel="noreferrer">since Git 2.7.0</a> for <a href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html" rel="noreferrer"><code>git branch</code></a>:</p>
<h1>Basic Usage:</h1>
<pre class="lang-shell prettyprint-override"><code>git for-each-ref --sort=-committerdate refs/heads/
# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate # DESC
git branch --sort=committerdate # ASC
</code></pre>
<h3>Result:</h3>
<p><img src="https://i.imgur.com/AlaP8dD.png" alt="Result" /></p>
<h1>Advanced Usage:</h1>
<pre class="lang-shell prettyprint-override"><code>git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
</code></pre>
<h3>Result:</h3>
<p><img src="https://i.imgur.com/tDCTiZx.png" alt="Result" /></p>
<h1>Pro Usage (Unix):</h1>
<p>You can put the following snippet in your <code>~/.gitconfig</code>. The recentb alias accepts two arguments:</p>
<ul>
<li><code>refbranch</code>: which branch the <em>ahead</em> and <em>behind</em> columns are calculated against. Default <em>master</em></li>
<li><code>count</code>: how many recent branches to show. Default <em>20</em></li>
</ul>
<pre class="lang-shell prettyprint-override"><code>[alias]
# ATTENTION: All aliases prefixed with ! run in /bin/sh make sure you use sh syntax, not bash/zsh or whatever
recentb = "!r() { refbranch=$1 count=$2; git for-each-ref --sort=-committerdate refs/heads --format='%(refname:short)|%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always --count=${count:-20} | while read line; do branch=$(echo \"$line\" | awk 'BEGIN { FS = \"|\" }; { print $1 }' | tr -d '*'); ahead=$(git rev-list --count \"${refbranch:-origin/master}..${branch}\"); behind=$(git rev-list --count \"${branch}..${refbranch:-origin/master}\"); colorline=$(echo \"$line\" | sed 's/^[^|]*|//'); echo \"$ahead|$behind|$colorline\" | awk -F'|' -vOFS='|' '{$5=substr($5,1,70)}1' ; done | ( echo \"ahead|behind||branch|lastcommit|message|author\\n\" && cat) | column -ts'|';}; r"
</code></pre>
<h3>Result:</h3>
<p><a href="https://i.stack.imgur.com/Q8Buq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q8Buq.png" alt="Recentb alias result" /></a></p> | {
"question_id": 5188320,
"question_date": "2011-03-04T00:26:35.063Z",
"question_score": 1811,
"tags": "git|version-control|branch",
"answer_id": 5188364,
"answer_date": "2011-03-04T00:33:02.743Z",
"answer_score": 2533
} |
Please answer the following Stack Overflow question:
Title: What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?
<p>Python 3.3 includes in its standard library the new package <code>venv</code>. What does it do, and how does it differ from all the other packages that match the regex <code>(py)?(v|virtual|pip)?env</code>?</p> | <p><strong>This is my personal recommendation for beginners:</strong> start by learning <a href="https://pypi.org/project/virtualenv/" rel="noreferrer"><code>virtualenv</code></a> and <a href="https://pypi.org/project/pip/" rel="noreferrer"><code>pip</code></a>, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.</p>
<p>Now on to the answer to the question: what is the difference between these simalarly named things: venv, virtualenv, etc?</p>
<h1>PyPI packages not in the standard library:</h1>
<ul>
<li><p><strong><a href="https://pypi.python.org/pypi/virtualenv" rel="noreferrer"><code>virtualenv</code></a></strong> is a very popular tool that creates isolated Python environments for Python libraries. If you're not familiar with this tool, I highly recommend learning it, as it is a very useful tool.</p>
<p>It works by installing a bunch of files in a directory (eg: <code>env/</code>), and then modifying the <code>PATH</code> environment variable to prefix it with a custom <code>bin</code> directory (eg: <code>env/bin/</code>). An exact copy of the <code>python</code> or <code>python3</code> binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It's not part of Python's standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using <code>pip</code>.</p>
</li>
<li><p><strong><a href="https://github.com/pyenv/pyenv" rel="noreferrer"><code>pyenv</code></a></strong> is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you'll need a way to switch between them. Once activated, it prefixes the <code>PATH</code> environment variable with <code>~/.pyenv/shims</code>, where there are special files matching the Python commands (<code>python</code>, <code>pip</code>). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the <code>PYENV_VERSION</code> environment variable, or the <code>.python-version</code> file, or the <code>~/.pyenv/version</code> file. <code>pyenv</code> also makes the process of downloading and installing multiple Python versions easier, using the command <code>pyenv install</code>.</p>
</li>
<li><p><strong><a href="https://github.com/pyenv/pyenv-virtualenv" rel="noreferrer"><code>pyenv-virtualenv</code></a></strong> is a plugin for <code>pyenv</code> by the same author as <code>pyenv</code>, to allow you to use <code>pyenv</code> and <code>virtualenv</code> at the same time conveniently. However, if you're using Python 3.3 or later, <code>pyenv-virtualenv</code> will try to run <code>python -m venv</code> if it is available, instead of <code>virtualenv</code>. You can use <code>virtualenv</code> and <code>pyenv</code> together without <code>pyenv-virtualenv</code>, if you don't want the convenience features.</p>
</li>
<li><p><strong><a href="https://pypi.python.org/pypi/virtualenvwrapper" rel="noreferrer"><code>virtualenvwrapper</code></a></strong> is a set of extensions to <code>virtualenv</code> (see <a href="http://virtualenvwrapper.readthedocs.io/en/latest/" rel="noreferrer">docs</a>). It gives you commands like <code>mkvirtualenv</code>, <code>lssitepackages</code>, and especially <code>workon</code> for switching between different <code>virtualenv</code> directories. This tool is especially useful if you want multiple <code>virtualenv</code> directories.</p>
</li>
<li><p><strong><a href="https://github.com/pyenv/pyenv-virtualenvwrapper" rel="noreferrer"><code>pyenv-virtualenvwrapper</code></a></strong> is a plugin for <code>pyenv</code> by the same author as <code>pyenv</code>, to conveniently integrate <code>virtualenvwrapper</code> into <code>pyenv</code>.</p>
</li>
<li><p><strong><a href="https://pypi.python.org/pypi/pipenv" rel="noreferrer"><code>pipenv</code></a></strong> aims to combine <code>Pipfile</code>, <code>pip</code> and <code>virtualenv</code> into one command on the command-line. The <code>virtualenv</code> directory typically gets placed in <code>~/.local/share/virtualenvs/XXX</code>, with <code>XXX</code> being a hash of the path of the project directory. This is different from <code>virtualenv</code>, where the directory is typically in the current working directory. <code>pipenv</code> is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to <code>pipenv</code>, such as <code>poetry</code>, which I won't list here since this question is only about the packages that are similarly named.</p>
</li>
</ul>
<h1>Standard library:</h1>
<ul>
<li><p><strong><code>pyvenv</code></strong> (not to be confused with <strong><a href="https://github.com/pyenv/pyenv" rel="noreferrer"><code>pyenv</code></a></strong> in the previous section) is a script shipped with Python 3.3 to 3.7. It was <a href="https://docs.python.org/3/whatsnew/3.8.html#api-and-feature-removals" rel="noreferrer">removed from Python 3.8</a> as it had problems (not to mention the confusing name). Running <code>python3 -m venv</code> has exactly the same effect as <code>pyvenv</code>.</p>
</li>
<li><p><strong><a href="https://docs.python.org/3/library/venv.html" rel="noreferrer"><code>venv</code></a></strong> is a package shipped with Python 3, which you can run using <code>python3 -m venv</code> (although for some reason some distros separate it out into a separate distro package, such as <code>python3-venv</code> on Ubuntu/Debian). It serves the same purpose as <code>virtualenv</code>, but only has a subset of its features (<a href="https://virtualenv.pypa.io/en/latest/" rel="noreferrer">see a comparison here</a>). <code>virtualenv</code> continues to be more popular than <code>venv</code>, especially since the former supports both Python 2 and 3.</p>
</li>
</ul> | {
"question_id": 41573587,
"question_date": "2017-01-10T16:27:43.207Z",
"question_score": 1808,
"tags": "python|virtualenv|virtualenvwrapper|pyenv|python-venv",
"answer_id": 41573588,
"answer_date": "2017-01-10T16:27:43.207Z",
"answer_score": 2080
} |
Please answer the following Stack Overflow question:
Title: Check existence of input argument in a Bash shell script
<p>I need to check the existence of an input argument. I have the following script</p>
<pre><code>if [ "$1" -gt "-1" ]
then echo hi
fi
</code></pre>
<p>I get</p>
<pre><code>[: : integer expression expected
</code></pre>
<p>How do I check the input argument1 first to see if it exists?</p> | <p>It is:</p>
<pre class="lang-bash prettyprint-override"><code>if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
</code></pre>
<p>The <code>$#</code> variable will tell you the number of input arguments the script was passed.</p>
<p>Or you can check if an argument is an empty string or not like:</p>
<pre><code>if [ -z "$1" ]
then
echo "No argument supplied"
fi
</code></pre>
<p>The <code>-z</code> switch will test if the expansion of <code>"$1"</code> is a null string or not. If it is a null string then the body is executed.</p> | {
"question_id": 6482377,
"question_date": "2011-06-26T05:49:21.130Z",
"question_score": 1807,
"tags": "bash|shell",
"answer_id": 6482403,
"answer_date": "2011-06-26T05:55:41.863Z",
"answer_score": 3056
} |
Please answer the following Stack Overflow question:
Title: How do we control web page caching, across all browsers?
<p>Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.</p>
<p>For security reasons we do not want certain pages in our application to be cached, <strong>ever,</strong> by the web browser. This must work for at least the following browsers:</p>
<ul>
<li>Internet Explorer 6+</li>
<li>Firefox 1.5+</li>
<li>Safari 3+</li>
<li>Opera 9+</li>
<li>Chrome</li>
</ul>
<p>Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.</p> | <h1>Introduction</h1>
<p>The correct minimum set of headers that works across all mentioned clients (and proxies):</p>
<pre><code>Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
</code></pre>
<p>The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" rel="noreferrer"><code>Cache-Control</code></a> is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to <code>Expires</code>). The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32" rel="noreferrer"><code>Pragma</code></a> is per the HTTP 1.0 spec for prehistoric clients. The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21" rel="noreferrer"><code>Expires</code></a> is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the <code>Cache-Control</code> takes precedence over <code>Expires</code>, so it's after all for HTTP 1.0 proxies only.</p>
<p>If you don't care about IE6 and its broken caching when serving pages over HTTPS with only <code>no-store</code>, then you could omit <code>Cache-Control: no-cache</code>.</p>
<pre><code>Cache-Control: no-store, must-revalidate
Pragma: no-cache
Expires: 0
</code></pre>
<p>If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit <code>Pragma</code>.</p>
<pre><code>Cache-Control: no-store, must-revalidate
Expires: 0
</code></pre>
<p>If you don't care about HTTP 1.0 proxies either, then you could omit <code>Expires</code>.</p>
<pre><code>Cache-Control: no-store, must-revalidate
</code></pre>
<p>On the other hand, if the server auto-includes a valid <code>Date</code> header, then you could theoretically omit <code>Cache-Control</code> too and rely on <code>Expires</code> only.</p>
<pre><code>Date: Wed, 24 Aug 2016 18:32:02 GMT
Expires: 0
</code></pre>
<p>But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it.</p>
<p>Other <code>Cache-Control</code> parameters such as <code>max-age</code> are irrelevant if the abovementioned <code>Cache-Control</code> parameters are specified. The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29" rel="noreferrer"><code>Last-Modified</code></a> header as included in most other answers here is <em>only</em> interesting if you <strong>actually want</strong> to cache the request, so you don't need to specify it at all.</p>
<h1>How to set it?</h1>
<p>Using PHP:</p>
<pre class="lang-php prettyprint-override"><code>header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
</code></pre>
<p>Using Java Servlet, or Node.js:</p>
<pre class="lang-java prettyprint-override"><code>response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
</code></pre>
<p>Using ASP.NET-MVC</p>
<pre class="lang-cs prettyprint-override"><code>Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
</code></pre>
<p>Using ASP.NET Web API:</p>
<pre class="lang-cs prettyprint-override"><code>// `response` is an instance of System.Net.Http.HttpResponseMessage
response.Headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
response.Headers.Pragma.ParseAdd("no-cache");
// We can't use `response.Content.Headers.Expires` directly
// since it allows only `DateTimeOffset?` values.
response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString());
</code></pre>
<p>Using ASP.NET:</p>
<pre class="lang-cs prettyprint-override"><code>Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
</code></pre>
<p>Using ASP.NET Core v3</p>
<pre class="lang-c# prettyprint-override"><code>// using Microsoft.Net.Http.Headers
Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
Response.Headers[HeaderNames.Expires] = "0";
Response.Headers[HeaderNames.Pragma] = "no-cache";
</code></pre>
<p>Using ASP:</p>
<pre class="lang-vb prettyprint-override"><code>Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response.addHeader "Expires", "0" ' Proxies.
</code></pre>
<p>Using Ruby on Rails:</p>
<pre class="lang-ruby prettyprint-override"><code>headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
headers["Pragma"] = "no-cache" # HTTP 1.0.
headers["Expires"] = "0" # Proxies.
</code></pre>
<p>Using Python/Flask:</p>
<pre class="lang-python prettyprint-override"><code>response = make_response(render_template(...))
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response.headers["Pragma"] = "no-cache" # HTTP 1.0.
response.headers["Expires"] = "0" # Proxies.
</code></pre>
<p>Using Python/Django:</p>
<pre class="lang-python prettyprint-override"><code>response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
</code></pre>
<p>Using Python/Pyramid:</p>
<pre class="lang-python prettyprint-override"><code>request.response.headerlist.extend(
(
('Cache-Control', 'no-cache, no-store, must-revalidate'),
('Pragma', 'no-cache'),
('Expires', '0')
)
)
</code></pre>
<p>Using Go:</p>
<pre class="lang-default prettyprint-override"><code>responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter.Header().Set("Expires", "0") // Proxies.
</code></pre>
<p>Using Clojure (require Ring utils):</p>
<pre class="lang-clj prettyprint-override"><code>(require '[ring.util.response :as r])
(-> response
(r/header "Cache-Control" "no-cache, no-store, must-revalidate")
(r/header "Pragma" "no-cache")
(r/header "Expires" 0))
</code></pre>
<p>Using Apache <code>.htaccess</code> file:</p>
<pre class="lang-xml prettyprint-override"><code><IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
</code></pre>
<p>Using HTML:</p>
<pre class="lang-html prettyprint-override"><code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code></pre>
<h1>HTML meta tags vs HTTP response headers</h1>
<p>Important to know is that when an HTML page is served over an HTTP connection, and a header is present in <strong>both</strong> the HTTP response headers and the HTML <code><meta http-equiv></code> tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a <code>file://</code> URL. See also <a href="http://www.w3.org/TR/html4/charset.html#h-5.2.2" rel="noreferrer">W3 HTML spec chapter 5.2.2</a>. Take care with this when you don't specify them programmatically because the webserver can namely include some default values.</p>
<p>Generally, you'd better just <strong>not</strong> specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those <code><meta http-equiv></code> tags are <a href="http://validator.w3.org" rel="noreferrer"><strong>invalid</strong></a> in HTML5. Only the <code>http-equiv</code> values listed in <a href="http://w3c.github.io/html/document-metadata.html#pragma-directives" rel="noreferrer">HTML5 specification</a> are allowed.</p>
<h1>Verifying the actual HTTP response headers</h1>
<p>To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The <a href="https://i.stack.imgur.com/fSnXH.png" rel="noreferrer">below screenshot</a> is from Chrome:</p>
<p><img src="https://i.stack.imgur.com/fSnXH.png" alt="Chrome developer toolset HTTP traffic monitor showing HTTP response headers on stackoverflow.com" /></p>
<h1>I want to set those headers on file downloads too</h1>
<p>First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see <a href="https://stackoverflow.com/q/5034454">IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found</a>.</p> | {
"question_id": 49547,
"question_date": "2008-09-08T12:08:49.213Z",
"question_score": 1803,
"tags": "http|caching|https|http-headers|cross-browser",
"answer_id": 2068407,
"answer_date": "2010-01-14T23:50:18.593Z",
"answer_score": 3000
} |
Please answer the following Stack Overflow question:
Title: Vanilla JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
<p>With jQuery, we all know the wonderful <code>.ready()</code> function:</p>
<pre><code>$('document').ready(function(){});
</code></pre>
<p>However, let's say I want to run a function that is written in standard JavaScript with no library backing it, and that I want to launch a function as soon as the page is ready to handle it. What's the proper way to approach this?</p>
<p>I know I can do:</p>
<pre class="lang-js prettyprint-override"><code>window.onload="myFunction()";
</code></pre>
<p>Or I can use the <code>body</code> tag:</p>
<pre class="lang-html prettyprint-override"><code><body onload="myFunction()">
</code></pre>
<p>Or I can even try at the bottom of the page after everything, but the end <code>body</code> or <code>html</code> tag like:</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
myFunction();
</script>
</code></pre>
<p>What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's <code>$.ready()</code>?</p> | <p>The simplest thing to do in the absence of a framework that does all the cross-browser compatibility for you is to just put a call to your code at the end of the body. This is faster to execute than an <code>onload</code> handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.</p>
<pre><code><!doctype html>
<html>
<head>
</head>
<body>
Your HTML here
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
})();
</script>
</body>
</html>
</code></pre>
<hr>
<p>For modern browsers (anything from IE9 and newer and any version of Chrome, Firefox or Safari), if you want to be able to implement a jQuery like <code>$(document).ready()</code> method that you can call from anywhere (without worrying about where the calling script is positioned), you can just use something like this:</p>
<pre><code>function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" || document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
</code></pre>
<p>Usage:</p>
<pre><code>docReady(function() {
// DOM is loaded and ready for manipulation here
});
</code></pre>
<hr>
<p>If you need full cross browser compatibility (including old versions of IE) and you don't want to wait for <code>window.onload</code>, then you probably should go look at how a framework like jQuery implements its <code>$(document).ready()</code> method. It's fairly involved depending upon the capabilities of the browser.</p>
<p>To give you a little idea what jQuery does (which will work wherever the script tag is placed).</p>
<p>If supported, it tries the standard:</p>
<pre><code>document.addEventListener('DOMContentLoaded', fn, false);
</code></pre>
<p>with a fallback to:</p>
<pre><code>window.addEventListener('load', fn, false )
</code></pre>
<p>or for older versions of IE, it uses:</p>
<pre><code>document.attachEvent("onreadystatechange", fn);
</code></pre>
<p>with a fallback to:</p>
<pre><code>window.attachEvent("onload", fn);
</code></pre>
<p>And, there are some work-arounds in the IE code path that I don't quite follow, but it looks like it has something to do with frames.</p>
<hr>
<p>Here is a full substitute for jQuery's <code>.ready()</code> written in plain javascript:</p>
<pre><code>(function(funcName, baseObj) {
// The public function name defaults to window.docReady
// but you can pass in your own object and own function name and those will be used
// if you want to put them in a different namespace
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);
</code></pre>
<p>The latest version of the code is shared publicly on GitHub at <a href="https://github.com/jfriend00/docReady" rel="noreferrer">https://github.com/jfriend00/docReady</a></p>
<p>Usage:</p>
<pre><code>// pass a function reference
docReady(fn);
// use an anonymous function
docReady(function() {
// code here
});
// pass a function reference and a context
// the context will be passed to the function as the first argument
docReady(fn, context);
// use an anonymous function with a context
docReady(function(context) {
// code here that can use the context argument that was passed to docReady
}, ctx);
</code></pre>
<hr>
<p>This has been tested in:</p>
<pre class="lang-none prettyprint-override"><code>IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safari 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices
</code></pre>
<p>Working implementation and test bed: <a href="http://jsfiddle.net/jfriend00/YfD3C/" rel="noreferrer">http://jsfiddle.net/jfriend00/YfD3C/</a></p>
<hr>
<p>Here's a summary of how it works:</p>
<ol>
<li>Create an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="noreferrer">IIFE</a> (immediately invoked function expression) so we can have non-public state variables.</li>
<li>Declare a public function <code>docReady(fn, context)</code></li>
<li>When <code>docReady(fn, context)</code> is called, check if the ready handler has already fired. If so, just schedule the newly added callback to fire right after this thread of JS finishes with <code>setTimeout(fn, 1)</code>.</li>
<li>If the ready handler has not already fired, then add this new callback to the list of callbacks to be called later.</li>
<li>Check if the document is already ready. If so, execute all ready handlers.</li>
<li>If we haven't installed event listeners yet to know when the document becomes ready, then install them now.</li>
<li>If <code>document.addEventListener</code> exists, then install event handlers using <code>.addEventListener()</code> for both <code>"DOMContentLoaded"</code> and <code>"load"</code> events. The "load" is a backup event for safety and should not be needed.</li>
<li>If <code>document.addEventListener</code> doesn't exist, then install event handlers using <code>.attachEvent()</code> for <code>"onreadystatechange"</code> and <code>"onload"</code> events.</li>
<li>In the <code>onreadystatechange</code> event, check to see if the <code>document.readyState === "complete"</code> and if so, call a function to fire all the ready handlers.</li>
<li>In all the other event handlers, call a function to fire all the ready handlers.</li>
<li>In the function to call all the ready handlers, check a state variable to see if we've already fired. If we have, do nothing. If we haven't yet been called, then loop through the array of ready functions and call each one in the order they were added. Set a flag to indicate these have all been called so they are never executed more than once.</li>
<li>Clear the function array so any closures they might be using can be freed.</li>
</ol>
<p>Handlers registered with <code>docReady()</code> are guaranteed to be fired in the order they were registered.</p>
<p>If you call <code>docReady(fn)</code> after the document is already ready, the callback will be scheduled to execute as soon as the current thread of execution completes using <code>setTimeout(fn, 1)</code>. This allows the calling code to always assume they are async callbacks that will be called later, even if later is as soon as the current thread of JS finishes and it preserves calling order.</p> | {
"question_id": 9899372,
"question_date": "2012-03-27T23:57:21.543Z",
"question_score": 1802,
"tags": "javascript|jquery|html",
"answer_id": 9899701,
"answer_date": "2012-03-28T00:46:22.690Z",
"answer_score": 2526
} |
Please answer the following Stack Overflow question:
Title: How to query MongoDB with "like"
<p>I want to query something with SQL's <code>like</code> query:</p>
<pre><code>SELECT * FROM users WHERE name LIKE '%m%'
</code></pre>
<p>How can I achieve the same in MongoDB? I can't find an operator for <code>like</code> in <a href="http://www.mongodb.org/display/DOCS/Advanced+Queries" rel="noreferrer">the documentation</a>.</p> | <p>That would have to be:</p>
<pre><code>db.users.find({"name": /.*m.*/})
</code></pre>
<p>Or, similar:</p>
<pre><code>db.users.find({"name": /m/})
</code></pre>
<p>You're looking for something that contains "m" somewhere (SQL's '<code>%</code>' operator is equivalent to regular expressions' '<code>.*</code>'), not something that has "m" anchored to the beginning of the string.</p>
<p><strong>Note:</strong> MongoDB uses regular expressions which are more powerful than "LIKE" in SQL. With regular expressions you can create any pattern that you imagine.</p>
<p>For more information on regular expressions, refer to <em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" rel="noreferrer">Regular expressions</a></em> (MDN).</p> | {
"question_id": 3305561,
"question_date": "2010-07-22T03:19:21.683Z",
"question_score": 1798,
"tags": "sql|mongodb|mongodb-query|sql-like",
"answer_id": 3305687,
"answer_date": "2010-07-22T03:57:50.930Z",
"answer_score": 2396
} |
Please answer the following Stack Overflow question:
Title: Resolve Git merge conflicts in favor of their changes during a pull
<p>How do I resolve a git merge conflict in favor of pulled changes?</p>
<p>I want to remove all conflicting changes from a working tree without having to go through all of the conflicts with <code>git mergetool</code>, while keeping all conflict-free changes. Preferably, I want to do this while pulling, not afterwards.</p> | <pre><code>git pull -s recursive -X theirs <remoterepo or other repo>
</code></pre>
<p>Or, simply, for the default repository:</p>
<pre><code>git pull -X theirs
</code></pre>
<p><a href="http://stackoverflow.com/a/33569970/93540">If you're already in conflicted state...</a></p>
<pre><code>git checkout --theirs path/to/file
</code></pre> | {
"question_id": 10697463,
"question_date": "2012-05-22T07:18:07.833Z",
"question_score": 1798,
"tags": "git|git-merge|git-merge-conflict",
"answer_id": 21777677,
"answer_date": "2014-02-14T11:06:57.187Z",
"answer_score": 1968
} |
Please answer the following Stack Overflow question:
Title: Where should I put <script> tags in HTML markup?
<p>When embedding JavaScript in an HTML document, where is the proper place to put the <code><script></code> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <code><head></code> section, but placing at the beginning of the <code><body></code> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the <em>end</em> of the <code><body></code> section as a logical place for <code><script></code> tags.</p>
<p>So, where <em>is</em> the right place to put the <code><script></code> tags?</p>
<p>(This question references <a href="https://stackoverflow.com/questions/436154/why-does-the-call-to-this-jquery-function-fail-in-firefox">this question</a>, in which it was suggested that JavaScript function calls should be moved from <code><a></code> tags to <code><script></code> tags. I'm specifically using jQuery, but more general answers are also appropriate.)</p> | <p>Here's what happens when a browser loads a website with a <code><script></code> tag on it:</p>
<ol>
<li>Fetch the HTML page (e.g. <em>index.html</em>)</li>
<li>Begin parsing the HTML</li>
<li>The parser encounters a <code><script></code> tag referencing an external script file.</li>
<li>The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.</li>
<li>After some time the script is downloaded and subsequently executed.</li>
<li>The parser continues parsing the rest of the HTML document.</li>
</ol>
<p>Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.</p>
<h2>Why does this even happen?</h2>
<p>Any script can insert its own HTML via <code>document.write()</code> or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script <em>could</em> have inserted its own HTML in the document.</p>
<p>However, most JavaScript developers no longer manipulate the DOM <em>while</em> the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:</p>
<pre><code><!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
</code></pre>
<p>JavaScript:</p>
<pre><code>// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
</code></pre>
<p>Because your browser does not know <em>my-script.js</em> isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.</p>
<h2>Antiquated recommendation</h2>
<p>The old approach to solving this problem was to put <code><script></code> tags at the bottom of your <code><body></code>, because this ensures the parser isn't blocked until the very end.</p>
<p>This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.</p>
<p>In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.</p>
<h2>The modern approach</h2>
<p>Today, browsers support the <code>async</code> and <code>defer</code> attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.</p>
<h3>async</h3>
<pre><code><script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>
</code></pre>
<p>Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.</p>
<p>According to <a href="http://caniuse.com/#feat=script-async" rel="noreferrer">http://caniuse.com/#feat=script-async</a>, 97.78% of all browsers support this.</p>
<h3>defer</h3>
<pre><code><script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>
</code></pre>
<p>Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.</p>
<p>Unlike async scripts, defer scripts are only executed after the entire document has been loaded.</p>
<p>According to <a href="http://caniuse.com/#feat=script-defer" rel="noreferrer">http://caniuse.com/#feat=script-defer</a>, 97.79% of all browsers support this. 98.06% support it at least partially.</p>
<p>An important note on browser compatibility: in some circumstances, Internet Explorer 9 and earlier may execute deferred scripts out of order. If you need to support those browsers, please read <a href="https://github.com/h5bp/lazyweb-requests/issues/42" rel="noreferrer">this</a> first!</p>
<p><em>(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)</em></p>
<h1>Conclusion</h1>
<p>The current state-of-the-art is to put scripts in the <code><head></code> tag and use the <code>async</code> or <code>defer</code> attributes. This allows your scripts to be downloaded ASAP without blocking your browser.</p>
<p>The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.</p>
<h2>References</h2>
<ul>
<li><a href="https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html" rel="noreferrer">async vs defer attributes</a></li>
<li><a href="https://flaviocopes.com/javascript-async-defer/" rel="noreferrer">Efficiently load JavaScript with defer and async</a></li>
<li><a href="https://developers.google.com/speed/docs/insights/BlockingJS" rel="noreferrer">Remove Render-Blocking JavaScript</a></li>
<li><a href="https://gist.github.com/jakub-g/385ee6b41085303a53ad92c7c8afd7a6#visual-representation" rel="noreferrer">Async, Defer, Modules: A Visual Cheatsheet</a></li>
</ul> | {
"question_id": 436411,
"question_date": "2009-01-12T18:15:54.570Z",
"question_score": 1795,
"tags": "javascript|html|script-tag",
"answer_id": 24070373,
"answer_date": "2014-06-05T21:20:51.447Z",
"answer_score": 2259
} |
Please answer the following Stack Overflow question:
Title: How to access the correct `this` inside a callback
<p>I have a constructor function which registers an event handler:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);</code></pre>
</div>
</div>
</p>
<p>However, I'm not able to access the <code>data</code> property of the created object inside the callback. It looks like <code>this</code> does not refer to the object that was created, but to another one.</p>
<p>I also tried to use an object method instead of an anonymous function:</p>
<pre><code>function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
</code></pre>
<p>but it exhibits the same problems.</p>
<p>How can I access the correct object?</p> | <h2>What you should know about <code>this</code></h2>
<p><code>this</code> (aka "the context") is a special keyword inside each function and its value only depends on <em>how</em> the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:</p>
<pre><code>function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
</code></pre>
<p>To learn more about <code>this</code>, have a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" rel="noreferrer">MDN documentation</a>.</p>
<hr />
<h2>How to refer to the correct <code>this</code></h2>
<h3>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a></h3>
<p>ECMAScript 6 introduced <em>arrow functions</em>, which can be thought of as lambda functions. They don't have their own <code>this</code> binding. Instead, <code>this</code> is looked up in scope just like a normal variable. That means you don't have to call <code>.bind</code>. That's not the only special behavior they have, please refer to the MDN documentation for more information.</p>
<pre><code>function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => alert(this.data));
}
</code></pre>
<h3>Don't use <code>this</code></h3>
<p>You actually don't want to access <code>this</code> in particular, but <em>the object it refers to</em>. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are <code>self</code> and <code>that</code>.</p>
<pre><code>function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on('data', function() {
alert(self.data);
});
}
</code></pre>
<p>Since <code>self</code> is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the <code>this</code> value of the callback itself.</p>
<h3>Explicitly set <code>this</code> of the callback - part 1</h3>
<p>It might look like you have no control over the value of <code>this</code> because its value is set automatically, but that is actually not the case.</p>
<p>Every function has the method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="noreferrer"><code>.bind</code> <em><sup>[docs]</sup></em></a>, which returns a new function with <code>this</code> bound to a value. The function has exactly the same behavior as the one you called <code>.bind</code> on, only that <code>this</code> was set by you. No matter how or when that function is called, <code>this</code> will always refer to the passed value.</p>
<pre><code>function MyConstructor(data, transport) {
this.data = data;
var boundFunction = (function() { // parenthesis are not necessary
alert(this.data); // but might improve readability
}).bind(this); // <- here we are calling `.bind()`
transport.on('data', boundFunction);
}
</code></pre>
<p>In this case, we are binding the callback's <code>this</code> to the value of <code>MyConstructor</code>'s <code>this</code>.</p>
<p><strong>Note:</strong> When a binding context for jQuery, use <a href="http://api.jquery.com/jQuery.proxy/" rel="noreferrer"><code>jQuery.proxy</code> <em><sup>[docs]</sup></em></a> instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.</p>
<h3>Set <code>this</code> of the callback - part 2</h3>
<p>Some functions/methods which accept callbacks also accept a value to which the callback's <code>this</code> should refer to. This is basically the same as binding it yourself, but the function/method does it for you. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>Array#map</code> <em><sup>[docs]</sup></em></a> is such a method. Its signature is:</p>
<pre><code>array.map(callback[, thisArg])
</code></pre>
<p>The first argument is the callback and the second argument is the value <code>this</code> should refer to. Here is a contrived example:</p>
<pre><code>var arr = [1, 2, 3];
var obj = {multiplier: 42};
var new_arr = arr.map(function(v) {
return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument
</code></pre>
<p><strong>Note:</strong> Whether or not you can pass a value for <code>this</code> is usually mentioned in the documentation of that function/method. For example, <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery's <code>$.ajax</code> method <em><sup>[docs]</sup></em></a> describes an option called <code>context</code>:</p>
<blockquote>
<p>This object will be made the context of all Ajax-related callbacks.</p>
</blockquote>
<hr />
<h2>Common problem: Using object methods as callbacks/event handlers</h2>
<p>Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.</p>
<p>Consider the following example:</p>
<pre><code>function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = function() {
console.log(this.data);
};
</code></pre>
<p>The function <code>this.method</code> is assigned as click event handler, but if the <code>document.body</code> is clicked, the value logged will be <code>undefined</code>, because inside the event handler, <code>this</code> refers to the <code>document.body</code>, not the instance of <code>Foo</code>.<br />
As already mentioned at the beginning, what <code>this</code> refers to depends on how the function is <strong>called</strong>, not how it is <strong>defined</strong>.<br />
If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:</p>
<pre><code>function method() {
console.log(this.data);
}
function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = method;
</code></pre>
<p><strong>The solution</strong> is the same as mentioned above: If available, use <code>.bind</code> to explicitly bind <code>this</code> to a specific value</p>
<pre><code>document.body.onclick = this.method.bind(this);
</code></pre>
<p>or explicitly call the function as a "method" of the object, by using an anonymous function as callback / event handler and assign the object (<code>this</code>) to another variable:</p>
<pre><code>var self = this;
document.body.onclick = function() {
self.method();
};
</code></pre>
<p>or use an arrow function:</p>
<pre><code>document.body.onclick = () => this.method();
</code></pre> | {
"question_id": 20279484,
"question_date": "2013-11-29T06:13:11.430Z",
"question_score": 1789,
"tags": "javascript|callback|this",
"answer_id": 20279485,
"answer_date": "2013-11-29T06:13:11.430Z",
"answer_score": 2197
} |
Please answer the following Stack Overflow question:
Title: What is ":-!!" in C code?
<p>I bumped into this strange macro code in <a href="https://github.com/torvalds/linux/blob/ff2d8b19a3a62559afba1c53360c8577a7697714/include/linux/kernel.h#L677-L682" rel="noreferrer">/usr/include/linux/kernel.h</a>:</p>
<pre><code>/* Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
</code></pre>
<p>What does <code>:-!!</code> do?</p> | <p>This is, in effect, <strong>a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build</strong>.</p>
<p>The macro is somewhat misnamed; it should be something more like <code>BUILD_BUG_OR_ZERO</code>, rather than <code>...ON_ZERO</code>. (There have been <strong><a href="http://lkml.indiana.edu/hypermail/linux/kernel/0703.1/1546.html" rel="noreferrer">occasional discussions about whether this is a confusing name</a></strong>.)</p>
<p>You should read the expression like this:</p>
<pre><code>sizeof(struct { int: -!!(e); }))
</code></pre>
<ol>
<li><p><code>(e)</code>: Compute expression <code>e</code>.</p></li>
<li><p><code>!!(e)</code>: Logically negate twice: <code>0</code> if <code>e == 0</code>; otherwise <code>1</code>.</p></li>
<li><p><code>-!!(e)</code>: Numerically negate the expression from step 2: <code>0</code> if it was <code>0</code>; otherwise <code>-1</code>.</p></li>
<li><p><code>struct{int: -!!(0);} --> struct{int: 0;}</code>: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.</p></li>
<li><p><code>struct{int: -!!(1);} --> struct{int: -1;}</code>: On the other hand, if it <em>isn't</em> zero, then it will be some negative number. Declaring any bitfield with <em>negative</em> width is a compilation error.</p></li>
</ol>
<p>So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take <code>sizeof</code> that field, so we get a <code>size_t</code> with the appropriate width (which will be zero in the case where <code>e</code> is zero).</p>
<hr/>
<p>Some people have asked: <strong>Why not just use an <code>assert</code>?</strong></p>
<p><a href="https://stackoverflow.com/a/9230305/75170">keithmo's answer</a> here has a good response:</p>
<blockquote>
<p>These macros implement a compile-time test, while assert() is a run-time test.</p>
</blockquote>
<p>Exactly right. You don't want to detect problems in your <em>kernel</em> at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.</p> | {
"question_id": 9229601,
"question_date": "2012-02-10T14:50:08.910Z",
"question_score": 1789,
"tags": "c|linux|macros|linux-kernel",
"answer_id": 9229793,
"answer_date": "2012-02-10T15:04:12.097Z",
"answer_score": 1789
} |
Please answer the following Stack Overflow question:
Title: Type Checking: typeof, GetType, or is?
<p>I've seen many people use the following code:</p>
<pre><code>Type t = typeof(obj1);
if (t == typeof(int))
// Some code here
</code></pre>
<p>But I know you could also do this:</p>
<pre><code>if (obj1.GetType() == typeof(int))
// Some code here
</code></pre>
<p>Or this:</p>
<pre><code>if (obj1 is int)
// Some code here
</code></pre>
<p>Personally, I feel the last one is the cleanest, but is there something I'm missing? Which one is the best to use, or is it personal preference?</p> | <p>All are different.</p>
<ul>
<li><code>typeof</code> takes a type name (which you specify at compile time).</li>
<li><code>GetType</code> gets the runtime type of an instance.</li>
<li><code>is</code> returns true if an instance is in the inheritance tree.</li>
</ul>
<h3>Example</h3>
<pre><code>class Animal { }
class Dog : Animal { }
void PrintTypes(Animal a) {
Console.WriteLine(a.GetType() == typeof(Animal)); // false
Console.WriteLine(a is Animal); // true
Console.WriteLine(a.GetType() == typeof(Dog)); // true
Console.WriteLine(a is Dog); // true
}
Dog spot = new Dog();
PrintTypes(spot);
</code></pre>
<hr>
<blockquote>
<p>What about <code>typeof(T)</code>? Is it also resolved at compile time?</p>
</blockquote>
<p>Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:</p>
<pre><code>string Foo<T>(T parameter) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();
Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
</code></pre> | {
"question_id": 983030,
"question_date": "2009-06-11T19:10:28.980Z",
"question_score": 1788,
"tags": "c#|types|typeof|gettype",
"answer_id": 983061,
"answer_date": "2009-06-11T19:15:50.107Z",
"answer_score": 2135
} |
Please answer the following Stack Overflow question:
Title: Sass Variable in CSS calc() function
<p>I'm trying to use the <code>calc()</code> function in a Sass stylesheet, but I'm having some issues. Here's my code:</p>
<pre><code>$body_padding: 50px
body
padding-top: $body_padding
height: calc(100% - $body_padding)
</code></pre>
<p>If I use the literal <code>50px</code> instead of my <code>body_padding</code> variable, I get exactly what I want. However, when I switch to the variable, this is the output:</p>
<pre><code>body {
padding-top: 50px;
height: calc(100% - $body_padding);
}
</code></pre>
<p>How can I get Sass to recognize that it needs to replace the variable within the <code>calc</code> function?</p> | <p><a href="https://sass-lang.com/documentation/interpolation" rel="noreferrer">Interpolate</a>:</p>
<pre><code>body
height: calc(100% - #{$body_padding})
</code></pre>
<p>For this case, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#Values" rel="noreferrer">border-box</a> would also suffice:</p>
<pre><code>body
box-sizing: border-box
height: 100%
padding-top: $body_padding
</code></pre> | {
"question_id": 17982111,
"question_date": "2013-07-31T22:30:09.207Z",
"question_score": 1788,
"tags": "css|sass|css-calc",
"answer_id": 20236515,
"answer_date": "2013-11-27T07:40:28.277Z",
"answer_score": 3362
} |
Please answer the following Stack Overflow question:
Title: Why use getters and setters/accessors?
<p>What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?</p>
<p>If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:</p>
<pre class="lang-java prettyprint-override"><code>public String foo;
</code></pre>
<p>is any worse than:</p>
<pre class="lang-java prettyprint-override"><code>private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
</code></pre>
<p>Whereas the former takes a lot less boilerplate code.</p> | <p><strong>There are actually <em>many good reasons</em> to consider using accessors</strong> rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier. </p>
<p><em>Here are the some of the reasons I am aware of:</em></p>
<ul>
<li>Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.</li>
<li>Hiding the internal representation of the property while exposing a property using an alternative representation.</li>
<li>Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.</li>
<li>Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).</li>
<li>Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.</li>
<li>Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.</li>
<li>Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.</li>
<li>Allowing the getter/setter to be passed around as lambda expressions rather than values.</li>
<li>Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.</li>
</ul> | {
"question_id": 1568091,
"question_date": "2009-10-14T18:20:56.863Z",
"question_score": 1787,
"tags": "java|oop|setter|getter|abstraction",
"answer_id": 1568230,
"answer_date": "2009-10-14T18:47:55.443Z",
"answer_score": 1169
} |
Please answer the following Stack Overflow question:
Title: How to generate a self-signed SSL certificate using OpenSSL?
<p>I'm adding HTTPS support to an embedded Linux device. I have tried to generate a self-signed certificate with these steps:</p>
<pre><code>openssl req -new > cert.csr
openssl rsa -in privkey.pem -out key.pem
openssl x509 -in cert.csr -out cert.pem -req -signkey key.pem -days 1001
cat key.pem>>cert.pem
</code></pre>
<p>This works, but I get some errors with, for example, Google Chrome:</p>
<blockquote>
<p>This is probably not the site you are looking for!<br>
The site's security certificate is not trusted!</p>
</blockquote>
<p>Am I missing something? Is this the correct way to build a self-signed certificate?</p> | <p>You can do that in one command:</p>
<pre><code>openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 365
</code></pre>
<p>You can also add <code>-nodes</code> (short for "no DES") if you don't want to protect your private key with a passphrase. Otherwise it will prompt you for "at least a 4 character" password.</p>
<p>The <code>days</code> parameter (365) you can replace with any number to affect the expiration date. It will then prompt you for things like "Country Name", but you can just hit <kbd>Enter</kbd> and accept the defaults.</p>
<p>Add <code>-subj '/CN=localhost'</code> to suppress questions about the contents of the certificate (replace <code>localhost</code> with your desired domain).</p>
<p>Self-signed certificates are not validated with any third party unless you import them to the browsers previously. If you need more security, you should use a certificate signed by a <a href="https://en.wikipedia.org/wiki/Certificate_authority" rel="noreferrer">certificate authority</a> (CA).</p> | {
"question_id": 10175812,
"question_date": "2012-04-16T14:14:42.163Z",
"question_score": 1786,
"tags": "ssl|openssl|certificate|ssl-certificate|x509certificate",
"answer_id": 10176685,
"answer_date": "2012-04-16T15:04:51.010Z",
"answer_score": 2867
} |
Please answer the following Stack Overflow question:
Title: How to check if a string "StartsWith" another string?
<p>How would I write the equivalent of C#'s <a href="http://msdn.microsoft.com/en-us/library/baketfxw.aspx" rel="noreferrer"><code>String.StartsWith</code></a> in JavaScript?</p>
<pre><code>var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
</code></pre>
<p>Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith" rel="noreferrer"><code>.startsWith</code></a> method. However, at the time of writing this update (2015) <a href="http://kangax.github.io/compat-table/es6/#test-String.prototype_methods_String.prototype.startsWith" rel="noreferrer">browser support is far from complete</a>.</p> | <p>You can use ECMAScript 6's <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith" rel="nofollow noreferrer"><code>String.prototype.startsWith()</code></a> method. It's <a href="https://caniuse.com/mdn-javascript_builtins_string_startswith" rel="nofollow noreferrer">supported in all major browsers</a>. However, if you want to use it in a browser that is unsupported you'll want to use a shim/polyfill to add it on those browsers. Creating an implementation that complies with <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.startswith" rel="nofollow noreferrer">all the details laid out in the spec</a> is a little complicated. If you want a faithful shim, use either:</p>
<ul>
<li><a href="https://github.com/mathiasbynens/String.prototype.startsWith" rel="nofollow noreferrer">Matthias Bynens's <code>String.prototype.startsWith</code> shim</a>, or</li>
<li>The <a href="https://github.com/paulmillr/es6-shim" rel="nofollow noreferrer">es6-shim</a>, which shims as much of the ES6 spec as possible, including <code>String.prototype.startsWith</code>.</li>
</ul>
<p>Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it 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>console.log("Hello World!".startsWith("He")); // true
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false</code></pre>
</div>
</div>
</p> | {
"question_id": 646628,
"question_date": "2009-03-14T20:12:51.233Z",
"question_score": 1784,
"tags": "javascript|string|startswith",
"answer_id": 646643,
"answer_date": "2009-03-14T20:19:13.077Z",
"answer_score": 1841
} |
Please answer the following Stack Overflow question:
Title: How do I check if an object has a key in JavaScript?
<p>Which is the right thing to do?</p>
<pre><code>if (myObj['key'] == undefined)
</code></pre>
<p>or</p>
<pre><code>if (myObj['key'] == null)
</code></pre>
<p>or</p>
<pre><code>if (myObj['key'])
</code></pre> | <p>Try the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in" rel="noreferrer">JavaScript <strong>in</strong> operator</a>.</p>
<pre><code>if ('key' in myObj)
</code></pre>
<p>And the inverse.</p>
<pre><code>if (!('key' in myObj))
</code></pre>
<p><strong>Be careful!</strong> The <code>in</code> operator matches all object keys, including those in the object's prototype chain.</p>
<p>Use <code>myObj.hasOwnProperty('key')</code> to check an object's own keys and will only return <code>true</code> if <code>key</code> is available on <code>myObj</code> directly:</p>
<pre><code>myObj.hasOwnProperty('key')
</code></pre>
<p>Unless you have a specific reason to use the <code>in</code> operator, using <code>myObj.hasOwnProperty('key')</code> produces the result most code is looking for.</p> | {
"question_id": 455338,
"question_date": "2009-01-18T15:42:58.593Z",
"question_score": 1782,
"tags": "javascript|object",
"answer_id": 455366,
"answer_date": "2009-01-18T16:03:00.720Z",
"answer_score": 3127
} |
Please answer the following Stack Overflow question:
Title: How do I get into a Docker container's shell?
<p>I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.</p>
<p>I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run <code>docker-compose run containername ls -la</code>, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?</p> | <p><code>docker attach</code> will let you connect to your Docker container, but this isn't really the same thing as <code>ssh</code>. If your container is running a webserver, for example, <code>docker attach</code> will probably connect you to the <em>stdout</em> of the web server process. It won't necessarily give you a shell.</p>
<p>The <code>docker exec</code> command is probably what you are looking for; this will let you run arbitrary commands inside an existing container. For example:</p>
<pre><code>docker exec -it <mycontainer> bash
</code></pre>
<p>Of course, whatever command you are running must exist in the container filesystem.</p>
<p>In the above command <code><mycontainer></code> is the name or ID of the target container. It doesn't matter whether or not you're using <code>docker compose</code>; just run <code>docker ps</code> and use either the ID (a hexadecimal string displayed in the first column) or the name (displayed in the final column). E.g., given:</p>
<pre><code>$ docker ps
d2d4a89aaee9 larsks/mini-httpd "mini_httpd -d /cont 7 days ago Up 7 days web
</code></pre>
<p>I can run:</p>
<pre><code>$ docker exec -it web ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
18: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.3/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:3/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>I could accomplish the same thing by running:</p>
<pre><code>$ docker exec -it d2d4a89aaee9 ip addr
</code></pre>
<p>Similarly, I could start a shell in the container;</p>
<pre><code>$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$
</code></pre> | {
"question_id": 30172605,
"question_date": "2015-05-11T16:12:30.830Z",
"question_score": 1781,
"tags": "docker|docker-container",
"answer_id": 30173220,
"answer_date": "2015-05-11T16:44:52.333Z",
"answer_score": 2504
} |
Please answer the following Stack Overflow question:
Title: How do you use a variable in a regular expression?
<p>I would like to create a <code>String.replaceAll()</code> method in JavaScript and I'm thinking that using a regex would be most terse way to do it. However, I can't figure out how to pass a variable in to a regex. I can do this already which will replace all the instances of <code>"B"</code> with <code>"A"</code>.</p>
<pre><code>"ABABAB".replace(/B/g, "A");
</code></pre>
<p>But I want to do something like this:</p>
<pre><code>String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
</code></pre>
<p>But obviously this will only replace the text <code>"replaceThis"</code>...so how do I pass this variable in to my regex string?</p> | <p>Instead of using the <code>/regex\d/g</code> syntax, you can construct a new <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions" rel="noreferrer">RegExp</a> object:</p>
<pre><code>var replace = "regex\\d";
var re = new RegExp(replace,"g");
</code></pre>
<p>You can dynamically create regex objects this way. Then you will do:</p>
<pre><code>"mystring1".replace(re, "newstring");
</code></pre> | {
"question_id": 494035,
"question_date": "2009-01-30T00:11:05.160Z",
"question_score": 1779,
"tags": "javascript|regex",
"answer_id": 494046,
"answer_date": "2009-01-30T00:15:40.643Z",
"answer_score": 2270
} |
Please answer the following Stack Overflow question:
Title: When to use virtual destructors?
<p>I have a solid understanding of most <code>OOP</code> theory but the one thing that confuses me a lot is virtual destructors.</p>
<p>I thought that the destructor always gets called no matter what and for every object in the chain.</p>
<p>When are you meant to make them virtual and why?</p> | <p>Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:</p>
<pre><code>class Base
{
// some virtual methods
};
class Derived : public Base
{
~Derived()
{
// Do some important cleanup
}
};
</code></pre>
<p>Here, you'll notice that I didn't declare Base's destructor to be <code>virtual</code>. Now, let's have a look at the following snippet:</p>
<pre><code>Base *b = new Derived();
// use b
delete b; // Here's the problem!
</code></pre>
<p>Since Base's destructor is not <code>virtual</code> and <code>b</code> is a <code>Base*</code> pointing to a <code>Derived</code> object, <code>delete b</code> has <a href="https://stackoverflow.com/q/2397984/20984">undefined behaviour</a>:</p>
<blockquote>
<p>[In <code>delete b</code>], if the static type of the
object to be deleted is different from its dynamic type, the static
type shall be a base class of the dynamic type of the object to be
deleted and <strong>the static type shall have a virtual destructor or the
behavior is undefined</strong>.</p>
</blockquote>
<p>In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.</p>
<p>To sum up, always make base classes' destructors <code>virtual</code> when they're meant to be manipulated polymorphically.</p>
<p>If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call <code>delete</code> on a base class pointer.</p>
<p>You can learn more about virtuality and virtual base class destructor in <a href="http://www.gotw.ca/publications/mill18.htm" rel="noreferrer">this article from Herb Sutter</a>.</p> | {
"question_id": 461203,
"question_date": "2009-01-20T12:58:21.280Z",
"question_score": 1779,
"tags": "c++|polymorphism|shared-ptr|virtual-destructor",
"answer_id": 461224,
"answer_date": "2009-01-20T13:04:58.677Z",
"answer_score": 1813
} |
Please answer the following Stack Overflow question:
Title: How to grep (search) committed code in the Git history
<p>I have deleted a file or some code in a file sometime in the past. Can I grep in the content (not in the commit messages)?</p>
<p>A very poor solution is to grep the log:</p>
<pre><code>git log -p | grep <pattern>
</code></pre>
<p>However, this doesn't return the commit hash straight away. I played around with <code>git grep</code> to no avail.</p> | <p>To search for commit <em>content</em> (i.e., actual lines of source, as opposed to commit messages and the like), you need to do:</p>
<pre><code>git grep <regexp> $(git rev-list --all)
</code></pre>
<p><code>git rev-list --all | xargs git grep <expression></code> will work if you run into an "Argument list too long" error.</p>
<p>If you want to limit the search to some subtree (for instance, "lib/util"), you will need to pass that to the <code>rev-list</code> subcommand and <code>grep</code> as well:</p>
<pre><code>git grep <regexp> $(git rev-list --all -- lib/util) -- lib/util
</code></pre>
<p>This will grep through all your commit text for <code>regexp</code>.</p>
<p>The reason for passing the path in both commands is because <code>rev-list</code> will return the revisions list where all the changes to <code>lib/util</code> happened, but also you need to pass to <code>grep</code> so that it will only search in <code>lib/util</code>.</p>
<p>Just imagine the following scenario: <code>grep</code> might find the same <code><regexp></code> on other files which are contained in the same revision returned by <code>rev-list</code> (even if there was no change to that file on that revision).</p>
<p>Here are some other useful ways of searching your source:</p>
<p>Search working tree for text matching regular expression regexp:</p>
<pre><code>git grep <regexp>
</code></pre>
<p>Search working tree for lines of text matching regular expression regexp1 or regexp2:</p>
<pre><code>git grep -e <regexp1> [--or] -e <regexp2>
</code></pre>
<p>Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only:</p>
<pre><code>git grep -l -e <regexp1> --and -e <regexp2>
</code></pre>
<p>Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2:</p>
<pre><code>git grep -l --all-match -e <regexp1> -e <regexp2>
</code></pre>
<p>Search working tree for changed lines of text matching pattern:</p>
<pre><code>git diff --unified=0 | grep <pattern>
</code></pre>
<p>Search all revisions for text matching regular expression regexp:</p>
<pre><code>git grep <regexp> $(git rev-list --all)
</code></pre>
<p>Search all revisions between rev1 and rev2 for text matching regular expression regexp:</p>
<pre><code>git grep <regexp> $(git rev-list <rev1>..<rev2>)
</code></pre> | {
"question_id": 2928584,
"question_date": "2010-05-28T11:36:06.250Z",
"question_score": 1779,
"tags": "git|grep|diff",
"answer_id": 2929502,
"answer_date": "2010-05-28T13:47:19.363Z",
"answer_score": 2313
} |
Please answer the following Stack Overflow question:
Title: How can I make a UITextField move up when the keyboard is present - on starting to edit?
<p>With the iOS SDK:</p>
<p>I have a <code>UIView</code> with <code>UITextField</code>s that bring up a keyboard. I need it to be able to:</p>
<ol>
<li><p>Allow scrolling of the contents of the <code>UIScrollView</code> to see the other text fields once the keyboard is brought up</p>
</li>
<li><p>Automatically "jump" (by scrolling up) or shortening</p>
</li>
</ol>
<p>I know that I need a <code>UIScrollView</code>. I've tried changing the class of my <code>UIView</code> to a <code>UIScrollView</code>, but I'm still unable to scroll the textboxes up or down.</p>
<p>Do I need both a <code>UIView</code> and a <code>UIScrollView</code>? Does one go inside the other?</p>
<p>What needs to be implemented in order to automatically scroll to the active text field?</p>
<p>Ideally as much of the setup of the components as possible will be done in Interface Builder. I'd like to only write code for what needs it.</p>
<p>Note: the <code>UIView</code> (or <code>UIScrollView</code>) that I'm working with is brought up by a tabbar (<code>UITabBar</code>), which needs to function as normal.</p>
<hr />
<p>I am adding the scroll bar just for when the keyboard comes up. Even though it's not needed, I feel like it provides a better interface because then the user can scroll and change textboxes, for example.</p>
<p>I've got it working where I change the frame size of the <code>UIScrollView</code> when the keyboard goes up and down. I'm simply using:</p>
<pre><code>-(void)textFieldDidBeginEditing:(UITextField *)textField {
//Keyboard becomes visible
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height - 215 + 50); // Resize
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
// Keyboard will hide
scrollView.frame = CGRectMake(scrollView.frame.origin.x,
scrollView.frame.origin.y,
scrollView.frame.size.width,
scrollView.frame.size.height + 215 - 50); // Resize
}
</code></pre>
<p>However, this doesn't automatically "move up" or center the lower text fields in the visible area, which is what I would really like.</p> | <ol>
<li><p>You will only need a <code>ScrollView</code> if the contents you have now do not fit in the iPhone screen. (If you are adding the <code>ScrollView</code> as the superview of the components just to make the <code>TextField</code> scroll up when keyboard comes up, then it's not needed.)</p></li>
<li><p>The standard way to prevent the <code>TextField</code>s from being covered by the keyboard is to move the view up/down whenever the keyboard is shown.</p></li>
</ol>
<p>Here is some sample code:</p>
<pre><code>#define kOFFSET_FOR_KEYBOARD 80.0
-(void)keyboardWillShow {
// Animate the current view out of the way
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
-(void)keyboardWillHide {
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if ([sender isEqual:mailTf])
{
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
}
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
// revert back to the normal state.
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
</code></pre> | {
"question_id": 1126726,
"question_date": "2009-07-14T17:06:07.483Z",
"question_score": 1773,
"tags": "ios|objective-c|uiscrollview|uitextfield|uikeyboard",
"answer_id": 1127025,
"answer_date": "2009-07-14T18:03:55.057Z",
"answer_score": 1066
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Promises and Observables?
<p>What is the difference between <code>Promise</code> and <code>Observable</code> in Angular?</p>
<p>An example on each would be helpful in understanding both the cases. In what scenario can we use each case?</p> | <p><strong>Promise</strong></p>
<p>A <code>Promise</code> handles a <strong>single event</strong> when an async operation completes or fails.</p>
<p>Note: There are <code>Promise</code> libraries out there that support cancellation, but ES6 <code>Promise</code> doesn't so far.</p>
<p><strong>Observable</strong></p>
<p>An <code>Observable</code> is like a <strong><code>Stream</code></strong> (in many languages) and allows to pass zero or more events where the callback is called for each event.</p>
<p>Often <code>Observable</code> is preferred over <code>Promise</code> because it provides the features of <code>Promise</code> and more. With <code>Observable</code> it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.</p>
<p><code>Observable</code> also has the advantage over <code>Promise</code> to be <strong>cancellable</strong>. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the <code>Subscription</code> of an <code>Observable</code> allows to cancel the subscription, while a <code>Promise</code> will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.</p>
<p>While a <code>Promise</code> starts immediately, an <code>Observable</code> only starts if you subscribe to it. This is why Observables are called lazy.</p>
<p>Observable provides <strong>operators</strong> like <code>map</code>, <code>forEach</code>, <code>reduce</code>, ... similar to an array</p>
<p>There are also powerful operators like <code>retry()</code>, or <code>replay()</code>, ... that are often quite handy.
<a href="https://rxjs-dev.firebaseapp.com/guide/operators" rel="noreferrer">A list of operators shipped with rxjs</a></p>
<p>Lazy execution allows to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.</p> | {
"question_id": 37364973,
"question_date": "2016-05-21T15:43:27.463Z",
"question_score": 1772,
"tags": "angular|promise|rxjs|angular-promise|angular-observable",
"answer_id": 37365955,
"answer_date": "2016-05-21T17:19:35.403Z",
"answer_score": 1952
} |
Please answer the following Stack Overflow question:
Title: How to loop through a plain JavaScript object with the objects as members
<p>How can I loop through all members in a JavaScript object, including values that are objects?</p>
<p>For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?</p>
<pre><code>var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar"
}
}
</code></pre> | <pre><code>for (var key in validation_messages) {
// skip loop if the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var obj = validation_messages[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(prop)) continue;
// your code
alert(prop + " = " + obj[prop]);
}
}
</code></pre> | {
"question_id": 921789,
"question_date": "2009-05-28T16:18:14.620Z",
"question_score": 1771,
"tags": "javascript|loops",
"answer_id": 921808,
"answer_date": "2009-05-28T16:20:58.153Z",
"answer_score": 2233
} |
Please answer the following Stack Overflow question:
Title: AddTransient, AddScoped and AddSingleton Services Differences
<p>I want to implement <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a> (DI) in ASP.NET Core. So after adding this code to <strong><code>ConfigureServices</code></strong> method, both ways work.</p>
<p>What is the difference between the <code>services.AddTransient</code> and <code>service.AddScoped</code> methods in ASP.NET Core?</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddScoped<IEmailSender, AuthMessageSender>();
}
</code></pre> | <p><strong>TL;DR</strong></p>
<blockquote>
<p>Transient objects are always different; a new instance is provided to
every controller and every service.</p>
<p>Scoped objects are the same within a request, but different across
different requests.</p>
<p>Singleton objects are the same for every object and every request.</p>
</blockquote>
<p>For more clarification, this example from <a href="https://docs.microsoft.com/dotnet/core/extensions/dependency-injection-usage" rel="noreferrer">.NET documentation</a> shows the difference:</p>
<p>To demonstrate the difference between these lifetime and registration options, consider a simple interface that represents one or more tasks as an operation with a unique identifier, <code>OperationId</code>. Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class. To make it clear which lifetime is being requested, we will create one type per lifetime option:</p>
<pre><code>using System;
namespace DependencyInjectionSample.Interfaces
{
public interface IOperation
{
Guid OperationId { get; }
}
public interface IOperationTransient : IOperation
{
}
public interface IOperationScoped : IOperation
{
}
public interface IOperationSingleton : IOperation
{
}
public interface IOperationSingletonInstance : IOperation
{
}
}
</code></pre>
<p>We implement these interfaces using a single class, <code>Operation</code>, that accepts a GUID in its constructor, or uses a new GUID if none is provided:</p>
<pre><code>using System;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Classes
{
public class Operation : IOperationTransient, IOperationScoped, IOperationSingleton, IOperationSingletonInstance
{
Guid _guid;
public Operation() : this(Guid.NewGuid())
{
}
public Operation(Guid guid)
{
_guid = guid;
}
public Guid OperationId => _guid;
}
}
</code></pre>
<p>Next, in <code>ConfigureServices</code>, each type is added to the container according to its named lifetime:</p>
<pre><code>services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();
</code></pre>
<p>Note that the <code>IOperationSingletonInstance</code> service is using a specific instance with a known ID of <code>Guid.Empty</code>, so it will be clear when this type is in use. We have also registered an <code>OperationService</code> that depends on each of the other <code>Operation</code> types, so that it will be clear within a request whether this service is getting the same instance as the controller, or a new one, for each operation type. All this service does is expose its dependencies as properties, so they can be displayed in the view.</p>
<pre><code>using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Services
{
public class OperationService
{
public IOperationTransient TransientOperation { get; }
public IOperationScoped ScopedOperation { get; }
public IOperationSingleton SingletonOperation { get; }
public IOperationSingletonInstance SingletonInstanceOperation { get; }
public OperationService(IOperationTransient transientOperation,
IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance instanceOperation)
{
TransientOperation = transientOperation;
ScopedOperation = scopedOperation;
SingletonOperation = singletonOperation;
SingletonInstanceOperation = instanceOperation;
}
}
}
</code></pre>
<p>To demonstrate the object lifetimes within and between separate individual requests to the application, the sample includes an <code>OperationsController</code> that requests each kind of <code>IOperation</code> type as well as an <code>OperationService</code>. The <code>Index</code> action then displays all of the controller’s and service’s <code>OperationId</code> values.</p>
<pre><code>using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;
namespace DependencyInjectionSample.Controllers
{
public class OperationsController : Controller
{
private readonly OperationService _operationService;
private readonly IOperationTransient _transientOperation;
private readonly IOperationScoped _scopedOperation;
private readonly IOperationSingleton _singletonOperation;
private readonly IOperationSingletonInstance _singletonInstanceOperation;
public OperationsController(OperationService operationService,
IOperationTransient transientOperation,
IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance singletonInstanceOperation)
{
_operationService = operationService;
_transientOperation = transientOperation;
_scopedOperation = scopedOperation;
_singletonOperation = singletonOperation;
_singletonInstanceOperation = singletonInstanceOperation;
}
public IActionResult Index()
{
// ViewBag contains controller-requested services
ViewBag.Transient = _transientOperation;
ViewBag.Scoped = _scopedOperation;
ViewBag.Singleton = _singletonOperation;
ViewBag.SingletonInstance = _singletonInstanceOperation;
// Operation service has its own requested services
ViewBag.Service = _operationService;
return View();
}
}
}
</code></pre>
<p>Now two separate requests are made to this controller action:</p>
<p><a href="https://i.stack.imgur.com/ilUB6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ilUB6.png" alt="First Request" /></a></p>
<p><a href="https://i.stack.imgur.com/X2QCd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X2QCd.png" alt="Second Request" /></a></p>
<p>Observe which of the <code>OperationId</code> values varies within a request, and between requests.</p>
<ul>
<li><p>Transient objects are always different; a new instance is provided to every controller and every service.</p>
</li>
<li><p>Scoped objects are the same within a request, but different across different requests</p>
</li>
<li><p>Singleton objects are the same for every object and every request (regardless of whether an instance is provided in <code>ConfigureServices</code>)</p>
</li>
</ul> | {
"question_id": 38138100,
"question_date": "2016-07-01T06:03:02.523Z",
"question_score": 1770,
"tags": "c#|asp.net-core|.net-core",
"answer_id": 38139500,
"answer_date": "2016-07-01T07:27:11.177Z",
"answer_score": 2891
} |
Please answer the following Stack Overflow question:
Title: With arrays, why is it the case that a[5] == 5[a]?
<p>As Joel points out in <a href="https://stackoverflow.blog/2008/12/18/podcast-34/">Stack Overflow podcast #34</a>, in <a href="https://rads.stackoverflow.com/amzn/click/com/0131103628" rel="noreferrer" rel="nofollow noreferrer">C Programming Language</a> (aka: K & R), there is mention of this property of arrays in C: <code>a[5] == 5[a]</code></p>
<p>Joel says that it's because of pointer arithmetic but I still don't understand. <strong>Why does <code>a[5] == 5[a]</code></strong>?</p> | <p>The C standard defines the <code>[]</code> operator as follows:</p>
<p><code>a[b] == *(a + b)</code></p>
<p>Therefore <code>a[5]</code> will evaluate to:</p>
<pre><code>*(a + 5)
</code></pre>
<p>and <code>5[a]</code> will evaluate to:</p>
<pre><code>*(5 + a)
</code></pre>
<p><code>a</code> is a pointer to the first element of the array. <code>a[5]</code> is the value that's 5 <strong>elements</strong> further from <code>a</code>, which is the same as <code>*(a + 5)</code>, and from elementary school math we know those are equal (addition is <a href="https://en.wikipedia.org/wiki/commutative" rel="noreferrer">commutative</a>).</p> | {
"question_id": 381542,
"question_date": "2008-12-19T17:01:33.177Z",
"question_score": 1769,
"tags": "c|arrays|pointers|pointer-arithmetic",
"answer_id": 381549,
"answer_date": "2008-12-19T17:04:16.697Z",
"answer_score": 2081
} |
Please answer the following Stack Overflow question:
Title: Calling the base constructor in C#
<p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p>
<p>For example, if I inherit from the Exception class I want to do something like this:</p>
<pre><code>class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
</code></pre>
<p>Basically what I want is to be able to pass the string message to the base Exception class.</p> | <p>Modify your constructor to the following so that it calls the base class constructor properly:</p>
<pre><code>public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
</code></pre>
<p>Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.</p> | {
"question_id": 12051,
"question_date": "2008-08-15T07:39:23.097Z",
"question_score": 1765,
"tags": "c#|.net|inheritance|constructor",
"answer_id": 12052,
"answer_date": "2008-08-15T07:40:22.157Z",
"answer_score": 2140
} |
Please answer the following Stack Overflow question:
Title: How does Facebook disable the browser's integrated Developer Tools?
<p>So apparently because of the recent scams, the developer tools is exploited by people to post spam and even used to "hack" accounts. Facebook has blocked the developer tools, and I can't even use the console.</p>
<p><img src="https://i.stack.imgur.com/Wiatp.png" alt="Enter image description here"></p>
<p>How did they do that?? <a href="https://stackoverflow.com/questions/7559409/disable-developer-tools">One Stack Overflow post claimed that it is not possible</a>, but Facebook has proven them wrong.</p>
<p>Just go to Facebook and open up the developer tools, type one character into the console, and this warning pops up. No matter what you put in, it will not get executed.</p>
<p>How is this possible?</p>
<p>They even blocked auto-complete in the console:</p>
<p><img src="https://i.stack.imgur.com/j0Zmx.png" alt="Enter image description here"></p> | <p>I'm a security engineer at Facebook and this is my fault. We're testing this for some users to see if it can slow down some attacks where users are tricked into pasting (malicious) JavaScript code into the browser console.</p>
<p>Just to be clear: trying to block hackers client-side is a <a href="https://stackoverflow.com/questions/7559409/disable-developer-tools">bad idea</a> in general;
this is to protect against a <a href="https://www.facebook.com/photo.php?v=956977232793" rel="noreferrer">specific social engineering attack</a>.</p>
<p>If you ended up in the test group and are annoyed by this, sorry.
I tried to make the old opt-out page (now <a href="https://www.facebook.com/selfxss" rel="noreferrer">help page</a>) as simple as possible while still being scary enough to stop at least <em>some</em> of the victims.</p>
<p>The actual code is pretty similar to <a href="https://stackoverflow.com/a/21692733">@joeldixon66's link</a>; ours is a little more complicated for no good reason.</p>
<p>Chrome wraps all console code in</p>
<pre><code>with ((console && console._commandLineAPI) || {}) {
<code goes here>
}
</code></pre>
<p>... so the site redefines <code>console._commandLineAPI</code> to throw:</p>
<pre><code>Object.defineProperty(console, '_commandLineAPI',
{ get : function() { throw 'Nooo!' } })
</code></pre>
<p>This is <a href="http://escape.alf.nu/20" rel="noreferrer">not quite enough (try it!)</a>, but that's the
main trick.</p>
<hr>
<p>Epilogue: The Chrome team decided that defeating the console from user-side JS was a bug and <a href="https://code.google.com/p/chromium/issues/detail?id=349993" rel="noreferrer">fixed the issue</a>, rendering this technique invalid. Afterwards, additional protection was added to <a href="https://code.google.com/p/chromium/issues/detail?id=345205#c21" rel="noreferrer">protect users from self-xss</a>. </p> | {
"question_id": 21692646,
"question_date": "2014-02-11T03:42:08.540Z",
"question_score": 1763,
"tags": "javascript|facebook|google-chrome-devtools",
"answer_id": 21693931,
"answer_date": "2014-02-11T05:33:16.070Z",
"answer_score": 2511
} |
Please answer the following Stack Overflow question:
Title: What does "Could not find or load main class" mean?
<p>A common problem that new Java developers experience is that their programs fail to run with the error message: <code>Could not find or load main class ...</code></p>
<p>What does this mean, what causes it, and how should you fix it?</p> | <h2>The <code>java <class-name></code> command syntax</h2>
<p>First of all, you need to understand the correct way to launch a program using the <code>java</code> (or <code>javaw</code>) command.</p>
<p>The normal syntax<sup>1</sup> is this:</p>
<pre><code> java [ <options> ] <class-name> [<arg> ...]
</code></pre>
<p>where <code><option></code> is a command line option (starting with a "-" character), <code><class-name></code> is a fully qualified Java class name, and <code><arg></code> is an arbitrary command line argument that gets passed to your application.</p>
<hr />
<p><sup>1 - There are some other syntaxes which are described near the end of this answer.</sup></p>
<p>The fully qualified name (FQN) for the class is conventionally written as you would in Java source code; e.g.</p>
<pre><code> packagename.packagename2.packagename3.ClassName
</code></pre>
<p>However some versions of the <code>java</code> command allow you to use slashes instead of periods; e.g.</p>
<pre><code> packagename/packagename2/packagename3/ClassName
</code></pre>
<p>which (confusingly) looks like a file pathname, but isn't one. Note that the term <em>fully qualified name</em> is standard Java terminology ... not something I just made up to confuse you :-)</p>
<p>Here is an example of what a <code>java</code> command should look like:</p>
<pre><code> java -Xmx100m com.acme.example.ListUsers fred joe bert
</code></pre>
<p>The above is going to cause the <code>java</code> command to do the following:</p>
<ol>
<li>Search for the compiled version of the <code>com.acme.example.ListUsers</code> class.</li>
<li>Load the class.</li>
<li>Check that the class has a <code>main</code> method with <em>signature</em>, <em>return type</em> and <em>modifiers</em> given by <code>public static void main(String[])</code>. (Note, the method argument's name is <strong>NOT</strong> part of the signature.)</li>
<li>Call that method passing it the command line arguments ("fred", "joe", "bert") as a <code>String[]</code>.</li>
</ol>
<h2>Reasons why Java cannot find the class</h2>
<p>When you get the message "Could not find or load main class ...", that means that the first step has failed. The <code>java</code> command was not able to find the class. And indeed, the "..." in the message will be the <em>fully qualified class name</em> that <code>java</code> is looking for.</p>
<p>So why might it be unable to find the class?</p>
<h2>Reason #1 - you made a mistake with the classname argument</h2>
<p>The first likely cause is that you may have provided the wrong class name. (Or ... the right class name, but in the wrong form.) Considering the example above, here are a variety of <strong>wrong ways</strong> to specify the class name:</p>
<ul>
<li><p>Example #1 - a simple class name:</p>
<pre><code>java ListUser
</code></pre>
<p>When the class is declared in a package such as <code>com.acme.example</code>, then you must use the full classname <em>including</em> the package name in the <code>java</code> command; e.g.</p>
<pre><code>java com.acme.example.ListUser
</code></pre>
</li>
<li><p>Example #2 - a filename or pathname rather than a class name:</p>
<pre><code>java ListUser.class
java com/acme/example/ListUser.class
</code></pre>
</li>
<li><p>Example #3 - a class name with the casing incorrect:</p>
<pre><code>java com.acme.example.listuser
</code></pre>
</li>
<li><p>Example #4 - a typo</p>
<pre><code>java com.acme.example.mistuser
</code></pre>
</li>
<li><p>Example #5 - a source filename (except for Java 11 or later; see below)</p>
<pre><code>java ListUser.java
</code></pre>
</li>
<li><p>Example #6 - you forgot the class name entirely</p>
<pre><code>java lots of arguments
</code></pre>
</li>
</ul>
<h2>Reason #2 - the application's classpath is incorrectly specified</h2>
<p>The second likely cause is that the class name is correct, but that the <code>java</code> command cannot find the class. To understand this, you need to understand the concept of the "classpath". This is explained <em>well</em> by the Oracle documentation:</p>
<ul>
<li><a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html" rel="noreferrer">The <code>java</code> command documentation</a></li>
<li><a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html" rel="noreferrer">Setting the Classpath</a>.</li>
<li>The Java Tutorial - <a href="http://docs.oracle.com/javase/tutorial/essential/environment/paths.html" rel="noreferrer">PATH and CLASSPATH</a></li>
</ul>
<p>So ... if you have specified the class name correctly, the next thing to check is that you have specified the classpath correctly:</p>
<ol>
<li>Read the three documents linked above. (Yes ... READ them! It is important that a Java programmer <em>understands</em> at least the basics of how the Java classpath mechanisms works.)</li>
<li>Look at command line and / or the CLASSPATH environment variable that is in effect when you run the <code>java</code> command. Check that the directory names and JAR file names are correct.</li>
<li>If there are <em>relative</em> pathnames in the classpath, check that they resolve correctly ... from the current directory that is in effect when you run the <code>java</code> command.</li>
<li>Check that the class (mentioned in the error message) can be located on the <em>effective</em> classpath.</li>
<li>Note that the classpath syntax is <em>different</em> for Windows versus Linux and Mac OS. (The classpath separator is <code>;</code> on Windows and <code>:</code> on the others. If you use the wrong separator for your platform, you won't get an explicit error message. Instead, you will get a nonexistent file or directory on the path that will be silently ignored.)</li>
</ol>
<h2>Reason #2a - the wrong directory is on the classpath</h2>
<p>When you put a directory on the classpath, it notionally corresponds to the root of the qualified name space. Classes are located in the directory structure beneath that root, <em>by mapping the fully qualified name to a pathname</em>. So for example, if "/usr/local/acme/classes" is on the class path, then when the JVM looks for a class called <code>com.acme.example.Foon</code>, it will look for a ".class" file with this pathname:</p>
<pre><code> /usr/local/acme/classes/com/acme/example/Foon.class
</code></pre>
<p>If you had put "/usr/local/acme/classes/com/acme/example" on the classpath, then the JVM wouldn't be able to find the class.</p>
<h2>Reason #2b - the subdirectory path doesn't match the FQN</h2>
<p>If your classes FQN is <code>com.acme.example.Foon</code>, then the JVM is going to look for "Foon.class" in the directory "com/acme/example":</p>
<ul>
<li><p>If your directory structure doesn't match the package naming as per the pattern above, the JVM won't find your class.</p>
</li>
<li><p>If you attempt <em>rename</em> a class by moving it, that will fail as well ... but the exception stacktrace will be different. It is liable to say something like this:</p>
<pre><code>Caused by: java.lang.NoClassDefFoundError: <path> (wrong name: <name>)
</code></pre>
<p>because the FQN in the class file doesn't match what the class loader is expecting to find.</p>
</li>
</ul>
<p>To give a concrete example, supposing that:</p>
<ul>
<li>you want to run <code>com.acme.example.Foon</code> class,</li>
<li>the full file path is <code>/usr/local/acme/classes/com/acme/example/Foon.class</code>,</li>
<li>your current working directory is <code>/usr/local/acme/classes/com/acme/example/</code>,</li>
</ul>
<p>then:</p>
<pre class="lang-bash prettyprint-override"><code># wrong, FQN is needed
java Foon
# wrong, there is no `com/acme/example` folder in the current working directory
java com.acme.example.Foon
# wrong, similar to above
java -classpath . com.acme.example.Foon
# fine; relative classpath set
java -classpath ../../.. com.acme.example.Foon
# fine; absolute classpath set
java -classpath /usr/local/acme/classes com.acme.example.Foon
</code></pre>
<p>Notes:</p>
<ul>
<li>The <code>-classpath</code> option can be shortened to <code>-cp</code> in most Java releases. Check the respective manual entries for <code>java</code>, <code>javac</code> and so on.</li>
<li>Think carefully when choosing between absolute and relative pathnames in classpaths. Remember that a relative pathname may "break" if the current directory changes.</li>
</ul>
<h2>Reason #2c - dependencies missing from the classpath</h2>
<p>The classpath needs to include all of the <em>other</em> (non-system) classes that your application depends on. (The system classes are located automatically, and you rarely need to concern yourself with this.) For the main class to load correctly, the JVM needs to find:</p>
<ul>
<li>the class itself.</li>
<li>all classes and interfaces in the superclass hierarchy (e.g. see <a href="https://stackoverflow.com/questions/42880748">Java class is present in classpath but startup fails with Error: Could not find or load main class</a>)</li>
<li>all classes and interfaces that are referred to by means of variable or variable declarations, or method call or field access expressions.</li>
</ul>
<p>(Note: the JLS and JVM specifications allow some scope for a JVM to load classes "lazily", and this can affect when a classloader exception is thrown.)</p>
<h2>Reason #3 - the class has been declared in the wrong package</h2>
<p>It occasionally happens that someone puts a source code file into the
the wrong folder in their source code tree, or they leave out the <code>package</code> declaration. If you do this in an IDE, the IDE's compiler will tell you about this immediately. Similarly if you use a decent Java build tool, the tool will run <code>javac</code> in a way that will detect the problem. However, if you build your Java code by hand, you can do it in such a way that the compiler doesn't notice the problem, and the resulting ".class" file is not in the place that you expect it to be.</p>
<h2>Still can't find the problem?</h2>
<p>There lots of things to check, and it is easy to miss something. Try adding the <code>-Xdiag</code> option to the <code>java</code> command line (as the first thing after <code>java</code>). It will output various things about class loading, and this may offer you clues as to what the real problem is.</p>
<p>Also, consider possible problems caused by copying and pasting invisible or non-ASCII characters from websites, documents and so on. And consider "homoglyphs", where two letters or symbols look the same ... but aren't.</p>
<p>You may run into this problem if you have invalid or incorrect signatures in <code>META-INF/*.SF</code>. You can try opening up the .jar in your favorite ZIP editor, and removing files from <code>META-INF</code> until all you have is your <code>MANIFEST.MF</code>. However this is NOT RECOMMENDED in general. (The invalid signature may be the result of someone having injected malware into the original signed JAR file. If you erase the invalid signature, you are in infecting your application with the malware!) The recommended approach is to get hold of JAR files with valid signatures, or rebuild them from the (authentic) original source code.</p>
<p>Finally, you can apparently run into this problem if there is a syntax error in the <code>MANIFEST.MF</code> file (see <a href="https://stackoverflow.com/a/67145190/139985">https://stackoverflow.com/a/67145190/139985</a>).</p>
<hr />
<h2>Alternative syntaxes for <code>java</code></h2>
<p>There are three alternative syntaxes for the launching Java programs using the <code>java command</code>.</p>
<ol>
<li><p>The syntax used for launching an "executable" JAR file is as follows:</p>
<pre><code>java [ <options> ] -jar <jar-file-name> [<arg> ...]
</code></pre>
<p>e.g.</p>
<pre><code>java -Xmx100m -jar /usr/local/acme-example/listuser.jar fred
</code></pre>
<p>The name of the entry-point class (i.e. <code>com.acme.example.ListUser</code>) and the classpath are specified in the MANIFEST of the JAR file.</p>
</li>
<li><p>The syntax for launching an application from a module (Java 9 and later) is as follows:</p>
<pre><code>java [ <options> ] --module <module>[/<mainclass>] [<arg> ...]
</code></pre>
<p>The name of the entrypoint class is either defined by the <code><module></code> itself, or is given by the optional <code><mainclass></code>.</p>
</li>
<li><p>From Java 11 onwards, you can use the <code>java</code> command to compile and run a single source code file using the following syntax:</p>
<pre><code>java [ <options> ] <sourcefile> [<arg> ...]
</code></pre>
<p>where <code><sourcefile></code> is (typically) a file with the suffix ".java".</p>
</li>
</ol>
<p>For more details, please refer to the official documentation for the <code>java</code> command for the Java release that you are using.</p>
<hr />
<h2>IDEs</h2>
<p>A typical Java IDE has support for running Java applications in the IDE JVM itself or in a child JVM. These are <em>generally</em> immune from this particular exception, because the IDE uses its own mechanisms to construct the runtime classpath, identify the main class and create the <code>java</code> command line.</p>
<p>However it is still possible for this exception to occur, if you do things behind the back of the IDE. For example, if you have previously set up an Application Launcher for your Java app in Eclipse, and you then moved the JAR file containing the "main" class to a different place in the file system <em>without telling Eclipse</em>, Eclipse would unwittingly launch the JVM with an incorrect classpath.</p>
<p>In short, if you get this problem in an IDE, check for things like stale IDE state, broken project references or broken launcher configurations.</p>
<p>It is also possible for an IDE to simply get confused. IDE's are hugely complicated pieces of software comprising many interacting parts. Many of these parts adopt various caching strategies in order to make the IDE as a whole responsive. These can sometimes go wrong, and one possible symptom is problems when launching applications. If you suspect this could be happening, it is worth trying other things like restarting your IDE, rebuilding the project and so on.</p>
<hr />
<h2>Other References</h2>
<ul>
<li>From the Oracle Java Tutorials - <a href="http://docs.oracle.com/javase/tutorial/getStarted/problems/index.html" rel="noreferrer">Common Problems (and Their Solutions)</a></li>
</ul> | {
"question_id": 18093928,
"question_date": "2013-08-07T03:02:46.263Z",
"question_score": 1762,
"tags": "java|class|program-entry-point",
"answer_id": 18093929,
"answer_date": "2013-08-07T03:02:46.263Z",
"answer_score": 1559
} |
Please answer the following Stack Overflow question:
Title: Redirect from an HTML page
<p>Is it possible to set up a basic HTML page to redirect to another page on load?</p> | <p>Try using:</p>
<pre><code><meta http-equiv="refresh" content="0; url=http://example.com/" />
</code></pre>
<p>Note: Place it in the <code><head></code> section.</p>
<p>Additionally for older browsers if you add a quick link in case it doesn't refresh correctly:</p>
<p><code><p><a href="http://example.com/">Redirect</a></p></code></p>
<p>Will appear as</p>
<p><a href="http://example.com/" rel="noreferrer">Redirect</a></p>
<p>This will still allow you to get to where you're going with an additional click.</p> | {
"question_id": 5411538,
"question_date": "2011-03-23T20:58:29.670Z",
"question_score": 1761,
"tags": "html|redirect|xhtml|meta|html-head",
"answer_id": 5411567,
"answer_date": "2011-03-23T21:00:25.850Z",
"answer_score": 2333
} |
Please answer the following Stack Overflow question:
Title: Generate random integers between 0 and 9
<p>How can I generate random integers between 0 and 9 (inclusive) in Python?</p>
<p>For example, <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code>, <code>7</code>, <code>8</code>, <code>9</code></p> | <p>Try <a href="https://docs.python.org/3/library/random.html#random.randrange" rel="noreferrer"><code>random.randrange</code></a>:</p>
<pre><code>from random import randrange
print(randrange(10))
</code></pre> | {
"question_id": 3996904,
"question_date": "2010-10-22T12:48:29.157Z",
"question_score": 1761,
"tags": "python|random|integer",
"answer_id": 3996930,
"answer_date": "2010-10-22T12:51:31.247Z",
"answer_score": 2482
} |
Please answer the following Stack Overflow question:
Title: Open files always in a new tab
<p>I am using Visual Studio Code 1.3.1 with the newly introduced tabs.</p>
<p>When I click on files, the first file will open in a tab. If I do not make any changes to this file, the second clicked file will open in the same tab.</p>
<p>How can I avoid this and make Visual Studio Code always open a new tab?</p> | <p>When you [single-]click a file in the left sidebar's file browser or open it from the quick open menu (<kbd>Ctrl</kbd>-<kbd>P</kbd>, type the file name, <kbd>Enter</kbd>), Visual Studio Code opens it in what's called "Preview Mode", which allows you to quickly <strong>view</strong> files.</p>
<p>Preview Mode tabs are not kept open. As soon as you go to open another file from the sidebar, the existing Preview Mode tab (if one exists) is used. You can determine if a tab is in Preview Mode, by looking at its title in the tab bar. If the title is <em>italic</em>, the tab is in preview mode.</p>
<p>To open a file for editing (i.e. don't open in Preview Mode), double-click on the file in the sidebar, or single-click it in the sidebar then double click the title of its Preview Mode tab.</p>
<p>If you want to disable Preview Mode all together, you can do so by setting <code>"workbench.editor.enablePreview": false</code> in your settings file. You can also use the <code>"workbench.editor.enablePreviewFromQuickOpen"</code> option to disable it only from the quick open menu.</p>
<p>Before you can disable Preview Mode, you'll need to open your <a href="https://code.visualstudio.com/docs/customization/userandworkspace#_settings-file-locations" rel="noreferrer">Settings File</a>.</p>
<p><strong>Pro Tip</strong>: You can use the <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette" rel="noreferrer">Command Palette</a>(shortcut Ctrl+Shift+P) to open your settings file, just enter "<code>Preferences: Open User Settings</code>"!</p>
<p>Once you've opened your settings file (<em>your</em> settings file should be located on the right), add the <code>"workbench.editor.enablePreview"</code> property, and set its value to <code>false</code>.</p>
<p>You can learn more about Visual Studio Code's "Preview Mode", <a href="https://code.visualstudio.com/docs/editor/tabs#_preview-mode" rel="noreferrer">here</a>.</p> | {
"question_id": 38713405,
"question_date": "2016-08-02T06:43:01.913Z",
"question_score": 1759,
"tags": "visual-studio-code",
"answer_id": 38723094,
"answer_date": "2016-08-02T14:22:10.533Z",
"answer_score": 3124
} |
Please answer the following Stack Overflow question:
Title: Git push requires username and password
<p>I cloned a Git repository from my GitHub account to my PC.</p>
<p>I want to work with both my PC and laptop, but with one GitHub account.</p>
<p>When I try to push to or pull from GitHub using my PC, it requires a username and password, but not when I'm using the laptop!</p>
<p>I don't want to type my username and password every time I interact with <code>origin</code>. What am I missing here?</p> | <p>A common cause is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking "Clone or download", then clicking the "Use SSH" button above the URL field and updating the URL of your origin remote like this:</p>
<pre><code>git remote set-url origin [email protected]:username/repo.git
</code></pre>
<p>You can check if you have added the remote as HTTPS or SSH using:</p>
<pre><code>git remote -v
</code></pre>
<p>This is documented at GitHub: <a href="https://help.github.com/articles/changing-a-remote-s-url/#switching-remote-urls-from-https-to-ssh" rel="noreferrer">Switching remote URLs from HTTPS to SSH</a>.</p> | {
"question_id": 6565357,
"question_date": "2011-07-03T20:25:17.440Z",
"question_score": 1758,
"tags": "git|github|git-push|git-clone|git-pull",
"answer_id": 6565661,
"answer_date": "2011-07-03T21:25:15.443Z",
"answer_score": 2384
} |
Please answer the following Stack Overflow question:
Title: Installing specific package version with pip
<p>I am trying to install version 1.2.2 of <code>MySQL_python</code>, using a fresh virtualenv created with the <code>--no-site-packages</code> option. The current version shown in PyPi is <a href="http://pypi.python.org/pypi/MySQL-python/1.2.3" rel="noreferrer">1.2.3</a>. Is there a way to install the older version? I have tried:</p>
<pre class="lang-sh prettyprint-override"><code>pip install MySQL_python==1.2.2
</code></pre>
<p>However, when installed, it still shows <code>MySQL_python-1.2.3-py2.6.egg-info</code> in the site packages. Is this a problem specific to this package, or am I doing something wrong?</p> | <p><strong>TL;DR</strong>:</p>
<ul>
<li><code>pip install -Iv</code> (i.e. <code>pip install -Iv MySQL_python==1.2.2</code>)</li>
</ul>
<hr />
<p>What these options mean:</p>
<ul>
<li><code>-I</code> stands for <code>--ignore-installed</code> which will ignore the installed packages, overwriting them.</li>
<li><code>-v</code> is for verbose. You can combine for even more verbosity (i.e. <code>-vv</code>) up to 3 times (e.g. <code>-Ivvv</code>).</li>
</ul>
<p>For more information, see <code>pip install --help</code></p>
<p>First, I see two issues with what you're trying to do. Since you already have an installed version, you should either uninstall the current existing driver or use <code>pip install -I MySQL_python==1.2.2</code></p>
<p>However, you'll soon find out that this doesn't work. If you look at pip's installation log, or if you do a <code>pip install -Iv MySQL_python==1.2.2</code> you'll find that the PyPI URL link does not work for MySQL_python v1.2.2. You can verify this here: <a href="http://pypi.python.org/pypi/MySQL-python/1.2.2" rel="noreferrer">http://pypi.python.org/pypi/MySQL-python/1.2.2</a></p>
<p>The download link 404s and the fallback URL links are re-directing infinitely due to sourceforge.net's recent upgrade and PyPI's stale URL.</p>
<p>So to properly install the driver, you can follow these steps:</p>
<pre><code>pip uninstall MySQL_python
pip install -Iv http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.2/MySQL-python-1.2.2.tar.gz/download
</code></pre> | {
"question_id": 5226311,
"question_date": "2011-03-07T22:58:13.697Z",
"question_score": 1755,
"tags": "python|mysql|pip|pypi|mysql-python",
"answer_id": 5226504,
"answer_date": "2011-03-07T23:18:53.310Z",
"answer_score": 1244
} |
Please answer the following Stack Overflow question:
Title: What does enctype='multipart/form-data' mean?
<p>What does <code>enctype='multipart/form-data'</code> mean in an HTML form and when should we use it?</p> | <p>When you make a POST request, you have to encode the data that forms the body of the request in some way.</p>
<p>HTML forms provide <a href="https://www.w3.org/html/wg/spec/association-of-controls-and-forms.html#attr-fs-enctype" rel="noreferrer">three methods of encoding</a>.</p>
<ul>
<li><code>application/x-www-form-urlencoded</code> (the default)</li>
<li><code>multipart/form-data</code></li>
<li><code>text/plain</code></li>
</ul>
<p>Work was being done on adding <a href="http://www.w3.org/TR/html-json-forms/" rel="noreferrer"><code>application/json</code></a>, but that has been abandoned.</p>
<p>(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)</p>
<p>The specifics of the formats don't matter to most developers. The important points are:</p>
<ul>
<li>Never use <code>text/plain</code>.</li>
</ul>
<p>When you are writing client-side code:</p>
<ul>
<li>use <code>multipart/form-data</code> when your form includes any <code><input type="file"></code> elements</li>
<li>otherwise you can use <code>multipart/form-data</code> or <code>application/x-www-form-urlencoded</code> but <code>application/x-www-form-urlencoded</code> will be more efficient</li>
</ul>
<p>When you are writing server-side code:</p>
<ul>
<li>Use a prewritten form handling library</li>
</ul>
<p>Most (such as Perl's <code>CGI->param</code> or the one exposed by PHP's <code>$_POST</code> superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.</p>
<p>Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is <a href="https://github.com/expressjs/body-parser" rel="noreferrer">body-parser</a> which cannot handle multipart requests (but has documentation that recommends some alternatives which can).</p>
<hr />
<p>If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.</p>
<p><code>application/x-www-form-urlencoded</code> is more or less the same as a query string on the end of the URL.</p>
<p><code>multipart/form-data</code> is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4" rel="noreferrer">HTML 4 specification</a>.</p>
<p><code>text/plain</code> is introduced by HTML 5 and is useful only for debugging — from <a href="http://www.w3.org/TR/html5/forms.html#text/plain-encoding-algorithm" rel="noreferrer">the spec</a>: <em>They are not reliably interpretable by computer</em> — and I'd argue that the others combined with tools (like <a href="https://developers.google.com/web/tools/chrome-devtools/network" rel="noreferrer">the Network Panel</a> in the developer tools of most browsers) are better for that).</p> | {
"question_id": 4526273,
"question_date": "2010-12-24T12:19:27.933Z",
"question_score": 1753,
"tags": "html|http-headers|multipartform-data",
"answer_id": 4526286,
"answer_date": "2010-12-24T12:21:56.823Z",
"answer_score": 1908
} |
Please answer the following Stack Overflow question:
Title: Turning off eslint rule for a specific line
<p>In order to turn off linting rule for a particular line in JSHint we use the following rule:</p>
<pre><code>/* jshint ignore:start*/
$scope.someVar = ConstructorFunction();
/* jshint ignore:end */
</code></pre>
<p>I have been trying to locate the equivalent of the above for eslint. </p> | <p>To disable next line:</p>
<pre><code>// eslint-disable-next-line no-use-before-define
var thing = new Thing();
</code></pre>
<p>Or use the single line syntax:</p>
<pre><code>var thing = new Thing(); // eslint-disable-line no-use-before-define
</code></pre>
<p>See the <a href="http://eslint.org/docs/user-guide/configuring.html#configuring-rules" rel="noreferrer">eslint docs</a></p> | {
"question_id": 27732209,
"question_date": "2015-01-01T15:47:47.213Z",
"question_score": 1752,
"tags": "javascript|jshint|eslint",
"answer_id": 29592334,
"answer_date": "2015-04-12T17:27:38.480Z",
"answer_score": 2743
} |
Please answer the following Stack Overflow question:
Title: Multiple "order by" in LINQ
<p>I have two tables, <code>movies</code> and <code>categories</code>, and I want to get an ordered list by <strong>categoryID</strong> first and then by <strong>Name</strong>.</p>
<p>The movie table has three columns <strong>ID, Name and CategoryID</strong>.
The category table has two columns <strong>ID and Name</strong>.</p>
<p>I tried something like the following, but it didn't work.</p>
<pre><code>var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })
</code></pre> | <p>This should work for you:</p>
<pre><code>var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)
</code></pre> | {
"question_id": 298725,
"question_date": "2008-11-18T13:34:11.770Z",
"question_score": 1751,
"tags": "linq|sql-order-by",
"answer_id": 298741,
"answer_date": "2008-11-18T13:41:32.987Z",
"answer_score": 3096
} |
Please answer the following Stack Overflow question:
Title: How do I undo 'git reset'?
<p>I want to undo this command:</p>
<pre><code>git reset HEAD~
</code></pre> | <h3>Short answer:</h3>
<pre><code>git reset 'HEAD@{1}'
</code></pre>
<h3>Long answer:</h3>
<p>Git keeps a log of all ref updates (e.g., checkout, reset, commit, merge). You can view it by typing:</p>
<pre><code>git reflog
</code></pre>
<p>Somewhere in this list is the commit that you lost. Let's say you just typed <code>git reset HEAD~</code> and want to undo it. My reflog looks like this:</p>
<pre><code>$ git reflog
3f6db14 HEAD@{0}: HEAD~: updating HEAD
d27924e HEAD@{1}: checkout: moving from d27924e0fe16776f0d0f1ee2933a0334a4787b4c
[...]
</code></pre>
<p>The first line says that <code>HEAD</code> 0 positions ago (in other words, the current position) is 3f6db14; it was obtained by resetting to <code>HEAD~</code>. The second line says that <code>HEAD</code> 1 position ago (in other words, the state before the reset) is d27924e. It was obtained by checking out a particular commit (though that's not important right now). So, to undo the reset, run <code>git reset HEAD@{1}</code> (or <code>git reset d27924e</code>).</p>
<p>If, on the other hand, you've run some other commands since then that update HEAD, the commit you want won't be at the top of the list, and you'll need to search through the <code>reflog</code>.</p>
<p>One final note: It may be easier to look at the <code>reflog</code> for the specific branch you want to un-reset, say master, rather than <code>HEAD</code>:</p>
<pre><code>$ git reflog show master
c24138b master@{0}: merge origin/master: Fast-forward
90a2bf9 master@{1}: merge origin/master: Fast-forward
[...]
</code></pre>
<p>This should have less noise it in than the general <code>HEAD reflog</code>.</p> | {
"question_id": 2510276,
"question_date": "2010-03-24T18:08:29.350Z",
"question_score": 1751,
"tags": "git",
"answer_id": 2531803,
"answer_date": "2010-03-28T03:32:52.983Z",
"answer_score": 3203
} |
Please answer the following Stack Overflow question:
Title: How do I prompt for Yes/No/Cancel input in a Linux shell script?
<p>I want to pause input in a shell script, and prompt the user for choices.<br>
The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br>
How do I accomplish this in a typical bash prompt?</p> | <p>The simplest and most widely available method to get user input at a shell prompt is the <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-read" rel="noreferrer"><code>read</code></a> command. The best way to illustrate its use is a simple demonstration:</p>
<pre><code>while true; do
read -p "Do you wish to install this program? " yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
</code></pre>
<p>Another method, <a href="https://stackoverflow.com/a/226946/9084">pointed out</a> by <a href="https://stackoverflow.com/users/28604/steven-huwig">Steven Huwig</a>, is Bash's <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-select" rel="noreferrer"><code>select</code></a> command. Here is the same example using <code>select</code>:</p>
<pre><code>echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
</code></pre>
<p>With <code>select</code> you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a <code>while true</code> loop to retry if they give invalid input.</p>
<p>Also, <a href="https://stackoverflow.com/users/7939871/l%c3%a9a-gris">Léa Gris</a> demonstrated a way to make the request language agnostic in <a href="https://stackoverflow.com/a/57739142/9084">her answer</a>. Adapting my first example to better serve multiple languages might look like this:</p>
<pre><code>set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
if [[ "$yn" =~ $noexpr ]]; then exit; fi
echo "Answer ${yesword} / ${noword}."
done
</code></pre>
<p>Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.</p>
<p>Finally, please check out the <a href="https://stackoverflow.com/a/27875395/9084">excellent answer</a> by <a href="https://stackoverflow.com/users/1765658/f-hauri">F. Hauri</a>.</p> | {
"question_id": 226703,
"question_date": "2008-10-22T17:03:22.967Z",
"question_score": 1750,
"tags": "linux|bash|shell|scripting",
"answer_id": 226724,
"answer_date": "2008-10-22T17:08:50.943Z",
"answer_score": 1927
} |
Please answer the following Stack Overflow question:
Title: How can I avoid Java code in JSP files, using JSP 2?
<p>I'm new to Java EE and I know that something like the following three lines</p>
<pre><code><%= x+1 %>
<%= request.getParameter("name") %>
<%! counter++; %>
</code></pre>
<p>is an old school way of coding and in JSP version 2 there exists a method to avoid Java code in JSP files. What are the alternative JSP 2 lines, and what is this technique called?</p> | <p>The use of <em>scriptlets</em> (those <code><% %></code> things) in <a href="https://stackoverflow.com/tags/jsp/info">JSP</a> is indeed highly discouraged since the birth of <em>taglibs</em> (like <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a>) and <a href="https://stackoverflow.com/tags/el/info">EL</a> (<a href="https://stackoverflow.com/tags/el/info">Expression Language</a>, those <code>${}</code> things) way back in 2001.</p>
<p>The major disadvantages of <em>scriptlets</em> are:</p>
<ol>
<li><strong>Reusability:</strong> you can't reuse scriptlets.</li>
<li><strong>Replaceability:</strong> you can't make scriptlets abstract.</li>
<li><strong>OO-ability:</strong> you can't make use of inheritance/composition.</li>
<li><strong>Debuggability:</strong> if scriptlet throws an exception halfway, all you get is a blank page.</li>
<li><strong>Testability:</strong> scriptlets are not unit-testable.</li>
<li><strong>Maintainability:</strong> per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.</li>
</ol>
<p><strike>Sun</strike> Oracle itself also recommends in the <a href="https://www.oracle.com/technical-resources/articles/javase/code-convention.html" rel="noreferrer">JSP coding conventions</a> to avoid use of <em>scriptlets</em> whenever the same functionality is possible by (tag) classes. Here are several cites of relevance:</p>
<blockquote>
<p>From JSP 1.2 Specification, it is highly recommended that the JSP Standard Tag Library (JSTL) be used in your web application to help <strong>reduce the need for JSP scriptlets</strong> in your pages. Pages that use JSTL are, in general, easier to read and maintain.</p>
<p>...</p>
<p>Where possible, <strong>avoid JSP scriptlets</strong> whenever tag libraries provide equivalent functionality. This makes pages easier to read and maintain, helps to separate business logic from presentation logic, and will make your pages easier to evolve into JSP 2.0-style pages (JSP 2.0 Specification supports but de-emphasizes the use of scriptlets).</p>
<p>...</p>
<p>In the spirit of adopting the model-view-controller (MVC) design pattern to reduce coupling between the presentation tier from the business logic, <strong>JSP scriptlets should not be used</strong> for writing business logic. Rather, JSP scriptlets are used if necessary to transform data (also called "value objects") returned from processing the client's requests into a proper client-ready format. Even then, this would be better done with a front controller servlet or a custom tag.</p>
</blockquote>
<hr />
<p><strong>How to replace <em>scriptlets</em> entirely depends on the sole purpose of the code/logic. More than often this code is to be placed in a fullworthy Java class:</strong></p>
<ul>
<li><p>If you want to invoke the <strong>same</strong> Java code on <em>every</em> request, less-or-more regardless of the requested page, e.g. checking if a user is logged in, then implement a <a href="https://stackoverflow.com/tags/servlet-filters/info">filter</a> and write code accordingly in <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/servlet/filter#doFilter-jakarta.servlet.ServletRequest-jakarta.servlet.ServletResponse-jakarta.servlet.FilterChain-" rel="noreferrer"><code>doFilter()</code></a> method. E.g.:</p>
<pre class="lang-java prettyprint-override"><code> public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
((HttpServletResponse) response).sendRedirect("login"); // Not logged in, redirect to login page.
} else {
chain.doFilter(request, response); // Logged in, just continue request.
}
}
</code></pre>
<p>When mapped on an appropriate <code><url-pattern></code> covering the JSP pages of interest, then you don't need to copypaste the same piece of code overall JSP pages.</p>
<hr />
</li>
<li><p>If you want to invoke some Java code to <strong>process a GET request</strong>, e.g. preloading some list from a database to display in some table, if necessary based on some query parameters, then implement a <a href="https://stackoverflow.com/tags/servlets/info">servlet</a> and write code accordingly in <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/servlet/http/httpservlet#doGet-jakarta.servlet.http.HttpServletRequest-jakarta.servlet.http.HttpServletResponse-" rel="noreferrer"><code>doGet()</code></a> method. E.g.:</p>
<pre class="lang-java prettyprint-override"><code> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Product> products = productService.list(); // Obtain all products.
request.setAttribute("products", products); // Store products in request scope.
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (SQLException e) {
throw new ServletException("Retrieving products failed!", e);
}
}
</code></pre>
<p>This way dealing with exceptions is easier. The DB is not accessed in the midst of JSP rendering, but far before the JSP is been displayed. You still have the possibility to change the response whenever the DB access throws an exception. In the above example, the default error 500 page will be displayed which you can anyway customize by an <code><error-page></code> in <code>web.xml</code>.</p>
<hr />
</li>
<li><p>If you want to invoke some Java code to <strong>process a POST request</strong>, such as gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera), then implement a <a href="https://stackoverflow.com/tags/servlets/info">servlet</a> and write code accordingly in <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/servlet/http/httpservlet#doPost-jakarta.servlet.http.HttpServletRequest-jakarta.servlet.http.HttpServletResponse-" rel="noreferrer"><code>doPost()</code></a> method. E.g.:</p>
<pre class="lang-java prettyprint-override"><code> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirect to home page.
} else {
request.setAttribute("message", "Unknown username/password. Please retry."); // Store error message in request scope.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to JSP page to redisplay login form with error.
}
}
</code></pre>
<p>This way dealing with different result page destinations is easier: redisplaying the form with validation errors in case of an error (in this particular example you can redisplay it using <code>${message}</code> in <a href="https://stackoverflow.com/tags/el/info">EL</a>), or just taking to the desired target page in case of success.</p>
<hr />
</li>
<li><p>If you want to invoke some Java code to <strong>control</strong> the execution plan and/or the destination of the request and the response, then implement a <a href="https://stackoverflow.com/tags/servlets/info">servlet</a> according to the <a href="https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/3542297#3542297">MVC's Front Controller Pattern</a>. E.g.:</p>
<pre class="lang-java prettyprint-override"><code> protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Action action = ActionFactory.getAction(request);
String view = action.execute(request, response);
if (view.equals(request.getPathInfo().substring(1)) {
request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
} else {
response.sendRedirect(view);
}
} catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
}
</code></pre>
<p>Or just adopt an MVC framework like <a href="https://stackoverflow.com/tags/jsf/info">JSF</a>, <a href="https://stackoverflow.com/tags/spring-mvc/info">Spring MVC</a>, <a href="https://stackoverflow.com/tags/wicket/info">Wicket</a>, etc so that you end up with just a JSP/Facelets page and a JavaBean class without the need for a custom servlet.</p>
<hr />
</li>
<li><p>If you want to invoke some Java code to <strong>control the flow</strong> inside a JSP page, then you need to grab an (existing) flow control taglib like <a href="https://jakarta.ee/specifications/tags/1.2/tagdocs/c/tld-summary.html" rel="noreferrer">JSTL core</a>. E.g. displaying <code>List<Product></code> in a table:</p>
<pre class="lang-html prettyprint-override"><code> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
</code></pre>
<p>With XML-style tags which fit nicely among all that HTML, the code is better readable (and thus better maintainable) than a bunch of scriptlets with various opening and closing braces (<em>"Where the heck does this closing brace belong to?"</em>). An easy aid is to configure your web application to throw an exception whenever <em>scriptlets</em> are still been used by adding the following piece to <code>web.xml</code>:</p>
<pre class="lang-xml prettyprint-override"><code> <jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
</code></pre>
<p>In <a href="https://stackoverflow.com/tags/facelets/info">Facelets</a>, the successor of JSP, which is part of the Java EE provided MVC framework <a href="https://stackoverflow.com/tags/jsf/info">JSF</a>, it is already <strong>not</strong> possible to use <em>scriptlets</em>. This way you're automatically forced to do things "the right way".</p>
<hr />
</li>
<li><p>If you want to invoke some Java code to <strong>access and display</strong> "backend" data inside a JSP page, then you need to use EL (Expression Language), those <code>${}</code> things. E.g. redisplaying submitted input values:</p>
<pre class="lang-html prettyprint-override"><code> <input type="text" name="foo" value="${param.foo}" />
</code></pre>
<p>The <code>${param.foo}</code> displays the outcome of <code>request.getParameter("foo")</code>.</p>
<hr />
</li>
<li><p>If you want to invoke some <strong>utility</strong> Java code directly in the JSP page (typically <code>public static</code> methods), then you need to define them as EL functions. There's a standard <a href="https://jakarta.ee/specifications/tags/1.2/tagdocs/fn/tld-summary.html" rel="noreferrer">functions taglib</a> in JSTL, but <a href="https://stackoverflow.com/questions/6395621/how-to-call-a-static-method-in-jsp-el">you can also easily create functions yourself</a>. Here's an example how JSTL <code>fn:escapeXml</code> is useful to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS attacks</a>.</p>
<pre class="lang-html prettyprint-override"><code> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input type="text" name="foo" value="${fn:escapeXml(param.foo)}" />
</code></pre>
<p>Note that the XSS sensitivity is in no way specifically related to Java/JSP/JSTL/EL/whatever, this problem needs to be taken into account in <strong>every</strong> web application you develop. The problem of <em>scriptlets</em> is that it provides no way of builtin preventions, at least not using the standard Java API. JSP's successor Facelets has already implicit HTML escaping, so you don't need to worry about XSS holes in Facelets.</p>
</li>
</ul>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp/2097732#2097732">What's the difference between JSP, Servlet and JSF?</a></li>
<li><a href="https://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables/3106909#3106909">How does Servlet, ServletContext, HttpSession and HttpServletRequest/Response work?</a></li>
<li><a href="https://stackoverflow.com/questions/5003142/jsp-using-mvc-and-jdbc">Basic MVC example with JSP, Servlet and JDBC</a></li>
<li><a href="https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/">Design patterns in Java web applications</a></li>
<li><a href="https://balusc.omnifaces.org/2010/01/hidden-features-of-jspservlet.html" rel="noreferrer">Hidden features of JSP/Servlet</a></li>
</ul> | {
"question_id": 3177733,
"question_date": "2010-07-05T07:24:06.987Z",
"question_score": 1749,
"tags": "java|jsp|scriptlet",
"answer_id": 3180202,
"answer_date": "2010-07-05T14:19:35.120Z",
"answer_score": 2018
} |
Please answer the following Stack Overflow question:
Title: Parse JSON in JavaScript?
<p>I want to parse a JSON string in JavaScript. The response is something like</p>
<pre><code>var response = '{"result":true,"count":1}';
</code></pre>
<p>How can I get the values <code>result</code> and <code>count</code> from this?</p> | <p>The standard way to parse JSON in JavaScript is <a href="http://msdn.microsoft.com/en-us/library/cc836466(v=vs.85).aspx" rel="noreferrer"><strong><code>JSON.parse()</code></strong></a></p>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON" rel="noreferrer"><code>JSON</code></a> API was introduced with <a href="https://en.wikipedia.org/wiki/ECMAScript#5th_Edition" rel="noreferrer">ES5</a> (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:</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 json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);</code></pre>
</div>
</div>
</p>
<hr />
<p>The only time you won't be able to use <code>JSON.parse()</code> is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">json2.js</a>, the reference implementation of JSON written by <a href="https://en.wikipedia.org/wiki/Douglas_Crockford" rel="noreferrer">Douglas Crockford</a>, the inventor of JSON. That library will provide an implementation of <code>JSON.parse()</code>.</p>
<p>When processing extremely large JSON files, <code>JSON.parse()</code> may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as <a href="http://oboejs.com/" rel="noreferrer">Oboe.js</a> and <a href="https://github.com/dscape/clarinet" rel="noreferrer">clarinet</a>, which provide streaming JSON parsing.</p>
<p>jQuery once had a <a href="https://api.jquery.com/jQuery.parseJSON/" rel="noreferrer"><code>$.parseJSON()</code></a> function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around <code>JSON.parse()</code>.</p> | {
"question_id": 4935632,
"question_date": "2011-02-08T16:34:03.600Z",
"question_score": 1744,
"tags": "javascript|json|parsing",
"answer_id": 4935684,
"answer_date": "2011-02-08T16:38:35.493Z",
"answer_score": 2033
} |
Please answer the following Stack Overflow question:
Title: Is < faster than <=?
<p>Is <code>if (a < 901)</code> faster than <code>if (a <= 900)</code>?</p>
<p>Not exactly as in this simple example, but there are slight performance changes on loop complex code. I suppose this has to do something with generated machine code in case it's even true.</p> | <p>No, it will not be faster on most architectures. You didn't specify, but on x86, all of the integral comparisons will be typically implemented in two machine instructions:</p>
<ul>
<li>A <code>test</code> or <code>cmp</code> instruction, which sets <code>EFLAGS</code></li>
<li>And a <a href="http://www.unixwiz.net/techtips/x86-jumps.html" rel="noreferrer"><code>Jcc</code> (jump) instruction</a>, depending on the comparison type (and code layout):</li>
<li><code>jne</code> - Jump if not equal --> <code>ZF = 0</code></li>
<li><code>jz</code> - Jump if zero (equal) --> <code>ZF = 1</code></li>
<li><code>jg</code> - Jump if greater --> <code>ZF = 0 and SF = OF</code></li>
<li>(etc...)</li>
</ul>
<hr />
<p><strong>Example</strong> (Edited for brevity) Compiled with <code>$ gcc -m32 -S -masm=intel test.c</code></p>
<pre class="lang-c prettyprint-override"><code> if (a < b) {
// Do something 1
}
</code></pre>
<p>Compiles to:</p>
<pre><code> mov eax, DWORD PTR [esp+24] ; a
cmp eax, DWORD PTR [esp+28] ; b
jge .L2 ; jump if a is >= b
; Do something 1
.L2:
</code></pre>
<p>And</p>
<pre class="lang-c prettyprint-override"><code> if (a <= b) {
// Do something 2
}
</code></pre>
<p>Compiles to:</p>
<pre><code> mov eax, DWORD PTR [esp+24] ; a
cmp eax, DWORD PTR [esp+28] ; b
jg .L5 ; jump if a is > b
; Do something 2
.L5:
</code></pre>
<p>So the only difference between the two is a <code>jg</code> versus a <code>jge</code> instruction. The two will take the same amount of time.</p>
<hr />
<p>I'd like to address the comment that nothing indicates that the different jump instructions take the same amount of time. This one is a little tricky to answer, but here's what I can give: In the <a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html" rel="noreferrer">Intel Instruction Set Reference</a>, they are all grouped together under one common instruction, <code>Jcc</code> (Jump if condition is met). The same grouping is made together under the <a href="http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html" rel="noreferrer">Optimization Reference Manual</a>, in Appendix C. Latency and Throughput.</p>
<blockquote>
<p><strong>Latency</strong> — The number of clock cycles that are required for the
execution core to complete the execution of all of the μops that form
an instruction.</p>
</blockquote>
<blockquote>
<p><strong>Throughput</strong> — The number of clock cycles required to
wait before the issue ports are free to accept the same instruction
again. For many instructions, the throughput of an instruction can be
significantly less than its latency</p>
</blockquote>
<p>The values for <code>Jcc</code> are:</p>
<pre class="lang-none prettyprint-override"><code> Latency Throughput
Jcc N/A 0.5
</code></pre>
<p>with the following footnote on <code>Jcc</code>:</p>
<blockquote>
<ol start="7">
<li>Selection of conditional jump instructions should be based on the recommendation of section Section 3.4.1, “Branch Prediction Optimization,” to improve the predictability of branches. When branches are predicted successfully, the latency of <code>jcc</code> is effectively zero.</li>
</ol>
</blockquote>
<p>So, nothing in the Intel docs ever treats one <code>Jcc</code> instruction any differently from the others.</p>
<p>If one thinks about the actual circuitry used to implement the instructions, one can assume that there would be simple AND/OR gates on the different bits in <code>EFLAGS</code>, to determine whether the conditions are met. There is then, no reason that an instruction testing two bits should take any more or less time than one testing only one (Ignoring gate propagation delay, which is much less than the clock period.)</p>
<hr />
<p><strong>Edit: Floating Point</strong></p>
<p>This holds true for x87 floating point as well: (Pretty much same code as above, but with <code>double</code> instead of <code>int</code>.)</p>
<pre><code> fld QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; Compare ST(0) and ST(1), and set CF, PF, ZF in EFLAGS
fstp st(0)
seta al ; Set al if above (CF=0 and ZF=0).
test al, al
je .L2
; Do something 1
.L2:
fld QWORD PTR [esp+32]
fld QWORD PTR [esp+40]
fucomip st, st(1) ; (same thing as above)
fstp st(0)
setae al ; Set al if above or equal (CF=0).
test al, al
je .L5
; Do something 2
.L5:
leave
ret
</code></pre> | {
"question_id": 12135518,
"question_date": "2012-08-27T02:10:12.910Z",
"question_score": 1739,
"tags": "c++|c|performance|assembly|relational-operators",
"answer_id": 12135533,
"answer_date": "2012-08-27T02:13:38.163Z",
"answer_score": 1813
} |
Please answer the following Stack Overflow question:
Title: Convert form data to JavaScript object with jQuery
<p>How do I convert all elements of my form to a JavaScript object? </p>
<p>I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by <code>$('#formid').serialize();</code>, nor do I want the map returned by <code>$('#formid').serializeArray();</code></p> | <p><a href="http://api.jquery.com/serializeArray/" rel="noreferrer">serializeArray</a> already does exactly that. You just need to massage the data into your required format:</p>
<pre class="lang-js prettyprint-override"><code>function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
</code></pre>
<p>Watch out for hidden fields which have the same name as real inputs as they will get overwritten.</p> | {
"question_id": 1184624,
"question_date": "2009-07-26T13:39:54.980Z",
"question_score": 1733,
"tags": "javascript|jquery|json|serialization",
"answer_id": 1186309,
"answer_date": "2009-07-27T03:38:41.260Z",
"answer_score": 1723
} |
Please answer the following Stack Overflow question:
Title: How to undo "git commit --amend" done instead of "git commit"
<p>I accidentally amended my previous commit. The commit should have been separate to keep history of the changes I made to a particular file.</p>
<p>Is there a way to undo that last commit? If I do something like <code>git reset --hard HEAD^</code>, the first commit also is undone.</p>
<p>(I have not yet pushed to any remote directories)</p> | <p>What you need to do is to create a new commit with the same details as the current <code>HEAD</code> commit, but with the parent as the previous version of <code>HEAD</code>. <code>git reset --soft</code> will move the branch pointer so that the next commit happens on top of a different commit from where the current branch head is now.</p>
<pre class="lang-bash prettyprint-override"><code># Move the current head so that it's pointing at the old commit
# Leave the index intact for redoing the commit.
# HEAD@{1} gives you "the commit that HEAD pointed at before
# it was moved to where it currently points at". Note that this is
# different from HEAD~1, which gives you "the commit that is the
# parent node of the commit that HEAD is currently pointing to."
git reset --soft HEAD@{1}
# commit the current tree using the commit details of the previous
# HEAD commit. (Note that HEAD@{1} is pointing somewhere different from the
# previous command. It's now pointing at the erroneously amended commit.)
# The -C option takes the given commit and reuses the log message and
# authorship information.
git commit -C HEAD@{1}
</code></pre> | {
"question_id": 1459150,
"question_date": "2009-09-22T09:56:19.270Z",
"question_score": 1730,
"tags": "git|commit|undo|git-amend",
"answer_id": 1459264,
"answer_date": "2009-09-22T10:23:44.350Z",
"answer_score": 3043
} |
Please answer the following Stack Overflow question:
Title: What is an undefined reference/unresolved external symbol error and how do I fix it?
<p>What are undefined reference/unresolved external symbol errors? What are common causes and how to fix/prevent them?</p> | <p>Compiling a C++ program takes place in several steps, as specified by <strong>2.2</strong> <a href="https://stackoverflow.com/a/8834196">(credits to Keith Thompson for the reference)</a>:</p>
<blockquote>
<p>The precedence among the syntax rules of translation is specified by the following phases <em>[see footnote]</em>.</p>
<ol>
<li>Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set
(introducing new-line characters for end-of-line indicators) if
necessary. <em>[SNIP]</em></li>
<li>Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to
form logical source lines. <em>[SNIP]</em></li>
<li>The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). <em>[SNIP]</em></li>
<li>Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. <em>[SNIP]</em></li>
<li>Each source character set member in a character literal or a string literal, as well as each escape sequence and universal-character-name
in a character literal or a non-raw string literal, is converted to
the corresponding member of the execution character set; <em>[SNIP]</em></li>
<li>Adjacent string literal tokens are concatenated.</li>
<li>White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. (2.7). The
resulting tokens are syntactically and semantically analyzed and
translated as a translation unit. <em>[SNIP]</em></li>
<li>Translated translation units and instantiation units are combined as follows: <em>[SNIP]</em></li>
<li><strong>All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the
current translation. All such translator output is collected into a
program image which contains information needed for execution in its
execution environment.</strong> (emphasis mine)</li>
</ol>
<p><em>[footnote]</em> Implementations must behave as if these separate phases occur, although in practice different phases might be folded together.</p>
</blockquote>
<p>The specified errors occur during this last stage of compilation, most commonly referred to as linking. It basically means that you compiled a bunch of implementation files into object files or libraries and now you want to get them to work together.</p>
<p>Say you defined symbol <code>a</code> in <code>a.cpp</code>. Now, <code>b.cpp</code> <em>declared</em> that symbol and used it. Before linking, it simply assumes that that symbol was defined <em>somewhere</em>, but it doesn't yet care where. The linking phase is responsible for finding the symbol and correctly linking it to <code>b.cpp</code> (well, actually to the object or library that uses it).</p>
<p>If you're using Microsoft Visual Studio, you'll see that projects generate <code>.lib</code> files. These contain a table of exported symbols, and a table of imported symbols. The imported symbols are resolved against the libraries you link against, and the exported symbols are provided for the libraries that use that <code>.lib</code> (if any).</p>
<p>Similar mechanisms exist for other compilers/ platforms.</p>
<p>Common error messages are <code>error LNK2001</code>, <code>error LNK1120</code>, <code>error LNK2019</code> for <strong>Microsoft Visual Studio</strong> and <code>undefined reference to</code> <em>symbolName</em> for <strong>GCC</strong>.</p>
<p>The code:</p>
<pre><code>struct X
{
virtual void foo();
};
struct Y : X
{
void foo() {}
};
struct A
{
virtual ~A() = 0;
};
struct B: A
{
virtual ~B(){}
};
extern int x;
void foo();
int main()
{
x = 0;
foo();
Y y;
B b;
}
</code></pre>
<p>will generate the following errors with <strong>GCC</strong>:</p>
<pre><code>/home/AbiSfw/ccvvuHoX.o: In function `main':
prog.cpp:(.text+0x10): undefined reference to `x'
prog.cpp:(.text+0x19): undefined reference to `foo()'
prog.cpp:(.text+0x2d): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD1Ev[B::~B()]+0xb): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD0Ev[B::~B()]+0x12): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1Y[typeinfo for Y]+0x8): undefined reference to `typeinfo for X'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1B[typeinfo for B]+0x8): undefined reference to `typeinfo for A'
collect2: ld returned 1 exit status
</code></pre>
<p>and similar errors with <strong>Microsoft Visual Studio</strong>:</p>
<pre><code>1>test2.obj : error LNK2001: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ)
1>test2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall X::foo(void)" (?foo@X@@UAEXXZ)
1>...\test2.exe : fatal error LNK1120: 4 unresolved externals
</code></pre>
<p>Common causes include:</p>
<ul>
<li><a href="https://stackoverflow.com/a/12574400">Failure to link against appropriate libraries/object files or compile implementation files</a></li>
<li><a href="https://stackoverflow.com/a/12574403">Declared and undefined variable or function.</a></li>
<li><a href="https://stackoverflow.com/a/12574407">Common issues with class-type members</a></li>
<li><a href="https://stackoverflow.com/a/12574417">Template implementations not visible.</a></li>
<li><a href="https://stackoverflow.com/a/12574420">Symbols were defined in a C program and used in C++ code.</a></li>
<li><a href="https://stackoverflow.com/a/12574423">Incorrectly importing/exporting methods/classes across modules/dll. (MSVS specific)</a></li>
<li><a href="https://stackoverflow.com/a/20358542">Circular library dependency</a></li>
<li><a href="https://stackoverflow.com/questions/5259714/undefined-reference-to-winmain16/5260237#5260237">undefined reference to `WinMain@16'</a></li>
<li><a href="https://stackoverflow.com/a/24675715">Interdependent library order</a></li>
<li><a href="https://stackoverflow.com/questions/14364362/visualstudio-project-with-multiple-sourcefiles-of-the-same-name">Multiple source files of the same name</a></li>
<li><a href="https://stackoverflow.com/a/25744263">Mistyping or not including the .lib extension when using the <code>#pragma</code> (Microsoft Visual Studio)</a></li>
<li><a href="https://stackoverflow.com/a/35891188">Problems with template friends</a></li>
<li><a href="https://stackoverflow.com/a/36475406">Inconsistent <code>UNICODE</code> definitions</a></li>
<li><a href="https://stackoverflow.com/a/45478255">Missing "extern" in const variable declarations/definitions (C++ only)</a></li>
<li><a href="https://stackoverflow.com/a/72328407/775806">Visual Studio Code not configured for a multiple file project</a></li>
</ul> | {
"question_id": 12573816,
"question_date": "2012-09-24T22:27:40.680Z",
"question_score": 1729,
"tags": "c++|linker-errors|undefined-reference|c++-faq|unresolved-external",
"answer_id": 12573818,
"answer_date": "2012-09-24T22:27:40.680Z",
"answer_score": 961
} |
Please answer the following Stack Overflow question:
Title: LF will be replaced by CRLF in git - What is that and is it important?
<pre><code>git init
git add .
</code></pre>
<p>Gives the following warnings for many files:</p>
<blockquote>
<p>The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in <filename>.</p>
</blockquote>
<p>What's the difference between LF and CRLF? What should I do about the warnings?</p> | <p>In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.</p>
<p>If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line</p>
<pre><code>git config core.autocrlf true
</code></pre>
<p>If you want to make an intelligent decision how git should handle this, <a href="http://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration#Formatting-and-Whitespace" rel="noreferrer">read the documentation</a> </p>
<p>Here is a snippet</p>
<blockquote>
<p><strong>Formatting and Whitespace</strong></p>
<p>Formatting and whitespace issues are some of the more frustrating and
subtle problems that many developers encounter when collaborating,
especially cross-platform. It’s very easy for patches or other
collaborated work to introduce subtle whitespace changes because
editors silently introduce them, and if your files ever touch a
Windows system, their line endings might be replaced. Git has a few
configuration options to help with these issues.</p>
<pre><code>core.autocrlf
</code></pre>
<p>If you’re programming on Windows and working with people who are not
(or vice-versa), you’ll probably run into line-ending issues at some
point. This is because Windows uses both a carriage-return character
and a linefeed character for newlines in its files, whereas Mac and
Linux systems use only the linefeed character. This is a subtle but
incredibly annoying fact of cross-platform work; many editors on
Windows silently replace existing LF-style line endings with CRLF, or
insert both line-ending characters when the user hits the enter key.</p>
<p>Git can handle this by auto-converting CRLF line endings into LF when
you add a file to the index, and vice versa when it checks out code
onto your filesystem. You can turn on this functionality with the
core.autocrlf setting. If you’re on a Windows machine, set it to true
– this converts LF endings into CRLF when you check out code:</p>
<pre><code>$ git config --global core.autocrlf true
</code></pre>
<p>If you’re on a Linux or Mac system that uses LF line endings, then you
don’t want Git to automatically convert them when you check out files;
however, if a file with CRLF endings accidentally gets introduced,
then you may want Git to fix it. You can tell Git to convert CRLF to
LF on commit but not the other way around by setting core.autocrlf to
input:</p>
<pre><code>$ git config --global core.autocrlf input
</code></pre>
<p>This setup should leave you with CRLF endings in Windows checkouts,
but LF endings on Mac and Linux systems and in the repository.</p>
<p>If you’re a Windows programmer doing a Windows-only project, then you
can turn off this functionality, recording the carriage returns in the
repository by setting the config value to false:</p>
<pre><code>$ git config --global core.autocrlf false
</code></pre>
</blockquote> | {
"question_id": 5834014,
"question_date": "2011-04-29T15:28:10.787Z",
"question_score": 1726,
"tags": "git|newline|linefeed",
"answer_id": 5834094,
"answer_date": "2011-04-29T15:34:23.513Z",
"answer_score": 2139
} |
Please answer the following Stack Overflow question:
Title: How do I perform an IF...THEN in an SQL SELECT?
<p>How do I perform an <code>IF...THEN</code> in an <code>SQL SELECT</code> statement?</p>
<p>For example:</p>
<pre><code>SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
</code></pre> | <p>The <code>CASE</code> statement is the closest to IF in SQL and is supported on all versions of SQL Server.</p>
<pre><code>SELECT CAST(
CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END AS bit) as Saleable, *
FROM Product
</code></pre>
<p>You only need to use the <code>CAST</code> operator if you want the result as a Boolean value. If you are happy with an <code>int</code>, this works:</p>
<pre><code>SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
</code></pre>
<p><code>CASE</code> statements can be embedded in other <code>CASE</code> statements and even included in aggregates.</p>
<p>SQL Server Denali (SQL Server 2012) adds the <a href="http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx" rel="noreferrer">IIF</a> statement which is also available in <a href="http://www.techonthenet.com/access/functions/advanced/iif.php" rel="noreferrer">access</a> (pointed out by <a href="https://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-an-sql-select/6769805#6769805">Martin Smith</a>):</p>
<pre><code>SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
</code></pre> | {
"question_id": 63447,
"question_date": "2008-09-15T14:34:09.337Z",
"question_score": 1722,
"tags": "sql|sql-server|tsql|if-statement|case",
"answer_id": 63480,
"answer_date": "2008-09-15T14:38:24.473Z",
"answer_score": 1979
} |
Please answer the following Stack Overflow question:
Title: Can I delete a git commit but keep the changes?
<p>In one of my development branches, I made some changes to my codebase. Before I was able to complete the features I was working on, I had to switch my current branch to master to demo some features. But just using a "git checkout master" preserved the changes I also made in my development branch, thus breaking some of the functionality in master. So what I did was commit the changes on my development branch with a commit message "temporary commit" and then checkout master for the demo.</p>
<p>Now that I'm done with the demo and back to work on my development branch, I would like to remove the "temporary commit" that I made while still preserving the changes I made. Is that possible?</p> | <p>It's as simple as this:</p>
<pre><code>git reset HEAD^
</code></pre>
<p>Note: some shells treat <code>^</code> as a special character (for example some Windows shells or <a href="http://bewatermyfriend.org/p/2016/002/" rel="noreferrer">ZSH with globbing enabled</a>), so you may have to quote <code>"HEAD^"</code> or use <code>HEAD~1</code> in those cases.</p>
<p><code>git reset</code> without a <code>--hard</code> or <code>--soft</code> moves your <code>HEAD</code> to point to the specified commit, without changing any files. <code>HEAD^</code> refers to the (first) parent commit of your current commit, which in your case is the commit before the temporary one.</p>
<p>Note that another option is to carry on as normal, and then at the next commit point instead run:</p>
<pre><code>git commit --amend [-m … etc]
</code></pre>
<p>which will instead <em>edit</em> the most recent commit, having the same effect as above.</p>
<p>Note that this (as with nearly every git answer) can cause problems if you've already pushed the bad commit to a place where someone else may have pulled it from. Try to avoid that</p> | {
"question_id": 15772134,
"question_date": "2013-04-02T18:56:15.100Z",
"question_score": 1718,
"tags": "git|undo|git-reset",
"answer_id": 15772171,
"answer_date": "2013-04-02T18:58:39.790Z",
"answer_score": 2651
} |
Please answer the following Stack Overflow question:
Title: Replacements for switch statement in Python?
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p>
<p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?</p> | <p>The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the <a href="https://www.python.org/dev/peps/pep-0634/" rel="noreferrer"><code>match</code>-<code>case</code></a> statement which provides a first-class implementation of a "switch" for Python. For example:</p>
<pre><code>def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
</code></pre>
<p>The <code>match</code>-<code>case</code> statement is considerably more powerful than this simple example.</p>
<hr />
<p>You could use a dictionary:</p>
<pre><code>def f(x):
return {
'a': 1,
'b': 2,
}[x]
</code></pre> | {
"question_id": 60208,
"question_date": "2008-09-13T00:36:30.847Z",
"question_score": 1717,
"tags": "python|switch-statement",
"answer_id": 60211,
"answer_date": "2008-09-13T00:38:24.353Z",
"answer_score": 2066
} |
Please answer the following Stack Overflow question:
Title: JavaScript post request like a form submit
<p>I'm trying to direct a browser to a different page. If I wanted a GET request, I might say</p>
<pre><code>document.location.href = 'http://example.com/q=a';
</code></pre>
<p>But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML</p>
<pre><code><form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
</code></pre>
<p>Then I would just submit the form from the DOM.</p>
<p>But really I would like JavaScript code that allows me to say</p>
<pre><code>post_to_url('http://example.com/', {'q':'a'});
</code></pre>
<p>What's the best cross browser implementation?</p>
<p><strong>Edit</strong> </p>
<p>I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a>, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.</p> | <h2>Dynamically create <code><input></code>s in a form and submit it</h2>
<pre class="lang-js prettyprint-override"><code>/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the parameters to add to the url
* @param {string} [method=post] the method to use on the form
*/
function post(path, params, method='post') {
// The rest of this code assumes you are not using a library.
// It can be made less verbose if you use one.
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
</code></pre>
<p>Example:</p>
<pre class="lang-js prettyprint-override"><code>post('/contact/', {name: 'Johnny Bravo'});
</code></pre>
<p><strong>EDIT</strong>: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the <code>hasOwnProperty</code> check to fix any inadvertent bugs.</p> | {
"question_id": 133925,
"question_date": "2008-09-25T15:15:43.510Z",
"question_score": 1717,
"tags": "javascript|forms|post|submit",
"answer_id": 133997,
"answer_date": "2008-09-25T15:28:53.073Z",
"answer_score": 2329
} |
Please answer the following Stack Overflow question:
Title: What is a lambda expression in C++11?
<p>What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction?</p>
<p>A few examples, and use cases would be useful. </p> | <h1>The problem</h1>
<p>C++ includes useful generic functions like <code>std::for_each</code> and <code>std::transform</code>, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the <a href="https://stackoverflow.com/questions/356950/c-functors-and-their-uses">functor</a> you would like to apply is unique to the particular function.</p>
<pre><code>#include <algorithm>
#include <vector>
namespace {
struct f {
void operator()(int) {
// do something
}
};
}
void func(std::vector<int>& v) {
f f;
std::for_each(v.begin(), v.end(), f);
}
</code></pre>
<p>If you only use <code>f</code> once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.</p>
<p>In C++03 you might be tempted to write something like the following, to keep the functor local:</p>
<pre><code>void func2(std::vector<int>& v) {
struct {
void operator()(int) {
// do something
}
} f;
std::for_each(v.begin(), v.end(), f);
}
</code></pre>
<p>however this is not allowed, <code>f</code> cannot be passed to a <a href="https://en.cppreference.com/w/cpp/language/function_template" rel="noreferrer">template</a> function in C++03.</p>
<h1>The new solution</h1>
<p>C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the <code>struct f</code>. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:</p>
<pre><code>void func3(std::vector<int>& v) {
std::for_each(v.begin(), v.end(), [](int) { /* do something here*/ });
}
</code></pre>
<p>Lambda functions are just syntactic sugar for anonymous functors.</p>
<h2>Return types</h2>
<p>In simple cases the return type of the lambda is deduced for you, e.g.:</p>
<pre><code>void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) { return d < 0.00001 ? 0 : d; }
);
}
</code></pre>
<p>however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.:</p>
<pre><code>void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) {
if (d < 0.0001) {
return 0;
} else {
return d;
}
});
}
</code></pre>
<p>To resolve this you are allowed to explicitly specify a return type for a lambda function, using <code>-> T</code>:</p>
<pre><code>void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) -> double {
if (d < 0.0001) {
return 0;
} else {
return d;
}
});
}
</code></pre>
<h2>"Capturing" variables</h2>
<p>So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the <code>[]</code> of the expression), which has so far been unused in these examples, e.g.:</p>
<pre><code>void func5(std::vector<double>& v, const double& epsilon) {
std::transform(v.begin(), v.end(), v.begin(),
[epsilon](double d) -> double {
if (d < epsilon) {
return 0;
} else {
return d;
}
});
}
</code></pre>
<p>You can capture by both reference and value, which you can specify using <code>&</code> and <code>=</code> respectively:</p>
<ul>
<li><code>[&epsilon, zeta]</code> captures epsilon by reference and zeta by value</li>
<li><code>[&]</code> captures all variables used in the lambda by reference</li>
<li><code>[=]</code> captures all variables used in the lambda by value</li>
<li><code>[&, epsilon]</code> captures all variables used in the lambda by reference but captures epsilon by value</li>
<li><code>[=, &epsilon]</code> captures all variables used in the lambda by value but captures epsilon by reference</li>
</ul>
<p>The generated <code>operator()</code> is <code>const</code> by default, with the implication that captures will be <code>const</code> when you access them by default. This has the effect that each call with the same input would produce the same result, however you can <a href="https://stackoverflow.com/questions/5501959/why-does-c0xs-lambda-require-mutable-keyword-for-capture-by-value-by-defaul">mark the lambda as <code>mutable</code></a> to request that the <code>operator()</code> that is produced is not <code>const</code>.</p> | {
"question_id": 7627098,
"question_date": "2011-10-02T14:58:12.723Z",
"question_score": 1716,
"tags": "c++|lambda|c++11|c++-faq",
"answer_id": 7627218,
"answer_date": "2011-10-02T15:21:05.283Z",
"answer_score": 1737
} |
Please answer the following Stack Overflow question:
Title: How do I check if an object has a specific property in JavaScript?
<p>How do I check if an object has a specific property in JavaScript?</p>
<p>Consider:</p>
<pre><code>x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
</code></pre>
<p>Is that the best way to do it?</p> | <h2>2022 UPDATE</h2>
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn" rel="noreferrer"><code>Object.hasOwn()</code></a></h2>
<blockquote>
<p><code>Object.hasOwn()</code> is recommended over <code>Object.hasOwnProperty()</code> because it works for objects created using <code>Object.create(null)</code> and with objects that have overridden the inherited <code>hasOwnProperty()</code> method. While it is possible to workaround these problems by calling <code>Object.prototype.hasOwnProperty()</code> on an external object, <code>Object.hasOwn()</code> is more intuitive.</p>
</blockquote>
<h4>Example</h4>
<pre class="lang-js prettyprint-override"><code>const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
</code></pre>
<hr />
<h2>Original answer</h2>
<p>I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to <code>typeof this[property]</code> or, even worse, <code>x.key</code> will give you completely misleading results.</p>
<p>It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then <code>object.hasOwnProperty</code> is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)</p>
<p>If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: <code>prop in object</code> will give you your desired effect.</p>
<p>Since using <code>hasOwnProperty</code> is probably what you want, and considering that you may want a fallback method, I present to you the following solution:</p>
<pre><code>var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
</code></pre>
<p>The above is a working, cross-browser, solution to <code>hasOwnProperty()</code>, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.</p> | {
"question_id": 135448,
"question_date": "2008-09-25T19:27:06.980Z",
"question_score": 1715,
"tags": "javascript",
"answer_id": 136411,
"answer_date": "2008-09-25T21:52:02.747Z",
"answer_score": 1567
} |
Please answer the following Stack Overflow question:
Title: How can I check if a string is a valid number?
<p>I'm hoping there's something in the same conceptual space as the old VB6 <code>IsNumeric()</code> function?</p> | <p><strong>2nd October 2020:</strong> note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point "<code>.</code>":</p>
<pre class="lang-js prettyprint-override"><code>function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
</code></pre>
<hr />
<h2>To check if a variable (including a string) is a number, check if it is not a number:</h2>
<p>This works regardless of whether the variable content is a string or number.</p>
<pre><code>isNaN(num) // returns true if the variable does NOT contain a valid number
</code></pre>
<h3>Examples</h3>
<pre><code>isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
</code></pre>
<p>Of course, you can negate this if you need to. For example, to implement the <code>IsNumeric</code> example you gave:</p>
<pre><code>function isNumeric(num){
return !isNaN(num)
}
</code></pre>
<h2>To convert a string containing a number into a number:</h2>
<p>Only works if the string <em>only</em> contains numeric characters, else it returns <code>NaN</code>.</p>
<pre><code>+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
</code></pre>
<h3>Examples</h3>
<pre><code>+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
</code></pre>
<h2>To convert a string loosely to a number</h2>
<p>Useful for converting '12px' to 12, for example:</p>
<pre><code>parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
</code></pre>
<h3>Examples</h3>
<pre><code>parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
</code></pre>
<h2>Floats</h2>
<p>Bear in mind that, unlike <code>+num</code>, <code>parseInt</code> (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use <code>parseInt()</code> <em>because of</em> this behaviour, <a href="https://parsebox.io/dthree/gyeveeygrngl" rel="noreferrer">you're probably better off using another method instead</a>):</p>
<pre><code>+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
</code></pre>
<h2>Empty strings</h2>
<p>Empty strings may be a little counter-intuitive. <code>+num</code> converts empty strings or strings with spaces to zero, and <code>isNaN()</code> assumes the same:</p>
<pre><code>+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
</code></pre>
<p>But <code>parseInt()</code> does not agree:</p>
<pre><code>parseInt('') // NaN
parseInt(' ') // NaN
</code></pre> | {
"question_id": 175739,
"question_date": "2008-10-06T19:12:52.413Z",
"question_score": 1714,
"tags": "javascript|validation|numeric",
"answer_id": 175787,
"answer_date": "2008-10-06T19:24:20.287Z",
"answer_score": 2981
} |
Please answer the following Stack Overflow question:
Title: How can I reconcile detached HEAD with master/origin?
<p>I'm new at the branching complexities of Git. I always work on a single branch and commit changes and then periodically push to my remote origin.</p>
<p>Somewhere recently, I did a reset of some files to get them out of commit staging, and later did a <code>rebase -i</code> to get rid of a couple recent local commits. Now I'm in a state I don't quite understand.</p>
<p>In my working area, <code>git log</code> shows exactly what I'd expect-- I'm on the right train with the commits I didn't want gone, and new ones there, etc.</p>
<p>But I just pushed to the remote repository, and what's there is different-- a couple of the commits I'd killed in the rebase got pushed, and the new ones committed locally aren't there. </p>
<p>I think "master/origin" is detached from HEAD, but I'm not 100% clear on what that means, how to visualize it with the command line tools, and how to fix it.</p> | <p>First, let’s clarify <a href="https://git-scm.com/book/en/v2/Git-Internals-Git-References" rel="noreferrer"><strong>what HEAD is</strong></a> and what it means when it is detached. </p>
<p>HEAD is the symbolic name for the currently checked out commit. When HEAD is not detached (the “normal”<sup>1</sup> situation: you have a branch checked out), HEAD actually points to a branch’s “ref” and the branch points to the commit. HEAD is thus “attached” to a branch. When you make a new commit, the branch that HEAD points to is updated to point to the new commit. HEAD follows automatically since it just points to the branch.</p>
<ul>
<li><code>git symbolic-ref HEAD</code> yields <code>refs/heads/master</code><br>
The branch named “master” is checked out.</li>
<li><code>git rev-parse refs/heads/master</code> yield <code>17a02998078923f2d62811326d130de991d1a95a</code><br>
That commit is the current tip or “head” of the master branch.</li>
<li><code>git rev-parse HEAD</code> also yields <code>17a02998078923f2d62811326d130de991d1a95a</code><br>
This is what it means to be a “symbolic ref”. It points to an object through some other reference.<br>
(Symbolic refs were originally implemented as symbolic links, but later changed to plain files with extra interpretation so that they could be used on platforms that do not have symlinks.)</li>
</ul>
<p>We have <code>HEAD</code> → <code>refs/heads/master</code> → <code>17a02998078923f2d62811326d130de991d1a95a</code></p>
<p>When HEAD is detached, it points directly to a commit—instead of indirectly pointing to one through a branch. You can think of a detached HEAD as being on an unnamed branch. </p>
<ul>
<li><code>git symbolic-ref HEAD</code> fails with <code>fatal: ref HEAD is not a symbolic ref</code></li>
<li><code>git rev-parse HEAD</code> yields <code>17a02998078923f2d62811326d130de991d1a95a</code><br>
Since it is not a symbolic ref, it must point directly to the commit itself.</li>
</ul>
<p>We have <code>HEAD</code> → <code>17a02998078923f2d62811326d130de991d1a95a</code></p>
<p>The important thing to remember with a detached HEAD is that if the commit it points to is otherwise unreferenced (no other ref can reach it), then it will become “dangling” when you checkout some other commit. Eventually, such dangling commits will be pruned through the garbage collection process (by default, they are kept for at least 2 weeks and may be kept longer by being referenced by HEAD’s reflog).</p>
<p><sup>1</sup>
It is perfectly fine to do “normal” work with a detached HEAD, you just have to keep track of what you are doing to avoid having to fish dropped history out of the reflog.</p>
<hr>
<p>The intermediate steps of an interactive rebase are done with a detached HEAD (partially to avoid polluting the active branch’s reflog). If you finish the full rebase operation, it will update your original branch with the cumulative result of the rebase operation and reattach HEAD to the original branch. My guess is that you never fully completed the rebase process; this will leave you with a detached HEAD pointing to the commit that was most recently processed by the rebase operation.</p>
<p>To recover from your situation, you should create a branch that points to the commit currently pointed to by your detached HEAD:</p>
<pre><code>git branch temp
git checkout temp
</code></pre>
<p><sub>(these two commands can be abbreviated as <code>git checkout -b temp</code>)</sub></p>
<p>This will reattach your HEAD to the new <code>temp</code> branch.</p>
<p>Next, you should compare the current commit (and its history) with the normal branch on which you expected to be working:</p>
<pre><code>git log --graph --decorate --pretty=oneline --abbrev-commit master origin/master temp
git diff master temp
git diff origin/master temp
</code></pre>
<p>(You will probably want to experiment with the log options: add <code>-p</code>, leave off <code>--pretty=…</code> to see the whole log message, etc.)</p>
<p>If your new <code>temp</code> branch looks good, you may want to update (e.g.) <code>master</code> to point to it:</p>
<pre><code>git branch -f master temp
git checkout master
</code></pre>
<p><sub>(these two commands can be abbreviated as <code>git checkout -B master temp</code>)</sub></p>
<p>You can then delete the temporary branch:</p>
<pre><code>git branch -d temp
</code></pre>
<p>Finally, you will probably want to push the reestablished history:</p>
<pre><code>git push origin master
</code></pre>
<p>You may need to add <code>--force</code> to the end of this command to push if the remote branch can not be “fast-forwarded” to the new commit (i.e. you dropped, or rewrote some existing commit, or otherwise rewrote some bit of history).</p>
<p>If you were in the middle of a rebase operation you should probably clean it up. You can check whether a rebase was in process by looking for the directory <code>.git/rebase-merge/</code>. You can manually clean up the in-progress rebase by just deleting that directory (e.g. if you no longer remember the purpose and context of the active rebase operation). Usually you would use <code>git rebase --abort</code>, but that does some extra resetting that you probably want to avoid (it moves HEAD back to the original branch and resets it back to the original commit, which will undo some of the work we did above).</p> | {
"question_id": 5772192,
"question_date": "2011-04-24T17:51:01.633Z",
"question_score": 1714,
"tags": "git",
"answer_id": 5772882,
"answer_date": "2011-04-24T19:56:33.330Z",
"answer_score": 2735
} |
Please answer the following Stack Overflow question:
Title: How do I create a Java string from the contents of a file?
<p>I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.</p>
<p>Is there a better/different way to read a file into a string in Java?</p>
<pre><code>private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
</code></pre> | <h2>Read all text from a file</h2>
<p>Java 11 added the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path,java.nio.charset.Charset)" rel="noreferrer">readString()</a> method to read small files as a <code>String</code>, preserving line terminators:</p>
<pre><code>String content = Files.readString(path, encoding);
</code></pre>
<p>For versions between Java 7 and 11, here's a compact, robust idiom, wrapped up in a utility method:</p>
<pre><code>static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
</code></pre>
<h2>Read lines of text from a file</h2>
<p>Java 7 added a <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29" rel="noreferrer">convenience method to read a file as lines of text,</a> represented as a <code>List<String></code>. This approach is "lossy" because the line separators are stripped from the end of each line.</p>
<pre><code>List<String> lines = Files.readAllLines(Paths.get(path), encoding);
</code></pre>
<p>Java 8 added the <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-" rel="noreferrer"><code>Files.lines()</code></a> method to produce a <code>Stream<String></code>. Again, this method is lossy because line separators are stripped. If an <code>IOException</code> is encountered while reading the file, it is wrapped in an <a href="https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedIOException.html" rel="noreferrer"><code>UncheckedIOException</code></a>, since <code>Stream</code> doesn't accept lambdas that throw checked exceptions.</p>
<pre><code>try (Stream<String> lines = Files.lines(path, encoding)) {
lines.forEach(System.out::println);
}
</code></pre>
<p>This <code>Stream</code> does need a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--" rel="noreferrer"><code>close()</code></a> call; this is poorly documented on the API, and I suspect many people don't even notice <code>Stream</code> has a <code>close()</code> method. Be sure to use an ARM-block as shown.</p>
<p>If you are working with a source other than a file, you can use the <a href="https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--" rel="noreferrer"><code>lines()</code></a> method in <code>BufferedReader</code> instead.</p>
<h2>Memory utilization</h2>
<p>If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.</p>
<h2>Character encoding</h2>
<p>One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.</p>
<p>The <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html" rel="noreferrer"><code>StandardCharsets</code></a> class defines some constants for the encodings required of all Java runtimes:</p>
<pre><code>String content = readFile("test.txt", StandardCharsets.UTF_8);
</code></pre>
<p>The platform default is available from <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29" rel="noreferrer">the <code>Charset</code> class</a> itself:</p>
<pre><code>String content = readFile("test.txt", Charset.defaultCharset());
</code></pre>
<p>There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.</p>
<hr />
<p>Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.</p> | {
"question_id": 326390,
"question_date": "2008-11-28T18:32:07.253Z",
"question_score": 1713,
"tags": "java|string|file|file-io|io",
"answer_id": 326440,
"answer_date": "2008-11-28T18:56:13.693Z",
"answer_score": 1782
} |
Please answer the following Stack Overflow question:
Title: How do I remove a key from a JavaScript object?
<p>Let's say we have an object with this format:</p>
<pre><code>var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
</code></pre>
<p>I wanted to do a function that removes by key:</p>
<pre><code>removeFromObjectByKey('Cow');
</code></pre> | <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete" rel="noreferrer"><code>delete</code></a> operator allows you to remove a property from an object.</p>
<p>The following examples all do the same thing.</p>
<pre><code>// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
</code></pre>
<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>let animals = {
'Cow': 'Moo',
'Cat': 'Meow',
'Dog': 'Bark'
};
delete animals.Cow;
delete animals['Dog'];
console.log(animals);</code></pre>
</div>
</div>
</p>
<p>If you're interested, read <a href="http://perfectionkills.com/understanding-delete" rel="noreferrer">Understanding Delete</a> for an in-depth explanation.</p> | {
"question_id": 3455405,
"question_date": "2010-08-11T04:59:03.097Z",
"question_score": 1713,
"tags": "javascript",
"answer_id": 3455416,
"answer_date": "2010-08-11T05:01:45.757Z",
"answer_score": 2895
} |
Please answer the following Stack Overflow question:
Title: Git diff against a stash
<p>How can I see the changes un-stashing will make to the current working tree? I would like to know what changes will be made before applying them!</p> | <p>See the most recent stash:</p>
<pre><code>git stash show -p
</code></pre>
<p>See an arbitrary stash:</p>
<pre><code>git stash show -p stash@{1}
</code></pre>
<p>From the <code>git stash</code> manpages:</p>
<blockquote>
<p>By default, the command shows the diffstat, but it will accept any
format known to git diff (e.g., git stash show -p stash@{1} to view
the second most recent stash in patch form).</p>
</blockquote> | {
"question_id": 7677736,
"question_date": "2011-10-06T16:48:59.513Z",
"question_score": 1713,
"tags": "git|git-stash",
"answer_id": 7677755,
"answer_date": "2011-10-06T16:50:29.447Z",
"answer_score": 2359
} |
Please answer the following Stack Overflow question:
Title: Insert into ... values ( SELECT ... FROM ... )
<p>I am trying to <code>INSERT INTO</code> a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the <code>SQL</code> engine of the day (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>, <a href="http://en.wikipedia.org/wiki/Oracle_Database" rel="noreferrer">Oracle</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>, <a href="http://en.wikipedia.org/wiki/IBM_Informix" rel="noreferrer">Informix</a>, and <a href="http://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>).</p>
<p>Is there a silver-bullet syntax coming from an SQL standard (for example, <a href="http://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">SQL-92</a>) that would allow me to insert the values without worrying about the underlying database?</p> | <p>Try:</p>
<pre><code>INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
</code></pre>
<p>This is standard ANSI SQL and should work on any DBMS</p>
<p>It definitely works for:</p>
<ul>
<li>Oracle</li>
<li>MS SQL Server</li>
<li>MySQL</li>
<li>Postgres</li>
<li>SQLite v3</li>
<li>Teradata</li>
<li>DB2</li>
<li>Sybase</li>
<li>Vertica</li>
<li>HSQLDB</li>
<li>H2</li>
<li>AWS RedShift</li>
<li>SAP HANA</li>
<li>Google Spanner</li>
</ul> | {
"question_id": 25969,
"question_date": "2008-08-25T12:45:56.930Z",
"question_score": 1712,
"tags": "sql|database|syntax|database-agnostic|ansi-sql-92",
"answer_id": 25971,
"answer_date": "2008-08-25T12:47:54.460Z",
"answer_score": 1873
} |
Please answer the following Stack Overflow question:
Title: Table Naming Dilemma: Singular vs. Plural Names
<p>Academia has it that table names should be the singular of the entity that they store attributes of. </p>
<p>I dislike any T-SQL that requires square brackets around names, but I have renamed a <code>Users</code> table to the singular, forever sentencing those using the table to sometimes have to use brackets. </p>
<p>My gut feel is that it is more correct to stay with the singular, but my gut feel is also that brackets indicate undesirables like column names with spaces in them etc.</p>
<p>Should I stay, or should I go?</p> | <p>Others have given pretty good answers as far as "standards" go, but I just wanted to add this... Is it possible that "User" (or "Users") is not actually a full description of the data held in the table? Not that you should get too crazy with table names and specificity, but perhaps something like "Widget_Users" (where "Widget" is the name of your application or website) would be more appropriate.</p> | {
"question_id": 338156,
"question_date": "2008-12-03T18:09:30.710Z",
"question_score": 1712,
"tags": "sql|sql-server|naming-conventions",
"answer_id": 338433,
"answer_date": "2008-12-03T19:31:01.157Z",
"answer_score": 264
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.