input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How to add images to README.md on GitHub?
<p>Recently I joined <strong>GitHub</strong>. I hosted some projects there.</p>
<p>I need to include some images in my README File. I don't know how to do that.</p>
<p>I searched about this, but all I got was some links which tell me to "host images on web and specify the image path in README.md file".</p>
<p>Is there any way to do this without hosting the images on any third-party web hosting services?</p> | <p>Try this markdown:</p>
<pre><code>
</code></pre>
<p>I think you can link directly to the raw version of an image if it's stored in your repository. i.e.</p>
<pre><code>
</code></pre> | {
"question_id": 14494747,
"question_date": "2013-01-24T05:44:06.837Z",
"question_score": 2941,
"tags": "github|markdown|github-flavored-markdown|readme",
"answer_id": 14494775,
"answer_date": "2013-01-24T05:46:32.903Z",
"answer_score": 2995
} |
Please answer the following Stack Overflow question:
Title: Why is printing "B" dramatically slower than printing "#"?
<p>I generated two matrices of <code>1000</code> x <code>1000</code>:</p>
<p>First Matrix: <code>O</code> and <code>#</code>.<br>
Second Matrix: <code>O</code> and <code>B</code>.</p>
<p>Using the following code, the first matrix took 8.52 seconds to complete:</p>
<pre><code>Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("#");
}
}
System.out.println("");
}
</code></pre>
<p>With this code, the second matrix took 259.152 seconds to complete:</p>
<pre><code>Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B"); //only line changed
}
}
System.out.println("");
}
</code></pre>
<p>What is the reason behind the dramatically different run times?</p>
<hr>
<p>As suggested in the comments, printing only <code>System.out.print("#");</code> takes <code>7.8871</code> seconds, whereas <code>System.out.print("B");</code> gives <code>still printing...</code>.</p>
<p>As others who pointed out that it works for them normally, I tried <a href="http://ideone.com" rel="noreferrer">Ideone.com</a> for instance, and both pieces of code execute at the same speed.</p>
<p>Test Conditions:</p>
<ul>
<li>I ran this test from <em>Netbeans 7.2</em>, with the output into its console</li>
<li>I used <code>System.nanoTime()</code> for measurements</li>
</ul> | <p><em>Pure speculation</em> is that you're using a terminal that attempts to do <a href="http://en.wikipedia.org/wiki/Word_wrap" rel="noreferrer">word-wrapping</a> rather than character-wrapping, and treats <code>B</code> as a word character but <code>#</code> as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a <code>#</code> almost immediately and happily breaks there; whereas with the <code>B</code>, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).</p>
<p>But that's pure speculation.</p> | {
"question_id": 21947452,
"question_date": "2014-02-21T23:45:43.777Z",
"question_score": 2940,
"tags": "java|performance|loops|for-loop|system.out",
"answer_id": 21947627,
"answer_date": "2014-02-22T00:02:01.013Z",
"answer_score": 4225
} |
Please answer the following Stack Overflow question:
Title: Deleting an element from an array in PHP
<p>Is there an easy way to delete an element from an array using PHP, such that <code>foreach ($array)</code> no longer includes that element?</p>
<p>I thought that setting it to <code>null</code> would do it, but apparently it does not work.</p> | <p>There are different ways to delete an array element, where some are more useful for some specific tasks than others.</p>
<h2>Deleting a single array element</h2>
<p>If you want to delete just one array element you can use <a href="https://secure.php.net/manual/en/function.unset.php" rel="noreferrer"><code>unset()</code></a> or alternatively <a href="https://secure.php.net/manual/en/function.array-splice.php" rel="noreferrer"><code>\array_splice()</code></a>.</p>
<p>If you know the value and don’t know the key to delete the element you can use <a href="http://php.net/manual/en/function.array-search.php" rel="noreferrer"><code>\array_search()</code></a> to get the key. This only works if the element does not occur more than once, since <code>\array_search</code> returns the first hit only.</p>
<h3><a href="http://php.net/manual/en/function.unset.php" rel="noreferrer"><code>unset()</code></a></h3>
<p>Note that when you use <code>unset()</code> the array keys won’t change. If you want to reindex the keys you can use <a href="http://php.net/manual/en/function.array-values.php" rel="noreferrer"><code>\array_values()</code></a> after <code>unset()</code>, which will convert all keys to numerically enumerated keys starting from 0.</p>
<p>Code:</p>
<pre><code>$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
</code></pre>
<p>Output:</p>
<pre><code>[
[0] => a
[2] => c
]
</code></pre>
<h3><a href="http://php.net/manual/en/function.array-splice.php" rel="noreferrer"><code>\array_splice()</code></a> method</h3>
<p>If you use <code>\array_splice()</code> the keys will automatically be reindexed, but the associative keys won’t change — as opposed to <code>\array_values()</code>, which will convert all keys to numerical keys.</p>
<p><code>\array_splice()</code> needs the <em>offset</em>, not the <em>key</em>, as the second parameter.</p>
<p>Code:</p>
<pre><code>$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
</code></pre>
<p>Output:</p>
<pre><code>[
[0] => a
[1] => c
]
</code></pre>
<p><code>array_splice()</code>, same as <code>unset()</code>, take the array by reference. You don’t assign the return values of those functions back to the array.</p>
<h2>Deleting multiple array elements</h2>
<p>If you want to delete multiple array elements and don’t want to call <code>unset()</code> or <code>\array_splice()</code> multiple times you can use the functions <code>\array_diff()</code> or <code>\array_diff_key()</code> depending on whether you know the values or the keys of the elements which you want to delete.</p>
<h3><a href="http://php.net/manual/en/function.array-diff.php" rel="noreferrer"><code>\array_diff()</code></a> method</h3>
<p>If you know the values of the array elements which you want to delete, then you can use <code>\array_diff()</code>. As before with <code>unset()</code> it won’t change the keys of the array.</p>
<p>Code:</p>
<pre><code>$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
</code></pre>
<p>Output:</p>
<pre><code>[
[1] => b
]
</code></pre>
<h3><a href="http://php.net/manual/en/function.array-diff-key.php" rel="noreferrer"><code>\array_diff_key()</code></a> method</h3>
<p>If you know the keys of the elements which you want to delete, then you want to use <code>\array_diff_key()</code>. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.</p>
<p>Code:</p>
<pre><code>$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
</code></pre>
<p>Output:</p>
<pre><code>[
[1] => b
]
</code></pre>
<p>If you want to use <code>unset()</code> or <code>\array_splice()</code> to delete multiple elements with the same value you can use <a href="http://php.net/manual/en/function.array-keys.php" rel="noreferrer"><code>\array_keys()</code></a> to get all the keys for a specific value and then delete all elements.</p>
<h3><a href="https://www.php.net/manual/en/function.array-filter.php" rel="noreferrer"><code>\array_filter()</code></a> method</h3>
<p>If you want to delete all elements with a specific value in the array you can use <code>\array_filter()</code>.</p>
<p>Code:</p>
<pre><code>$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
</code></pre>
<p>Output:</p>
<pre><code>[
[0] => a
[1] => c
]
</code></pre> | {
"question_id": 369602,
"question_date": "2008-12-15T20:28:55.307Z",
"question_score": 2936,
"tags": "php|arrays|unset",
"answer_id": 369608,
"answer_date": "2008-12-15T20:30:46.303Z",
"answer_score": 3417
} |
Please answer the following Stack Overflow question:
Title: How do I modify a specific commit?
<p>I have the following commit history:</p>
<ol>
<li><code>HEAD</code></li>
<li><code>HEAD~</code></li>
<li><code>HEAD~2</code></li>
<li><code>HEAD~3</code></li>
</ol>
<p><code>git commit --amend</code> modifies the current <code>HEAD</code> commit. But how do I modify <code>HEAD~3</code>?</p> | <p>Use <a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase" rel="noreferrer"><code>git rebase</code></a>. For example, to modify commit <code>bbc643cd</code>, run:</p>
<pre><code>$ git rebase --interactive 'bbc643cd^'
</code></pre>
<p>Please note the caret <code>^</code> at the end of the command, because you need actually to rebase back to <a href="https://stackoverflow.com/questions/1955985/">the commit <em>before</em> the one you wish to modify</a>.</p>
<p>In the default editor, modify <code>pick</code> to <code>edit</code> in the line mentioning <code>bbc643cd</code>.</p>
<p>Save the file and exit. git will interpret and automatically execute the commands in the file. You will find yourself in the previous situation in which you just had created commit <code>bbc643cd</code>.</p>
<p>At this point, <code>bbc643cd</code> is your last commit and you can <a href="https://www.atlassian.com/git/tutorials/rewriting-history#git-commit--amend" rel="noreferrer">easily amend it</a>. Make your changes and then commit them with the command:</p>
<pre><code>$ git commit --all --amend --no-edit
</code></pre>
<p>After that, return back to the previous HEAD commit using:</p>
<pre><code>$ git rebase --continue
</code></pre>
<p><strong>WARNING</strong>: Note that this will change the SHA-1 of that commit <strong>as well as all children</strong> -- in other words, this rewrites the history from that point forward. <a href="https://stackoverflow.com/a/3926832/1269037">You can break repos doing this</a> if you push using the command <code>git push --force</code>.</p> | {
"question_id": 1186535,
"question_date": "2009-07-27T05:19:07.750Z",
"question_score": 2927,
"tags": "git|git-rewrite-history",
"answer_id": 1186549,
"answer_date": "2009-07-27T05:28:02.240Z",
"answer_score": 3940
} |
Please answer the following Stack Overflow question:
Title: What does " 2>&1 " mean?
<p>To combine <code>stderr</code> and <code>stdout</code> into the <code>stdout</code> stream, we append this to a command:</p>
<pre><code>2>&1
</code></pre>
<p>e.g. to see the first few errors from compiling <code>g++ main.cpp</code>:</p>
<pre><code>g++ main.cpp 2>&1 | head
</code></pre>
<p>What does <code>2>&1</code> mean, in detail?</p> | <p>File descriptor 1 is the standard output (<code>stdout</code>).<br>
File descriptor 2 is the standard error (<code>stderr</code>).</p>
<p>At first, <code>2>1</code> may look like a good way to redirect <code>stderr</code> to <code>stdout</code>. However, it will actually be interpreted as "redirect <code>stderr</code> to a file named <code>1</code>".</p>
<p><code>&</code> indicates that what follows and precedes is a <em>file descriptor</em>, and not a filename. Thus, we use <code>2>&1</code>. Consider <code>>&</code> to be a redirect merger operator.</p> | {
"question_id": 818255,
"question_date": "2009-05-03T22:57:00.817Z",
"question_score": 2924,
"tags": "bash|shell|unix|redirect",
"answer_id": 818284,
"answer_date": "2009-05-03T23:04:53.107Z",
"answer_score": 3256
} |
Please answer the following Stack Overflow question:
Title: How can I check for "undefined" in JavaScript?
<p>What is the most appropriate way to test if a variable is undefined in JavaScript?</p>
<p>I've seen several possible ways:</p>
<pre><code>if (window.myVariable)
</code></pre>
<p>Or</p>
<pre><code>if (typeof(myVariable) != "undefined")
</code></pre>
<p>Or</p>
<pre><code>if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
</code></pre> | <p>If you are interested in finding out whether a variable has been declared regardless of its value, then using the <code>in</code> operator is the safest way to go. Consider this example:</p>
<pre><code>// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
</code></pre>
<p>But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the <code>in</code> operator for a more robust check.</p>
<pre><code>"theFu" in window; // true
"theFoo" in window; // false
</code></pre>
<p>If you are interested in knowing whether the variable hasn't been declared or has the value <code>undefined</code>, then use the <code>typeof</code> operator, which is guaranteed to return a string:</p>
<pre><code>if (typeof myVar !== 'undefined')
</code></pre>
<p>Direct comparisons against <code>undefined</code> are troublesome as <code>undefined</code> can be overwritten. </p>
<pre><code>window.undefined = "foo";
"foo" == undefined // true
</code></pre>
<p>As @CMS pointed out, this has been patched in ECMAScript 5th ed., and <code>undefined</code> is non-writable.</p>
<p><code>if (window.myVar)</code> will also include these falsy values, so it's not very robust:</p>
<pre>
false
0
""
NaN
null
undefined
</pre>
<p>Thanks to @CMS for pointing out that your third case - <code>if (myVariable)</code> can also throw an error in two cases. The first is when the variable hasn't been defined which throws a <code>ReferenceError</code>. </p>
<pre><code>// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
</code></pre>
<p>The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,</p>
<pre><code>// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
</code></pre> | {
"question_id": 3390396,
"question_date": "2010-08-02T17:53:29.070Z",
"question_score": 2921,
"tags": "javascript|undefined",
"answer_id": 3390426,
"answer_date": "2010-08-02T17:58:18.717Z",
"answer_score": 3105
} |
Please answer the following Stack Overflow question:
Title: How do I split a list into equally-sized chunks?
<p>How do I split a list of arbitrary length into equal sized chunks?</p>
<p><strong>Related question:</strong> <a href="https://stackoverflow.com/q/434287/7758804">How to iterate over a list in chunks</a></p> | <p>Here's a generator that yields evenly-sized chunks:</p>
<pre><code>def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
</code></pre>
<pre><code>import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]
</code></pre>
<p>For Python 2, using <code>xrange</code> instead of <code>range</code>:</p>
<pre><code>def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), n):
yield lst[i:i + n]
</code></pre>
<hr />
<p>Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:</p>
<pre><code>[lst[i:i + n] for i in range(0, len(lst), n)]
</code></pre>
<p>For Python 2:</p>
<pre><code>[lst[i:i + n] for i in xrange(0, len(lst), n)]
</code></pre> | {
"question_id": 312443,
"question_date": "2008-11-23T12:15:52.050Z",
"question_score": 2912,
"tags": "python|list|split|chunks",
"answer_id": 312464,
"answer_date": "2008-11-23T12:33:53.433Z",
"answer_score": 4168
} |
Please answer the following Stack Overflow question:
Title: Git fetch remote branch
<p>The remote contains various branches such as <code>origin/daves_branch</code>:</p>
<pre><code>$ git branch -r
origin/HEAD -> origin/master
origin/daves_branch
origin/master
</code></pre>
<p>How do I checkout <code>daves_branch</code> locally so that it tracks <code>origin/daves_branch</code>? I tried:</p>
<pre><code>$ git fetch origin discover
$ git checkout discover
</code></pre> | <h1>Update: Using Git Switch</h1>
<p>All of the information written below was accurate, but a new command, <a href="https://git-scm.com/docs/git-switch" rel="noreferrer"><code>git switch</code></a> has been added that simplifies the effort.</p>
<p>If <code>daves_branch</code> exists on the remote repository, but not on your local branch, you can simply type:</p>
<pre class="lang-sh prettyprint-override"><code>git switch daves_branch
</code></pre>
<p>Since you do not have the branch locally, this will automatically make <code>switch</code> look on the remote repo. It will then also automatically set up remote branch tracking.</p>
<p>Note that if <code>daves_branch</code> doesn't exist locally you'll need to <code>git fetch</code> first before using <code>switch</code>.</p>
<hr />
<h1>Original Post</h1>
<p>You need to create a local branch that tracks a remote branch. The following command will create a local branch named <strong>daves_branch</strong>, tracking the remote branch <strong>origin/daves_branch</strong>. When you push your changes the remote branch will be updated.</p>
<p>For most recent versions of Git:</p>
<pre><code>git checkout --track origin/daves_branch
</code></pre>
<p><code>--track</code> is shorthand for <code>git checkout -b [branch] [remotename]/[branch]</code> where [remotename] is <strong>origin</strong> in this case and [branch] is twice the same, <strong>daves_branch</strong> in this case.</p>
<p>For Git 1.5.6.5 you needed this:</p>
<pre><code>git checkout --track -b daves_branch origin/daves_branch
</code></pre>
<p>For Git 1.7.2.3 and higher, this is enough (it might have started earlier, but this is the earliest confirmation I could find quickly):</p>
<pre><code>git checkout daves_branch
</code></pre>
<p>Note that with recent Git versions, this command will not create a local branch and will put you in a 'detached HEAD' state. If you want a local branch, use the <code>--track</code> option.</p>
<p>Full details are here: <em><a href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches#_tracking_branches" rel="noreferrer">3.5 Git Branching - Remote Branches, Tracking Branches</a></em></p> | {
"question_id": 9537392,
"question_date": "2012-03-02T17:06:56.660Z",
"question_score": 2909,
"tags": "git|branch|git-branch|git-fetch",
"answer_id": 9537923,
"answer_date": "2012-03-02T17:45:18.030Z",
"answer_score": 3930
} |
Please answer the following Stack Overflow question:
Title: How to append something to an array?
<p>How do I append an object (such as a string or number) to an array in JavaScript? </p> | <p>Use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" rel="noreferrer"><code>Array.prototype.push</code></a> method to append values to the end of an array:</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>// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);</code></pre>
</div>
</div>
</p>
<hr />
<p>You can use the <code>push()</code> function to append more than one value to an array in a single call:</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>// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}</code></pre>
</div>
</div>
</p>
<hr />
<p><strong>Update</strong></p>
<p>If you want to add the items of one array to another array, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer"><code>firstArray.concat(secondArray)</code></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>var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);</code></pre>
</div>
</div>
</p>
<p><strong>Update</strong></p>
<p>Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift" rel="noreferrer"><code>Array.prototype.unshift</code></a> for this purpose.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);</code></pre>
</div>
</div>
</p>
<p>It also supports appending multiple values at once just like <code>push</code>.</p>
<hr />
<p><strong>Update</strong></p>
<p>Another way with <em><strong>ES6</strong></em> syntax is to return a new array with the <em><strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spread syntax</a></strong></em>. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.</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 arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);</code></pre>
</div>
</div>
</p> | {
"question_id": 351409,
"question_date": "2008-12-09T00:20:05.937Z",
"question_score": 2891,
"tags": "javascript|arrays|append",
"answer_id": 351421,
"answer_date": "2008-12-09T00:24:28.143Z",
"answer_score": 5116
} |
Please answer the following Stack Overflow question:
Title: Is there a standard function to check for null, undefined, or blank variables in JavaScript?
<p>Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not <code>undefined</code> or <code>null</code>? I've got this code, but I'm not sure if it covers all cases:</p>
<pre><code>function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
</code></pre> | <p>You can just check if the <em>variable</em> has a <code>truthy</code> value or not. That means</p>
<pre><code>if( value ) {
}
</code></pre>
<p>will evaluate to <code>true</code> if <code>value</code> is <strong>not</strong>:</p>
<ul>
<li>null</li>
<li>undefined</li>
<li>NaN</li>
<li>empty string ("")</li>
<li>0</li>
<li>false</li>
</ul>
<p>The above list represents all possible <code>falsy</code> values in ECMA-/Javascript. Find it in the <a href="https://www.ecma-international.org/ecma-262/5.1/#sec-9.2" rel="noreferrer">specification</a> at the <code>ToBoolean</code> section.</p>
<p>Furthermore, if you do not <strong>know</strong> whether a variable exists (that means, if it was <em>declared</em>) you should check with the <code>typeof</code> operator. For instance</p>
<pre><code>if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
</code></pre>
<p>If you can be sure that a <em>variable</em> is declared at least, you should directly check if it has a <code>truthy</code> value like shown above.</p> | {
"question_id": 5515310,
"question_date": "2011-04-01T15:14:24.250Z",
"question_score": 2881,
"tags": "javascript|null|comparison|undefined",
"answer_id": 5515349,
"answer_date": "2011-04-01T15:17:44.727Z",
"answer_score": 5446
} |
Please answer the following Stack Overflow question:
Title: Length of a JavaScript object
<p>I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?</p>
<pre><code>const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
</code></pre> | <h2>Updated answer</h2>
<p><strong>Here's an update as of 2016 and <a href="http://kangax.github.io/compat-table/es5/" rel="noreferrer">widespread deployment of ES5</a> and beyond.</strong> For IE9+ and all other modern ES5+ capable browsers, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys()</code></a> so the above code just becomes:</p>
<pre><code>var size = Object.keys(myObj).length;
</code></pre>
<p>This doesn't have to modify any existing prototype since <code>Object.keys()</code> is now built-in.</p>
<p><strong>Edit</strong>: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.</p>
<p>Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.</p>
<p><code>Object.keys</code> or <code>Object.getOwnPropertyNames</code> does not work for symbolic properties. To return them you need to use <code>Object.getOwnPropertySymbols</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var person = {
[Symbol('name')]: 'John Doe',
[Symbol('age')]: 33,
"occupation": "Programmer"
};
const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1
let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2</code></pre>
</div>
</div>
</p>
<h2>Older answer</h2>
<p>The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:</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>Object.size = function(obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
const myObj = {}
var size = Object.size(myObj);</code></pre>
</div>
</div>
</p>
<p>There's a sort of convention in JavaScript that you <a href="https://stackoverflow.com/questions/10757455/object-prototype-is-verboten">don't add things to Object.prototype</a>, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.</p>
<hr /> | {
"question_id": 5223,
"question_date": "2008-08-07T19:42:21.060Z",
"question_score": 2876,
"tags": "javascript|javascript-objects",
"answer_id": 6700,
"answer_date": "2008-08-09T08:31:04.577Z",
"answer_score": 3169
} |
Please answer the following Stack Overflow question:
Title: How do I access environment variables in Python?
<p>How do I get the value of an environment variable in Python?</p> | <p>Environment variables are accessed through <a href="https://docs.python.org/library/os.html#os.environ" rel="noreferrer"><code>os.environ</code></a>:</p>
<pre><code>import os
print(os.environ['HOME'])
</code></pre>
<p>To see a list of all environment variables:</p>
<pre><code>print(os.environ)
</code></pre>
<hr />
<p>If a key is not present, attempting to access it will raise a <code>KeyError</code>. To avoid this:</p>
<pre><code># Returns `None` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# Returns `default_value` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))
# Returns `default_value` if key doesn't exist
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
</code></pre> | {
"question_id": 4906977,
"question_date": "2011-02-05T13:03:35.693Z",
"question_score": 2876,
"tags": "python|environment-variables",
"answer_id": 4907053,
"answer_date": "2011-02-05T13:18:00.240Z",
"answer_score": 4156
} |
Please answer the following Stack Overflow question:
Title: How do I modify the URL without reloading the page?
<p>Is there a way I can modify the URL of the current page without reloading the page?</p>
<p>I would like to access the portion <strong>before</strong> the # hash if possible.</p>
<p>I only need to change the portion <strong>after</strong> the domain, so it's not like I'm violating cross-domain policies.</p>
<pre><code> window.location.href = "www.mysite.com/page2.php"; // this reloads
</code></pre> | <p>This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!</p>
<p>See this question's answer for more information:
<em><a href="https://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page">Updating address bar with new URL without hash or reloading the page</a></em></p>
<p>Example:</p>
<pre><code> function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
</code></pre>
<p>You can then use <code>window.onpopstate</code> to detect the back/forward button navigation:</p>
<pre><code>window.onpopstate = function(e){
if(e.state){
document.getElementById("content").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
</code></pre>
<hr>
<p>For a more in-depth look at manipulating browser history, see <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history" rel="noreferrer">this MDN article</a>.</p> | {
"question_id": 824349,
"question_date": "2009-05-05T10:54:05.763Z",
"question_score": 2867,
"tags": "javascript|html|url|url-rewriting|friendly-url",
"answer_id": 3354511,
"answer_date": "2010-07-28T15:30:31.523Z",
"answer_score": 2343
} |
Please answer the following Stack Overflow question:
Title: How do I get the current date in JavaScript?
<p>How do I get the current date in JavaScript?</p> | <p>Use <code>new Date()</code> to generate a new <code>Date</code> object containing the current date and time.</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>var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
document.write(today);</code></pre>
</div>
</div>
</p>
<p>This will give you today's date in the format of mm/dd/yyyy.</p>
<p>Simply change <code>today = mm +'/'+ dd +'/'+ yyyy;</code> to whatever format you wish.</p> | {
"question_id": 1531093,
"question_date": "2009-10-07T11:39:02.730Z",
"question_score": 2863,
"tags": "javascript|date|date-formatting",
"answer_id": 4929629,
"answer_date": "2011-02-08T04:42:59.513Z",
"answer_score": 3316
} |
Please answer the following Stack Overflow question:
Title: Convert string "Jun 1 2005 1:33PM" into datetime
<p>How do I convert the following string to a <a href="https://docs.python.org/3/library/datetime.html#datetime-objects" rel="noreferrer"><code>datetime</code></a> object?</p>
<pre><code>"Jun 1 2005 1:33PM"
</code></pre> | <p><a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>datetime.strptime</code></a> parses an input string in the user-specified format into a <em>timezone-naive</em> <a href="https://docs.python.org/3/library/datetime.html#datetime-objects" rel="noreferrer"><code>datetime</code></a> object:</p>
<pre><code>>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
</code></pre>
<p>To obtain a <a href="https://docs.python.org/3/library/datetime.html#date-objects" rel="noreferrer"><code>date</code></a> object using an existing <code>datetime</code> object, convert it using <code>.date()</code>:</p>
<pre><code>>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
</code></pre>
<hr />
<p><strong>Links:</strong></p>
<ul>
<li><p><code>strptime</code> docs: <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="noreferrer" title="datetime.datetime.strptime">Python 2</a>, <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime" rel="noreferrer">Python 3</a></p>
</li>
<li><p><code>strptime</code>/<code>strftime</code> format string docs: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer" title="strftime-and-strptime-behavior">Python 2</a>, <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">Python 3</a></p>
</li>
<li><p><a href="http://strftime.org/" rel="noreferrer">strftime.org</a> format string cheatsheet</p>
</li>
</ul>
<p><strong>Notes:</strong></p>
<ul>
<li><code>strptime</code> = "string parse time"</li>
<li><code>strftime</code> = "string format time"</li>
</ul> | {
"question_id": 466345,
"question_date": "2009-01-21T18:00:29.140Z",
"question_score": 2849,
"tags": "python|datetime",
"answer_id": 466376,
"answer_date": "2009-01-21T18:08:52.353Z",
"answer_score": 4342
} |
Please answer the following Stack Overflow question:
Title: How can I check if a program exists from a Bash script?
<p>How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?</p>
<p>It seems like it should be easy, but it's been stumping me.</p> | <h2>Answer</h2>
<p>POSIX compatible:</p>
<pre><code>command -v <the_command>
</code></pre>
<p>Example use:</p>
<pre><code>if ! command -v <the_command> &> /dev/null
then
echo "<the_command> could not be found"
exit
fi
</code></pre>
<p>For Bash specific environments:</p>
<pre><code>hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
</code></pre>
<h2>Explanation</h2>
<p>Avoid <code>which</code>. Not only is it an external process you're launching for doing very little (meaning builtins like <code>hash</code>, <code>type</code> or <code>command</code> are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.</p>
<p>Why care?</p>
<ul>
<li>Many operating systems have a <code>which</code> that <strong>doesn't even set an exit status</strong>, meaning the <code>if which foo</code> won't even work there and will <strong>always</strong> report that <code>foo</code> exists, even if it doesn't (note that some POSIX shells appear to do this for <code>hash</code> too).</li>
<li>Many operating systems make <code>which</code> do custom and evil stuff like change the output or even hook into the package manager.</li>
</ul>
<p>So, don't use <code>which</code>. Instead use one of these:</p>
<pre><code>command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<pre><code>type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<pre><code>hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
</code></pre>
<p>(Minor side-note: some will suggest <code>2>&-</code> is the same <code>2>/dev/null</code> but shorter – <em>this is untrue</em>. <code>2>&-</code> closes FD 2 which causes an <strong>error</strong> in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))</p>
<p>If your hash bang is <code>/bin/sh</code> then you should care about what POSIX says. <code>type</code> and <code>hash</code>'s exit codes aren't terribly well defined by POSIX, and <code>hash</code> is seen to exit successfully when the command doesn't exist (haven't seen this with <code>type</code> yet). <code>command</code>'s exit status is well defined by POSIX, so that one is probably the safest to use.</p>
<p>If your script uses <code>bash</code> though, POSIX rules don't really matter anymore and both <code>type</code> and <code>hash</code> become perfectly safe to use. <code>type</code> now has a <code>-P</code> to search just the <code>PATH</code> and <code>hash</code> has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.</p>
<p>As a simple example, here's a function that runs <code>gdate</code> if it exists, otherwise <code>date</code>:</p>
<pre><code>gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
</code></pre>
<h1>Alternative with a complete feature set</h1>
<p>You can use <a href="https://gitlab.com/bertrand-benoit/scripts-common" rel="noreferrer">scripts-common</a> to reach your need.</p>
<p>To check if something is installed, you can do:</p>
<pre class="lang-bash prettyprint-override"><code>checkBin <the_command> || errorMessage "This tool requires <the_command>. Install it please, and then run this tool again."
</code></pre> | {
"question_id": 592620,
"question_date": "2009-02-26T21:52:49.460Z",
"question_score": 2846,
"tags": "bash",
"answer_id": 677212,
"answer_date": "2009-03-24T12:45:20.057Z",
"answer_score": 4050
} |
Please answer the following Stack Overflow question:
Title: What is the --save option for npm install?
<p>I saw some tutorial where the command was:</p>
<pre><code>npm install --save
</code></pre>
<p>What does the <code>--save</code> option mean?</p> | <p><strong>Update npm 5:</strong></p>
<p>As of <a href="http://blog.npmjs.org/post/161081169345/v500" rel="noreferrer">npm 5.0.0</a>, installed modules are added as a dependency by default, so the <code>--save</code> option is no longer needed. The other save options still exist and are listed in the <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">documentation</a> for <code>npm install</code>.</p>
<p><em>Original answer:</em></p>
<p>Before version 5, NPM simply installed a package under <code>node_modules</code> by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the <code>dependencies</code> section of your <code>package.json</code>.</p>
<p>The <code>--save</code> option instructed NPM to include the package inside of the <code>dependencies</code> section of your <code>package.json</code> automatically, thus saving you an additional step.</p>
<p>In addition, there are the complementary options <code>--save-dev</code> and <code>--save-optional</code> which save the package under <code>devDependencies</code> and <code>optionalDependencies</code>, respectively. This is useful when installing development-only packages, like <code>grunt</code> or your testing library.</p> | {
"question_id": 19578796,
"question_date": "2013-10-24T23:54:11.843Z",
"question_score": 2835,
"tags": "node.js|npm",
"answer_id": 19578808,
"answer_date": "2013-10-24T23:56:10.833Z",
"answer_score": 3302
} |
Please answer the following Stack Overflow question:
Title: How do I pass command line arguments to a Node.js program?
<p>I have a web server written in <a href="http://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a> and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:</p>
<pre><code>$ node server.js folder
</code></pre>
<p>here <code>server.js</code> is my server code. Node.js help says this is possible:</p>
<pre><code>$ node -h
Usage: node [options] script.js [arguments]
</code></pre>
<p>How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.</p> | <h1>Standard Method (no library)</h1>
<p>The arguments are stored in <code>process.argv</code></p>
<p>Here are <a href="http://nodejs.org/docs/latest/api/process.html#process_process_argv" rel="noreferrer">the node docs on handling command line args:</a></p>
<blockquote>
<p><code>process.argv</code> is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
</code></pre>
<p>This will generate:</p>
<pre class="lang-none prettyprint-override"><code>$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
</code></pre> | {
"question_id": 4351521,
"question_date": "2010-12-04T01:56:46.047Z",
"question_score": 2833,
"tags": "javascript|node.js|arguments|command-line-arguments",
"answer_id": 4351548,
"answer_date": "2010-12-04T02:05:32.903Z",
"answer_score": 3458
} |
Please answer the following Stack Overflow question:
Title: How do I clone a Git repository into a specific folder?
<p>The command <code>git clone [email protected]:whatever</code> creates a directory named <code>whatever</code> containing a Git repository:</p>
<pre><code>./
whatever/
.git
</code></pre>
<p>I want the contents of the Git repository cloned into my current directory <code>./</code> instead:</p>
<pre><code>./
.git
</code></pre> | <p><strong>Option A:</strong></p>
<pre><code>git clone [email protected]:whatever folder-name
</code></pre>
<p>Ergo, for <code>right here</code> use:</p>
<pre><code>git clone [email protected]:whatever .
</code></pre>
<p><strong>Option B:</strong></p>
<p>Move the <code>.git</code> folder, too. Note that the <code>.git</code> folder is hidden in most graphical file explorers, so be sure to show hidden files.</p>
<pre><code>mv /where/it/is/right/now/* /where/I/want/it/
mv /where/it/is/right/now/.* /where/I/want/it/
</code></pre>
<p>The first line grabs all normal files, the second line grabs dot-files. It is also possibe to do it in one line by enabling dotglob (i.e. <code>shopt -s dotglob</code>) but that is probably a bad solution if you are asking the question this answer answers.</p>
<p><strong>Better yet:</strong></p>
<p>Keep your working copy somewhere else, and create a symbolic link. Like this:</p>
<pre><code>ln -s /where/it/is/right/now /the/path/I/want/to/use
</code></pre>
<p>For your case this would be something like:</p>
<pre><code>ln -sfn /opt/projectA/prod/public /httpdocs/public
</code></pre>
<p>Which easily could be changed to test if you wanted it, i.e.:</p>
<pre><code>ln -sfn /opt/projectA/test/public /httpdocs/public
</code></pre>
<p>without moving files around. Added <code>-fn</code> in case someone is copying these lines (<code>-f</code> is force, <code>-n</code> avoid some often unwanted interactions with already and non-existing links).</p>
<p>If you just want it to work, use Option A, if someone else is going to look at what you have done, use Option C.</p> | {
"question_id": 651038,
"question_date": "2009-03-16T15:56:54.907Z",
"question_score": 2826,
"tags": "git|repository|git-clone",
"answer_id": 651079,
"answer_date": "2009-03-16T16:08:24.707Z",
"answer_score": 3962
} |
Please answer the following Stack Overflow question:
Title: How can I save an activity state using the save instance state?
<p>I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:</p>
<pre class="lang-java prettyprint-override"><code>package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
private TextView mTextView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
</code></pre>
<p>I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.</p>
<p>I'm sure the solution is as simple as overriding <code>onPause</code> or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.</p> | <p>You need to override <code>onSaveInstanceState(Bundle savedInstanceState)</code> and write the application state values you want to change to the <code>Bundle</code> parameter like this:</p>
<pre><code>@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
</code></pre>
<p>The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to <code>onCreate()</code> and also <code>onRestoreInstanceState()</code> where you would then extract the values from activity like this:</p>
<pre><code>@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
</code></pre>
<p>Or from a fragment.</p>
<pre><code>@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
</code></pre>
<p>You would usually use this technique to store instance values for your application (selections, unsaved text, etc.).</p> | {
"question_id": 151777,
"question_date": "2008-09-30T04:41:15.340Z",
"question_score": 2826,
"tags": "android|android-activity|application-state",
"answer_id": 151940,
"answer_date": "2008-09-30T06:12:20.847Z",
"answer_score": 2701
} |
Please answer the following Stack Overflow question:
Title: How do I detect a click outside an element?
<p>I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.</p>
<p>Is something like this possible with jQuery?</p>
<pre><code>$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
</code></pre> | <blockquote>
<p>Note: Using <code>stopPropagation</code> is something that should be avoided as it breaks normal event flow in the DOM. See <a href="https://css-tricks.com/dangers-stopping-event-propagation/" rel="noreferrer">this CSS Tricks article</a> for more information. Consider using <a href="https://stackoverflow.com/a/3028037/561309">this method</a> instead.</p>
</blockquote>
<p>Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.</p>
<pre class="lang-js prettyprint-override"><code>$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
</code></pre> | {
"question_id": 152975,
"question_date": "2008-09-30T13:17:12.340Z",
"question_score": 2822,
"tags": "javascript|jquery|click",
"answer_id": 153047,
"answer_date": "2008-09-30T13:38:11.133Z",
"answer_score": 1972
} |
Please answer the following Stack Overflow question:
Title: HTTP GET with request body
<p>I'm developing a new RESTful webservice for our application.</p>
<p>When doing a GET on certain entities, clients can request the contents of the entity.
If they want to add some parameters (for example sorting a list) they can add these parameters in the query string.</p>
<p>Alternatively I want people to be able to specify these parameters in the request body.
<a href="https://www.rfc-editor.org/rfc/rfc2616" rel="noreferrer">HTTP/1.1</a> does not seem to explicitly forbid this. This will allow them to specify more information, might make it easier to specify complex XML requests.</p>
<p>My questions:</p>
<ul>
<li>Is this a good idea altogether?</li>
<li>Will HTTP clients have issues with using request bodies within a GET request?</li>
</ul>
<p><a href="https://www.rfc-editor.org/rfc/rfc2616" rel="noreferrer">https://www.rfc-editor.org/rfc/rfc2616</a></p> | <p><a href="https://groups.yahoo.com/neo/groups/rest-discuss/conversations/messages/9962" rel="noreferrer">Roy Fielding's comment about including a body with a GET request</a>.</p>
<blockquote>
<p>Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.</p>
<p>So, yes, you can send a body with GET, and no, it is never useful to do so.</p>
<p>This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress).</p>
<p>....Roy</p>
</blockquote>
<p>Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and <em>changing your response based on its contents</em>, then you are ignoring this recommendation in <a href="https://www.rfc-editor.org/rfc/rfc2616#section-4.3" rel="noreferrer">the HTTP/1.1 spec, section 4.3</a>:</p>
<blockquote>
<p>...if the request method does not include defined semantics for an entity-body, then the message-body <a href="https://www.ietf.org/rfc/rfc2119.txt" rel="noreferrer">SHOULD</a> be ignored when handling the request.</p>
</blockquote>
<p>And the description of the GET method in <a href="https://www.rfc-editor.org/rfc/rfc2616#section-9.3" rel="noreferrer">the HTTP/1.1 spec, section 9.3</a>:</p>
<blockquote>
<p>The GET method means retrieve whatever information ([...]) is identified by the Request-URI.</p>
</blockquote>
<p>which states that the request-body is not part of the identification of the resource in a GET request, only the request URI.</p>
<p><strong>Update</strong></p>
<p>The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "the message-body SHOULD be ignored when handling the request" has been deleted. It's now just "Request message framing is independent of method semantics, even if the method doesn't define any use for a message body" The 2nd quote "The GET method means retrieve whatever information ... is identified by the Request-URI" was deleted. - From a comment</p>
<p>From the <a href="https://www.rfc-editor.org/rfc/rfc7231#page-24" rel="noreferrer">HTTP 1.1 2014 Spec</a>:</p>
<blockquote>
<p>A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.</p>
</blockquote> | {
"question_id": 978061,
"question_date": "2009-06-10T20:47:24.297Z",
"question_score": 2818,
"tags": "rest|http|http-get",
"answer_id": 983458,
"answer_date": "2009-06-11T20:27:36.547Z",
"answer_score": 2284
} |
Please answer the following Stack Overflow question:
Title: What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?
<p>What is the difference between the <code>COPY</code> and <code>ADD</code> commands in a Dockerfile, and when would I use one over the other?</p>
<pre><code>COPY <src> <dest>
</code></pre>
<blockquote>
<p>The COPY instruction will copy new files from <code><src></code> and add them to the container's filesystem at path <code><dest></code></p>
</blockquote>
<pre><code>ADD <src> <dest>
</code></pre>
<blockquote>
<p>The ADD instruction will copy new files from <code><src></code> and add them to the container's filesystem at path <code><dest></code>.</p>
</blockquote> | <p>You should check the <a href="https://docs.docker.com/engine/reference/builder/#add" rel="noreferrer"><code>ADD</code></a> and <a href="https://docs.docker.com/engine/reference/builder/#copy" rel="noreferrer"><code>COPY</code></a> documentation for a more detailed description of their behaviors, but in a nutshell, the major difference is that <code>ADD</code> can do more than <code>COPY</code>:</p>
<ul>
<li><code>ADD</code> allows <code><src></code> to be a URL</li>
<li>Referring to comments below, the <code>ADD</code> <a href="https://docs.docker.com/engine/reference/builder/#add" rel="noreferrer">documentation</a> states that:</li>
</ul>
<blockquote>
<p>If is a local tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from remote URLs are not decompressed.</p>
</blockquote>
<p>Note that the <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy" rel="noreferrer">Best practices for writing Dockerfiles</a> suggests using <code>COPY</code> where the magic of <code>ADD</code> is not required. Otherwise, you (<em>since you had to look up this answer</em>) are likely to get surprised someday when you mean to copy <code>keep_this_archive_intact.tar.gz</code> into your container, but instead, you spray the contents onto your filesystem.</p> | {
"question_id": 24958140,
"question_date": "2014-07-25T14:31:20.337Z",
"question_score": 2816,
"tags": "docker|dockerfile",
"answer_id": 24958548,
"answer_date": "2014-07-25T14:52:38.900Z",
"answer_score": 2734
} |
Please answer the following Stack Overflow question:
Title: What are the correct version numbers for C#?
<p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about <strong><em>C# 3.5</em></strong>?</p>
<p>This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. <strong><em>C# 3.5</em></strong>. The hope is that anyone failing to find an answer with the wrong version number will find <em>this</em> question and then search again with the right version number.</p> | <h1>C# language version history:</h1>
<p>These are the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history" rel="noreferrer">versions of C#</a> known about at the time of this writing:</p>
<ul>
<li><strong>C# 1.0</strong> released with .NET 1.0 and VS2002 (January 2002)</li>
<li><strong>C# 1.2</strong> (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call <code>Dispose</code> on <code>IEnumerator</code>s which implemented <code>IDisposable</code>. A few other small features.</li>
<li><strong>C# 2.0</strong> released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, and iterator blocks</li>
<li><strong>C# 3.0</strong> released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (<code>var</code>), and query expressions</li>
<li><strong>C# 4.0</strong> released with .NET 4 and VS2010 (April 2010). Major new features: late binding (<code>dynamic</code>), delegate and interface generic variance, more <a href="https://en.wikipedia.org/wiki/Component_Object_Model" rel="noreferrer">COM</a> support, named arguments, tuple data type and optional parameters</li>
<li><strong>C# 5.0</strong> released with .NET 4.5 and VS2012 (August 2012). <a href="https://devblogs.microsoft.com/csharpfaq/visual-studio-11-beta-is-here/" rel="noreferrer">Major features</a>: async programming, and caller info attributes. Breaking change: <a href="https://ericlippert.com/2009/11/16/closing-over-the-loop-variable-considered-harmful-part-two/" rel="noreferrer">loop variable closure</a>.</li>
<li><strong>C# 6.0</strong> released with .NET 4.6 and VS2015 (July 2015). Implemented by <a href="https://github.com/dotnet/roslyn" rel="noreferrer">Roslyn</a>. <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6" rel="noreferrer">Features</a>: initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers, <code>await</code> in <code>catch</code> and <code>finally</code>, extension <code>Add</code> methods in collection initializers.</li>
<li><strong>C# 7.0</strong> released with .NET 4.7 and VS2017 (March 2017). Major <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7" rel="noreferrer">new features</a>: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples" rel="noreferrer">tuples</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#ref-locals-and-returns" rel="noreferrer">ref locals and ref return</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching" rel="noreferrer">pattern matching</a> (including pattern-based switch statements), <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables" rel="noreferrer">inline <code>out</code> parameter declarations</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions" rel="noreferrer">local functions</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements" rel="noreferrer">binary literals, digit separators</a>, and <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#generalized-async-return-types" rel="noreferrer">arbitrary async returns</a>.</li>
<li><strong>C# 7.1</strong> released with VS2017 v15.3 (August 2017). New features: <a href="https://github.com/dotnet/csharplang/issues/97" rel="noreferrer">async main</a>, <a href="https://github.com/dotnet/csharplang/issues/415" rel="noreferrer">tuple member name inference</a>, <a href="https://github.com/dotnet/csharplang/issues/102" rel="noreferrer">default expression</a>, and <a href="https://github.com/dotnet/csharplang/issues/154" rel="noreferrer">pattern matching with generics</a>.</li>
<li><strong>C# 7.2</strong> released with VS2017 v15.5 (November 2017). New features: <a href="https://github.com/dotnet/csharplang/issues/37" rel="noreferrer">private protected access modifier</a>, <a href="https://github.com/dotnet/csharplang/issues/666" rel="noreferrer">Span<T>, aka interior pointer, aka stackonly struct</a>, and <a href="https://github.com/dotnet/csharplang/milestone/6" rel="noreferrer">everything else</a>.</li>
<li><strong>C# 7.3</strong> released with VS2017 v15.7 (May 2018). New features: <a href="https://devblogs.microsoft.com/premier-developer/dissecting-new-generics-constraints-in-c-7-3/" rel="noreferrer">enum, delegate and <code>unmanaged</code> generic type constraints</a>. <code>ref</code> reassignment. Unsafe improvements: <code>stackalloc</code> initialization, unpinned indexed <code>fixed</code> buffers, custom <code>fixed</code> statements. Improved overloading resolution. Expression variables in initializers and queries. <code>==</code> and <code>!=</code> defined for tuples. Auto-properties' backing fields can now be targeted by attributes.</li>
<li><strong>C# 8.0</strong> released with .NET Core 3.0 and VS2019 v16.3 (September 2019). Major <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8" rel="noreferrer">new features</a>: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references" rel="noreferrer">nullable reference-types</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams" rel="noreferrer">asynchronous streams</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges" rel="noreferrer">indices and ranges</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members" rel="noreferrer">readonly members</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">using declarations</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods" rel="noreferrer">default interface methods</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions" rel="noreferrer">static local functions</a>, and <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#enhancement-of-interpolated-verbatim-strings" rel="noreferrer">enhancement of interpolated verbatim strings</a>.</li>
<li><strong>C# 9.0</strong> released with <a href="https://devblogs.microsoft.com/dotnet/announcing-net-5-0/" rel="noreferrer">.NET 5.0</a> and VS2019 v16.8 (November 2020). Major <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9" rel="noreferrer">new features</a>: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters" rel="noreferrer">init-only properties</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types" rel="noreferrer">records</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression" rel="noreferrer">with-expressions</a>, data classes, positional records, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#top-level-statements" rel="noreferrer">top-level programs</a>, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements" rel="noreferrer">improved pattern matching</a> (simple type patterns, relational patterns, logical patterns), improved target typing (target-type <code>new</code> expressions, target typed <code>??</code> and <code>?</code>), and covariant returns. Minor features: relax ordering of <code>ref</code> and <code>partial</code> modifiers, parameter null checking, lambda discard parameters, native <code>int</code>s, attributes on local functions, function pointers, static lambdas, extension <code>GetEnumerator</code>, module initializers, and extending partial.</li>
<li><strong>C# 10.0</strong> released with .NET 6.0 (November 2021). Major <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10" rel="noreferrer">new features</a>: record structs, struct parameterless constructors, interpolated string handlers, global <code>using</code> directives, file-scoped namespace declarations, extended property patterns, const interpolated strings, mixed assignment and declaration in deconstruction, async method builders (via attributes) for individual methods, the <code>CallerArgumentExpression</code> attribute for parameters, enhanced <code>#line</code> pragmas.</li>
</ul>
<h2>In response to the OP's question:</h2>
<blockquote>
<p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?</p>
</blockquote>
<p>There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (<a href="https://msdn.microsoft.com/en-us/library/bb822049.aspx" rel="noreferrer">this MSDN page</a> used to refer to it that way, for example), but the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.environment.version" rel="noreferrer"><code>Environment.Version</code></a> property still reports 4.0.xxx.</p>
<p>As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: <a href="https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md" rel="noreferrer">Features Added in C# Language Versions</a>. There is also <a href="https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md" rel="noreferrer">a page that tracks upcoming and recently implemented language features</a>.</p> | {
"question_id": 247621,
"question_date": "2008-10-29T17:09:40.230Z",
"question_score": 2812,
"tags": "c#|.net|visual-studio|.net-core|.net-framework-version",
"answer_id": 247623,
"answer_date": "2008-10-29T17:10:18.090Z",
"answer_score": 3112
} |
Please answer the following Stack Overflow question:
Title: I need an unordered list without any bullets
<p>I have created an unordered list. I feel the bullets in the unordered list are bothersome, so I want to remove them. </p>
<p>Is it possible to have a list without bullets?</p> | <p>You can remove bullets by setting the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type" rel="noreferrer"><code>list-style-type</code></a> to <code>none</code> on the CSS for the parent element (typically a <code><ul></code>), for example:</p>
<pre class="lang-css prettyprint-override"><code>ul {
list-style-type: none;
}
</code></pre>
<p>You might also want to add <code>padding: 0</code> and <code>margin: 0</code> to that if you want to remove indentation as well.</p>
<p>See <a href="http://css.maxdesign.com.au/listutorial/index.htm" rel="noreferrer">Listutorial</a> for a great walkthrough of list formatting techniques.</p> | {
"question_id": 1027354,
"question_date": "2009-06-22T13:57:53.150Z",
"question_score": 2810,
"tags": "html|css",
"answer_id": 1027367,
"answer_date": "2009-06-22T14:00:00.947Z",
"answer_score": 4069
} |
Please answer the following Stack Overflow question:
Title: How does database indexing work?
<p>Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?</p>
<p>For information on queries to index a field, check out <a href="https://stackoverflow.com/questions/1156/">How do I index a database column</a>.</p> | <p><strong>Why is it needed?</strong></p>
<p>When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.</p>
<p>Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires <code>(N+1)/2</code> block accesses (on average), where <code>N</code> is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at <code>N</code> block accesses.</p>
<p>Whereas with a sorted field, a Binary Search may be used, which has <code>log2 N</code> block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.</p>
<p><strong>What is indexing?</strong></p>
<p>Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.</p>
<p>The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.</p>
<p><strong>How does it work?</strong></p>
<p>Firstly, let’s outline a sample database table schema;</p>
<pre>
Field name Data type Size on disk
id (Primary key) Unsigned INT 4 bytes
firstName Char(50) 50 bytes
lastName Char(50) 50 bytes
emailAddress Char(100) 100 bytes
</pre>
<p><strong>Note</strong>: char was used in place of varchar to allow for an accurate size on disk value.
This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the <em>id</em> (a sorted key field) and one using the <em>firstName</em> (a non-key unsorted field).</p>
<p><em><strong>Example 1</strong></em> - <em>sorted vs unsorted fields</em></p>
<p>Given our sample database of <code>r = 5,000,000</code> records of a fixed size giving a record length of <code>R = 204</code> bytes and they are stored in a table using the MyISAM engine which is using the default block size <code>B = 1,024</code> bytes. The blocking factor of the table would be <code>bfr = (B/R) = 1024/204 = 5</code> records per disk block. The total number of blocks required to hold the table is <code>N = (r/bfr) = 5000000/5 = 1,000,000</code> blocks.</p>
<p>A linear search on the id field would require an average of <code>N/2 = 500,000</code> block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of <code>log2 1000000 = 19.93 = 20</code> block accesses. Instantly we can see this is a drastic improvement.</p>
<p>Now the <em>firstName</em> field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact <code>N = 1,000,000</code> block accesses. It is this situation that indexing aims to correct.</p>
<p>Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the <em>firstName</em> field is outlined below;</p>
<pre>
Field name Data type Size on disk
firstName Char(50) 50 bytes
(record pointer) Special 4 bytes
</pre>
<p><strong>Note</strong>: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.</p>
<p><em><strong>Example 2</strong></em> - <em>indexing</em></p>
<p>Given our sample database of <code>r = 5,000,000</code> records with an index record length of <code>R = 54</code> bytes and using the default block size <code>B = 1,024</code> bytes. The blocking factor of the index would be <code>bfr = (B/R) = 1024/54 = 18</code> records per disk block. The total number of blocks required to hold the index is <code>N = (r/bfr) = 5000000/18 = 277,778</code> blocks.</p>
<p>Now a search using the <em>firstName</em> field can utilize the index to increase performance. This allows for a binary search of the index with an average of <code>log2 277778 = 18.08 = 19</code> block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to <code>19 + 1 = 20</code> block accesses, a far cry from the 1,000,000 block accesses required to find a <em>firstName</em> match in the non-indexed table.</p>
<p><strong>When should it be used?</strong></p>
<p>Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.</p>
<p>Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.</p> | {
"question_id": 1108,
"question_date": "2008-08-04T10:07:12.673Z",
"question_score": 2810,
"tags": "sql|database|performance|indexing|database-indexes",
"answer_id": 1130,
"answer_date": "2008-08-04T10:41:04.620Z",
"answer_score": 4051
} |
Please answer the following Stack Overflow question:
Title: Find the current directory and file's directory
<p>How do I determine:</p>
<ol>
<li>the current directory (where I was in the terminal when I ran the Python script), and</li>
<li>where the Python file I am executing is?</li>
</ol> | <p>To get the full path to the directory a Python file is contained in, write this in that file:</p>
<pre><code>import os
dir_path = os.path.dirname(os.path.realpath(__file__))
</code></pre>
<p>(Note that the incantation above won't work if you've already used <code>os.chdir()</code> to change your current working directory, since the value of the <code>__file__</code> constant is relative to the current working directory and is not changed by an <code>os.chdir()</code> call.)</p>
<hr>
<p>To get the current working directory use </p>
<pre><code>import os
cwd = os.getcwd()
</code></pre>
<hr>
<p>Documentation references for the modules, constants and functions used above:</p>
<ul>
<li>The <a href="https://docs.python.org/library/os.html"><code>os</code></a> and <a href="https://docs.python.org/library/os.path.html#module-os.path"><code>os.path</code></a> modules.</li>
<li>The <a href="https://docs.python.org/reference/datamodel.html"><code>__file__</code></a> constant</li>
<li><a href="https://docs.python.org/library/os.path.html#os.path.realpath"><code>os.path.realpath(path)</code></a> (returns <em>"the canonical path of the specified filename, eliminating any symbolic links encountered in the path"</em>)</li>
<li><a href="https://docs.python.org/library/os.path.html#os.path.dirname"><code>os.path.dirname(path)</code></a> (returns <em>"the directory name of pathname <code>path</code>"</em>)</li>
<li><a href="https://docs.python.org/library/os.html#os.getcwd"><code>os.getcwd()</code></a> (returns <em>"a string representing the current working directory"</em>)</li>
<li><a href="https://docs.python.org/library/os.html#os.chdir"><code>os.chdir(path)</code></a> (<em>"change the current working directory to <code>path</code>"</em>)</li>
</ul> | {
"question_id": 5137497,
"question_date": "2011-02-28T01:51:21.120Z",
"question_score": 2802,
"tags": "python|directory",
"answer_id": 5137509,
"answer_date": "2011-02-28T01:54:18.703Z",
"answer_score": 4387
} |
Please answer the following Stack Overflow question:
Title: Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
<p>It is my understanding that the <code>range()</code> function, which is actually <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-range" rel="nofollow noreferrer">an object type in Python 3</a>, generates its contents on the fly, similar to a generator.</p>
<p>This being the case, I would have expected the following line to take an inordinate amount of time because, in order to determine whether 1 quadrillion is in the range, a quadrillion values would have to be generated:</p>
<pre><code>1_000_000_000_000_000 in range(1_000_000_000_000_001)
</code></pre>
<p>Furthermore: it seems that no matter how many zeroes I add on, the calculation more or less takes the same amount of time (basically instantaneous).</p>
<p>I have also tried things like this, but the calculation is still almost instant:</p>
<pre><code># count by tens
1_000_000_000_000_000_000_000 in range(0,1_000_000_000_000_000_000_001,10)
</code></pre>
<p>If I try to implement my own range function, the result is not so nice!</p>
<pre><code>def my_crappy_range(N):
i = 0
while i < N:
yield i
i += 1
return
</code></pre>
<p>What is the <code>range()</code> object doing under the hood that makes it so fast?</p>
<hr />
<p><a href="https://stackoverflow.com/a/30081318/2437514">Martijn Pieters's answer</a> was chosen for its completeness, but also see <a href="https://stackoverflow.com/a/30081894/2437514">abarnert's first answer</a> for a good discussion of what it means for <code>range</code> to be a full-fledged <em>sequence</em> in Python 3, and some information/warning regarding potential inconsistency for <code>__contains__</code> function optimization across Python implementations. <a href="https://stackoverflow.com/a/30088140/2437514">abarnert's other answer</a> goes into some more detail and provides links for those interested in the history behind the optimization in Python 3 (and lack of optimization of <code>xrange</code> in Python 2). Answers <a href="https://stackoverflow.com/a/30081467/2437514">by poke</a> and <a href="https://stackoverflow.com/a/30081470/2437514">by wim</a> provide the relevant C source code and explanations for those who are interested.</p> | <p>The Python 3 <code>range()</code> object doesn't produce numbers immediately; it is a smart <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence" rel="noreferrer">sequence object</a> that produces numbers <em>on demand</em>. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.</p>
<p>The object also implements the <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="noreferrer"><code>object.__contains__</code> hook</a>, and <em>calculates</em> if your number is part of its range. Calculating is a (near) constant time operation <sup>*</sup>. There is never a need to scan through all possible integers in the range.</p>
<p>From the <a href="https://docs.python.org/3/library/stdtypes.html#range" rel="noreferrer"><code>range()</code> object documentation</a>:</p>
<blockquote>
<p>The advantage of the <code>range</code> type over a regular <code>list</code> or <code>tuple</code> is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the <code>start</code>, <code>stop</code> and <code>step</code> values, calculating individual items and subranges as needed).</p>
</blockquote>
<p>So at a minimum, your <code>range()</code> object would do:</p>
<pre><code>class my_range:
def __init__(self, start, stop=None, step=1, /):
if stop is None:
start, stop = 0, start
self.start, self.stop, self.step = start, stop, step
if step < 0:
lo, hi, step = stop, start, -step
else:
lo, hi = start, stop
self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1
def __iter__(self):
current = self.start
if self.step < 0:
while current > self.stop:
yield current
current += self.step
else:
while current < self.stop:
yield current
current += self.step
def __len__(self):
return self.length
def __getitem__(self, i):
if i < 0:
i += self.length
if 0 <= i < self.length:
return self.start + i * self.step
raise IndexError('my_range object index out of range')
def __contains__(self, num):
if self.step < 0:
if not (self.stop < num <= self.start):
return False
else:
if not (self.start <= num < self.stop):
return False
return (num - self.start) % self.step == 0
</code></pre>
<p>This is still missing several things that a real <code>range()</code> supports (such as the <code>.index()</code> or <code>.count()</code> methods, hashing, equality testing, or slicing), but should give you an idea.</p>
<p>I also simplified the <code>__contains__</code> implementation to only focus on integer tests; if you give a real <code>range()</code> object a non-integer value (including subclasses of <code>int</code>), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original <a href="http://bugs.python.org/issue1766304" rel="noreferrer">Python issue</a> that implemented the containment test.</p>
<hr />
<p>* <em>Near</em> constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.</p> | {
"question_id": 30081275,
"question_date": "2015-05-06T15:32:43.060Z",
"question_score": 2801,
"tags": "python|performance|python-3.x|range|python-internals",
"answer_id": 30081318,
"answer_date": "2015-05-06T15:33:58.393Z",
"answer_score": 2858
} |
Please answer the following Stack Overflow question:
Title: Determine installed PowerShell version
<p>How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?</p> | <p>Use <code>$PSVersionTable.PSVersion</code> to determine the engine version. If the variable does not exist, it is safe to assume the engine is version <code>1.0</code>.</p>
<p>Note that <code>$Host.Version</code> and <code>(Get-Host).Version</code> are not reliable - they reflect
the version of the host only, not the engine. PowerGUI,
PowerShellPLUS, etc. are all hosting applications, and
they will set the host's version to reflect their product
version — which is entirely correct, but not what you're looking for.</p>
<pre><code>PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
</code></pre> | {
"question_id": 1825585,
"question_date": "2009-12-01T11:30:03.010Z",
"question_score": 2799,
"tags": "powershell|version",
"answer_id": 1825807,
"answer_date": "2009-12-01T12:12:38.760Z",
"answer_score": 3759
} |
Please answer the following Stack Overflow question:
Title: How do I change the author and committer name/email for multiple commits?
<p>How do I change the author for a range of commits?</p> | <blockquote>
<p>This answer uses <code>git-filter-branch</code>, for which <a href="https://git-scm.com/docs/git-filter-branch" rel="noreferrer">the docs</a> now give this warning:</p>
<p>git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as <a href="https://github.com/newren/git-filter-repo/" rel="noreferrer">git filter-repo</a>. If you still need to use git filter-branch, please carefully read <a href="https://git-scm.com/docs/git-filter-branch#SAFETY" rel="noreferrer">SAFETY</a> (and <a href="https://git-scm.com/docs/git-filter-branch#PERFORMANCE" rel="noreferrer">PERFORMANCE</a>) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.</p>
</blockquote>
<p>Changing the author (or committer) would require rewriting all of the history. If you're okay with that and think it's worth it then you should check out <a href="https://schacon.github.io/git/git-filter-branch.html" rel="noreferrer">git filter-branch</a>. The manual page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the <a href="https://schacon.github.io/git/git.html" rel="noreferrer">git manual page</a>.</p>
<p>Specifically, you can fix all the wrong author names and emails <strong>for all branches and tags</strong> with this command (source: <a href="https://help.github.com/articles/changing-author-info/" rel="noreferrer">GitHub help</a>):</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
</code></pre>
<p>For using alternative history filtering tool <a href="https://github.com/newren/git-filter-repo/" rel="noreferrer">git filter-repo</a>, you can first install it and construct a <code>git-mailmap</code> according to the format of <a href="https://htmlpreview.github.io/?https://raw.githubusercontent.com/newren/git-filter-repo/docs/html/gitmailmap.html" rel="noreferrer">gitmailmap</a>.</p>
<pre><code>Proper Name <[email protected]> Commit Name <[email protected]>
</code></pre>
<p>And then run filter-repo with the created mailmap:</p>
<pre><code>git filter-repo --mailmap git-mailmap
</code></pre> | {
"question_id": 750172,
"question_date": "2009-04-15T03:09:24.207Z",
"question_score": 2799,
"tags": "git|version-control|git-filter-branch|git-rewrite-history",
"answer_id": 750182,
"answer_date": "2009-04-15T03:16:42.690Z",
"answer_score": 1491
} |
Please answer the following Stack Overflow question:
Title: ssh "permissions are too open"
<p>I get the following error from ssh:</p>
<pre><code>Permissions 0777 for '/Users/username/.ssh/id_rsa' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
</code></pre>
<p>What permissions should I give to the id_rsa file?</p> | <p>The keys need to be read-writable only by you:</p>
<pre><code>chmod 600 ~/.ssh/id_rsa
</code></pre>
<p>Alternatively, the keys can be only readable by you (this also blocks your write access):</p>
<pre><code>chmod 400 ~/.ssh/id_rsa
</code></pre>
<p><code>600</code> appears to be better in most cases, because you don't need to change file permissions later to edit it. (See the comments for more nuances)</p>
<p>The relevant portion from the manpage (<code>man ssh</code>)</p>
<blockquote>
<pre><code> ~/.ssh/id_rsa
Contains the private key for authentication. These files contain sensitive
data and should be readable by the user but not
accessible by others (read/write/execute). ssh will simply ignore a private
key file if it is
accessible by others. It is possible to specify a
passphrase when generating the key which will be used to encrypt the sensitive
part of this file using 3DES.
~/.ssh/identity.pub
~/.ssh/id_dsa.pub
~/.ssh/id_ecdsa.pub
~/.ssh/id_rsa.pub
Contains the public key for authentication. These files are not sensitive and
can (but need not) be readable by anyone.
</code></pre>
</blockquote> | {
"question_id": 9270734,
"question_date": "2012-02-14T02:02:31.860Z",
"question_score": 2795,
"tags": "permissions|ssh",
"answer_id": 9270753,
"answer_date": "2012-02-14T02:05:01.030Z",
"answer_score": 4651
} |
Please answer the following Stack Overflow question:
Title: Find the version of an installed npm package
<p>How can I find the version of an installed Node.js or npm <strong>package</strong>?</p>
<p>This prints the version of npm itself:</p>
<pre><code>npm -v <package-name>
</code></pre>
<p>This prints a cryptic error:</p>
<pre><code>npm version <package-name>
</code></pre>
<p>This prints the package version <em>on the registry</em> (i.e., the latest version available):</p>
<pre><code>npm view <package-name> version
</code></pre>
<p>How do I get the <strong>installed version</strong>?</p> | <p>Use <code>npm list</code> for local packages or <code>npm list -g</code> for globally installed packages.</p>
<p>You can find the version of a specific package by passing its name as an argument. For example, <code>npm list grunt</code> will result in:</p>
<pre class="lang-none prettyprint-override"><code>projectName@projectVersion /path/to/project/folder
└── [email protected]
</code></pre>
<p>Alternatively, you can just run <code>npm list</code> without passing a package name as an argument to see the versions of all your packages:</p>
<pre class="lang-none prettyprint-override"><code>├─┬ [email protected]
│ └── [email protected]
├── [email protected]
├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ └── [email protected]
└── [email protected]
</code></pre>
<p>You can also add <code>--depth=0</code> argument to list installed packages without their dependencies.</p> | {
"question_id": 10972176,
"question_date": "2012-06-10T20:36:27.693Z",
"question_score": 2790,
"tags": "node.js|package|npm",
"answer_id": 10986132,
"answer_date": "2012-06-11T19:13:26.997Z",
"answer_score": 3193
} |
Please answer the following Stack Overflow question:
Title: Flash CS4 refuses to let go
<p>I have a Flash project, and it has many source files. I have a fairly heavily-used class, call it Jenine. I recently (and, perhaps, callously) relocated Jenine from one namespace to another. I thought we were ready - I thought it was time. The new Jenine was better in every way - she had lost some code bloat, she had decoupled herself from a few vestigial class relationships, and she had finally come home to the namespace that she had always secretly known in her heart was the one she truly belonged to. She was among her own kind.</p>
<p>Unfortunately, Flash would have none of that. Perhaps it had formed an attachment. Perhaps it didn't <em>want</em> Jenine to be decoupled. Either way, it clung to the old, perfect version of Jenine in its memory. It refused to move on. It ignored her (function) calls. It tried to forget her new, public interfaces. Instead, every instance of Jenine that it constructed was always a copy of the old version, down to its classpath:</p>
<pre><code>var jenineInstance:Jenine = new Jenine();
trace( getQualifiedClassName(jenineInstance));
// Should print: com.newnamespace.subspace::Jenine
// Prints: com.oldnamespace.subspace::Jenine
// Ah, young love!
</code></pre>
<p>We fought. I'm not proud of some of the things I said or did. In the end, in a towering fit of rage, I deleted all references of Jenine completely. She was utterly, completely erased from the system. My cursor fell upon the "Empty Trash" menu option like the cold lid of a casket.</p>
<p>I don't think Flash ever recovered. To this day it still clings to the memory of Jenine. Her old, imperfect definitions still float through my project like abandoned ghosts. Whenever I force Flash to compile, it still lovingly inserts her into my movie, nestling her definition in amongst the other, living classes, like a small shrine. I wonder if they can see her.</p>
<p>Flash and I don't really talk anymore. I write my code, it compiles it. There's a new girl in town named Summer who looks almost identical to Jenine, as if someone had just copied her source-code wholesale into a new class, but Flash hasn't shown any interest. Most days it just mopes around and writes bad poetry in my comments when it thinks I'm not looking.</p>
<p>I hope no one else has had a similar experience, that this is just a singular, painful ripple in the horrifying dark lagoon that is the Flash code-base. Does anyone have any idea how to erase whatever cache the compiler is using?</p> | <p>Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:</p>
<pre class="lang-none prettyprint-override"><code>C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso
</code></pre>
<p>On a Mac, the directory structure is similar in <code>/Users/username/Library/Application Support/</code> </p>
<hr>
<p>You can remove those files by hand, or in Flash you can select <code>Control->Delete ASO files</code> to remove them.</p> | {
"question_id": 2193953,
"question_date": "2010-02-03T17:32:15.457Z",
"question_score": 2780,
"tags": "flash|caching|flash-cs4",
"answer_id": 2194530,
"answer_date": "2010-02-03T18:49:29.277Z",
"answer_score": 706
} |
Please answer the following Stack Overflow question:
Title: How can I create an executable JAR with dependencies using Maven?
<p>I want to package my project in a single executable JAR for distribution.</p>
<p>How can I make a Maven project package all dependency JARs into my output JAR?</p> | <pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>and you run it with</p>
<pre class="lang-xml prettyprint-override"><code>mvn clean compile assembly:single
</code></pre>
<p><em>Compile goal should be added before assembly:single or otherwise the code on your own project is not included.</em></p>
<p>See more details in comments.</p>
<hr />
<p>Commonly this goal is tied to a build phase to execute automatically. This ensures the JAR is built when executing <code>mvn install</code> or performing a deployment/release.</p>
<pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre> | {
"question_id": 574594,
"question_date": "2009-02-22T08:43:45.460Z",
"question_score": 2778,
"tags": "java|maven-2|build-process|build-automation|executable-jar",
"answer_id": 574650,
"answer_date": "2009-02-22T09:31:28.857Z",
"answer_score": 2722
} |
Please answer the following Stack Overflow question:
Title: How can I prevent SQL injection in PHP?
<p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p>
<pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
</code></pre>
<p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p>
<pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
</code></pre>
<p>What can be done to prevent this from happening?</p> | <p>The <em>correct</em> way to avoid SQL injection attacks, no matter which database you use, is to <strong>separate the data from SQL</strong>, so that data stays data and will <strong>never be interpreted</strong> as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't <em>fully</em> understand the details, you should always <strong>use prepared statements and parameterized queries.</strong> These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.</p>
<p>You basically have two options to achieve this:</p>
<ol>
<li><p>Using <a href="http://php.net/manual/en/book.pdo.php" rel="noreferrer"><strong>PDO</strong></a> (for any supported database driver):</p>
<pre class="lang-php prettyprint-override"><code>$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}
</code></pre>
</li>
<li><p>Using <a href="http://php.net/manual/en/book.mysqli.php" rel="noreferrer"><strong>MySQLi</strong></a> (for MySQL):</p>
<pre class="lang-php prettyprint-override"><code>$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
</code></pre>
</li>
</ol>
<p>If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, <code>pg_prepare()</code> and <code>pg_execute()</code> for PostgreSQL). PDO is the universal option.</p>
<hr />
<h2>Correctly setting up the connection</h2>
<h4>PDO</h4>
<p>Note that when using <strong>PDO</strong> to access a MySQL database <em>real</em> prepared statements are <strong>not used by default</strong>. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using <strong>PDO</strong> is:</p>
<pre class="lang-php prettyprint-override"><code>$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
</code></pre>
<p>In the above example, the error mode isn't strictly necessary, <strong>but it is advised to add it</strong>. This way PDO will inform you of all MySQL errors by means of throwing the <code>PDOException</code>.</p>
<p>What is <strong>mandatory</strong>, however, is the first <code>setAttribute()</code> line, which tells PDO to disable emulated prepared statements and use <em>real</em> prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).</p>
<p>Although you can set the <code>charset</code> in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">silently ignored the charset parameter</a> in the DSN.</p>
<h4>Mysqli</h4>
<p>For mysqli we have to follow the same routine:</p>
<pre class="lang-php prettyprint-override"><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
</code></pre>
<hr />
<h2>Explanation</h2>
<p>The SQL statement you pass to <code>prepare</code> is parsed and compiled by the database server. By specifying parameters (either a <code>?</code> or a named parameter like <code>:name</code> in the example above) you tell the database engine where you want to filter on. Then when you call <code>execute</code>, the prepared statement is combined with the parameter values you specify.</p>
<p>The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.</p>
<p>Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the <code>$name</code> variable contains <code>'Sarah'; DELETE FROM employees</code> the result would simply be a search for the string <code>"'Sarah'; DELETE FROM employees"</code>, and you will not end up with <a href="http://xkcd.com/327/" rel="noreferrer">an empty table</a>.</p>
<p>Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.</p>
<p>Oh, and since you asked about how to do it for an insert, here's an example (using PDO):</p>
<pre class="lang-php prettyprint-override"><code>$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
</code></pre>
<hr />
<h2>Can prepared statements be used for dynamic queries?</h2>
<p>While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.</p>
<p>For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.</p>
<pre><code>// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}
</code></pre> | {
"question_id": 60174,
"question_date": "2008-09-12T23:55:00.900Z",
"question_score": 2773,
"tags": "php|mysql|sql|security|sql-injection",
"answer_id": 60496,
"answer_date": "2008-09-13T12:30:26.950Z",
"answer_score": 9502
} |
Please answer the following Stack Overflow question:
Title: Encode URL in JavaScript?
<p>How do you safely encode a URL using JavaScript such that it can be put into a GET string?</p>
<pre><code>var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
</code></pre>
<p>I assume that you need to encode the <code>myUrl</code> variable on that second line?</p> | <p>Check out the built-in function <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="noreferrer">encodeURIComponent(str)</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI" rel="noreferrer">encodeURI(str)</a>.<br />
In your case, this should work:</p>
<pre><code>var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
</code></pre> | {
"question_id": 332872,
"question_date": "2008-12-02T02:37:08.457Z",
"question_score": 2770,
"tags": "javascript|url|encode|urlencode",
"answer_id": 332888,
"answer_date": "2008-12-02T02:43:57.100Z",
"answer_score": 3094
} |
Please answer the following Stack Overflow question:
Title: From inside of a Docker container, how do I connect to the localhost of the machine?
<p>So I have a Nginx running inside a docker container, I have a mysql running on the host system, I want to connect to the MySql from within my container. MySql is only binding to the localhost device.</p>
<p>Is there any way to connect to this MySql or any other program on localhost from within this docker container?</p>
<p>This question is different from "How to get the IP address of the docker host from inside a docker container" due to the fact that the IP address of the docker host could be the public IP or the private IP in the network which may or may not be reachable from within the docker container (I mean public IP if hosted at AWS or something). Even if you have the IP address of the docker host it does not mean you can connect to docker host from within the container given that IP address as your Docker network may be overlay, host, bridge, macvlan, none etc which restricts the reachability of that IP address.</p> | <p><strong>Edit:</strong></p>
<p>If you are using <a href="https://docs.docker.com/docker-for-mac/networking/#there-is-no-docker0-bridge-on-macos#i-want-to-connect-from-a-container-to-a-service-on-the-host" rel="noreferrer">Docker-for-mac</a> or <a href="https://docs.docker.com/docker-for-windows/networking/#there-is-no-docker0-bridge-on-windows#i-want-to-connect-from-a-container-to-a-service-on-the-host" rel="noreferrer">Docker-for-Windows</a> 18.03+, just connect to your mysql service using the host <code>host.docker.internal</code> (instead of the <code>127.0.0.1</code> in your connection string).</p>
<p>If you are using Docker-for-Linux 20.10.0+, you can also use the host <code>host.docker.internal</code> <strong>if</strong> you started your Docker container with the <code>--add-host host.docker.internal:host-gateway</code> option.</p>
<p>Otherwise, read below</p>
<hr />
<h2>TLDR</h2>
<p>Use <code>--network="host"</code> in your <code>docker run</code> command, then <code>127.0.0.1</code> in your docker container will point to your docker host.</p>
<p>Note: This mode only works on Docker for Linux, <a href="https://docs.docker.com/network/host/" rel="noreferrer">per the documentation</a>.</p>
<hr />
<h1>Note on docker container networking modes</h1>
<p>Docker offers <a href="https://docs.docker.com/engine/reference/run/#network-settings" rel="noreferrer">different networking modes</a> when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.</p>
<h2>docker run --network="bridge" (default)</h2>
<p>Docker creates a bridge named <code>docker0</code> by default. Both the docker host and the docker containers have an IP address on that bridge.</p>
<p>on the Docker host, type <code>sudo ip addr show docker0</code> you will have an output looking like:</p>
<pre><code>[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::5484:7aff:fefe:9799/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>So here my docker host has the IP address <code>172.17.42.1</code> on the <code>docker0</code> network interface.</p>
<p>Now start a new container and get a shell on it: <code>docker run --rm -it ubuntu:trusty bash</code> and within the container type <code>ip addr show eth0</code> to discover how its main network interface is set up:</p>
<pre><code>root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
inet 172.17.1.192/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>Here my container has the IP address <code>172.17.1.192</code>. Now look at the routing table:</p>
<pre><code>root@e77f6a1b3740:/# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.17.42.1 0.0.0.0 UG 0 0 0 eth0
172.17.0.0 * 255.255.0.0 U 0 0 0 eth0
</code></pre>
<p>So the IP Address of the docker host <code>172.17.42.1</code> is set as the default route and is accessible from your container.</p>
<pre><code>root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms
</code></pre>
<h2>docker run --network="host"</h2>
<p>Alternatively you can run a docker container with <a href="http://docs.docker.com/engine/reference/run/#network-host" rel="noreferrer">network settings set to <code>host</code></a>. Such a container will share the network stack with the docker host and from the container point of view, <code>localhost</code> (or <code>127.0.0.1</code>) will refer to the docker host.</p>
<p>Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the <a href="https://docs.docker.com/engine/reference/run/#expose-incoming-ports" rel="noreferrer"><code>-p</code> or <code>-P</code> <code>docker run</code> option</a>.</p>
<p>IP config on my docker host:</p>
<pre><code>[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>and from a docker container in <strong>host</strong> mode:</p>
<pre><code>[vagrant@docker:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
</code></pre>
<p>As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.</p>
<hr />
<h1>Connecting to MySQL from containers</h1>
<h2>bridge mode</h2>
<p>To access MySQL running on the docker host from containers in <em>bridge mode</em>, you need to make sure the MySQL service is listening for connections on the <code>172.17.42.1</code> IP address.</p>
<p>To do so, make sure you have either <code>bind-address = 172.17.42.1</code> or <code>bind-address = 0.0.0.0</code> in your MySQL config file (my.cnf).</p>
<p>If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :</p>
<pre><code>export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')
</code></pre>
<p>then in your application, use the <code>DOCKER_HOST_IP</code> environment variable to open the connection to MySQL.</p>
<p><strong>Note:</strong> if you use <code>bind-address = 0.0.0.0</code> your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.</p>
<p><strong>Note 2:</strong> if you use <code>bind-address = 172.17.42.1</code> your MySQL server won't listen for connections made to <code>127.0.0.1</code>. Processes running on the docker host that would want to connect to MySQL would have to use the <code>172.17.42.1</code> IP address.</p>
<h2>host mode</h2>
<p>To access MySQL running on the docker host from containers in <em>host mode</em>, you can keep <code>bind-address = 127.0.0.1</code> in your MySQL configuration and all you need to do is to connect to <code>127.0.0.1</code> from your containers:</p>
<pre><code>[vagrant@docker:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
</code></pre>
<p><strong>note:</strong> Do use <code>mysql -h 127.0.0.1</code> and not <code>mysql -h localhost</code>; otherwise the MySQL client would try to connect using a unix socket.</p> | {
"question_id": 24319662,
"question_date": "2014-06-20T03:54:16.893Z",
"question_score": 2746,
"tags": "docker|docker-networking",
"answer_id": 24326540,
"answer_date": "2014-06-20T11:46:51.397Z",
"answer_score": 3758
} |
Please answer the following Stack Overflow question:
Title: How to change the commit author for a single commit?
<p>I want to change the author of one specific commit in the history. It's not the latest commit.</p>
<p><strong>Related:</strong> <a href="https://stackoverflow.com/questions/750172/how-do-i-change-the-author-of-a-commit-in-git">How do I change the author and committer name/email for multiple commits?</a></p> | <p>Interactive rebase off of a point earlier in the history than the commit you need to modify (<code>git rebase -i <earliercommit></code>). In the list of commits being rebased, change the text from <code>pick</code> to <code>edit</code> next to the hash of the one you want to modify. Then when git prompts you to change the commit, use this:</p>
<pre><code>git commit --amend --author="Author Name <[email protected]>" --no-edit
</code></pre>
<hr>
<p>For example, if your commit history is <code>A-B-C-D-E-F</code> with <code>F</code> as <code>HEAD</code>, and you want to change the author of <code>C</code> and <code>D</code>, then you would...</p>
<ol>
<li>Specify <code>git rebase -i B</code> (<a href="https://help.github.com/articles/about-git-rebase/#an-example-of-using-git-rebase" rel="noreferrer">here is an example of what you will see after executing the <code>git rebase -i B</code> command</a>)
<ul>
<li>if you need to edit <code>A</code>, use <code>git rebase -i --root</code></li>
</ul></li>
<li>Change the lines for both <code>C</code> and <code>D</code> from <code>pick</code> to <code>edit</code></li>
<li>Exit the editor (for vim, this would be pressing Esc and then typing <code>:wq</code>).</li>
<li>Once the rebase started, it would first pause at <code>C</code></li>
<li>You would <code>git commit --amend --author="Author Name <[email protected]>"</code></li>
<li>Then <code>git rebase --continue</code></li>
<li>It would pause again at <code>D</code></li>
<li>Then you would <code>git commit --amend --author="Author Name <[email protected]>"</code> again</li>
<li><code>git rebase --continue</code></li>
<li>The rebase would complete.</li>
<li>Use <code>git push -f</code> to update your origin with the updated commits.</li>
</ol> | {
"question_id": 3042437,
"question_date": "2010-06-15T04:00:08.730Z",
"question_score": 2741,
"tags": "git|git-commit",
"answer_id": 3042512,
"answer_date": "2010-06-15T04:31:46.400Z",
"answer_score": 4586
} |
Please answer the following Stack Overflow question:
Title: Ignore files that have already been committed to a Git repository
<p>I have an already initialized Git repository that I added a <code>.gitignore</code> file to. How can I refresh the file index so the files I want ignored get ignored?</p> | <p>To untrack a <em>single</em> file that has already been added/initialized to your repository, <em>i.e.</em>, stop tracking the file but not delete it from your system use: <code>git rm --cached filename</code></p>
<p>To untrack <em>every</em> file that is now in your <code>.gitignore</code>:</p>
<p><strong>First commit any outstanding code changes</strong>, and then, run this command:</p>
<pre><code>git rm -r --cached .
</code></pre>
<p>This removes any changed files from the <em>index</em>(staging area), then just run:</p>
<pre><code>git add .
</code></pre>
<p>Commit it:</p>
<pre><code>git commit -m ".gitignore is now working"
</code></pre>
<hr />
<p>To undo <code>git rm --cached filename</code>, use <code>git add filename</code>.</p>
<blockquote>
<p>Make sure to commit all your important changes before running <code>git add .</code>
Otherwise, you will lose any changes to other files.</p>
</blockquote>
<blockquote>
<p>Please be careful, when you push this to a repository and pull from somewhere else into a state where those files are still tracked, the files will be DELETED</p>
</blockquote> | {
"question_id": 1139762,
"question_date": "2009-07-16T19:26:35.580Z",
"question_score": 2727,
"tags": "git|caching|version-control|gitignore|git-rm",
"answer_id": 1139797,
"answer_date": "2009-07-16T19:32:50.543Z",
"answer_score": 4541
} |
Please answer the following Stack Overflow question:
Title: How do I get a YouTube video thumbnail from the YouTube API?
<p>If I have a YouTube video URL, is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?</p> | <p>Each YouTube video has four generated images. They are predictably formatted as follows:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
</code></pre>
<p>The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (i.e., one of <code>1.jpg</code>, <code>2.jpg</code>, <code>3.jpg</code>) is:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
</code></pre>
<p>For the high quality version of the thumbnail use a URL similar to this:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
</code></pre>
<p>There is also a medium quality version of the thumbnail, using a URL similar to the HQ:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
</code></pre>
<p>For the standard definition version of the thumbnail, use a URL similar to this:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
</code></pre>
<p>For the maximum resolution version of the thumbnail use a URL similar to this:</p>
<pre class="lang-none prettyprint-override"><code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
</code></pre>
<p>All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname <code>i3.ytimg.com</code> works in place of <code>img.youtube.com</code> in the example URLs above.</p>
<p>Alternatively, you can use the <a href="https://developers.google.com/youtube/v3/" rel="noreferrer">YouTube Data API (v3)</a> to get thumbnail images.</p> | {
"question_id": 2068344,
"question_date": "2010-01-14T23:34:24.750Z",
"question_score": 2712,
"tags": "php|curl|youtube|youtube-api|youtube-data-api",
"answer_id": 2068371,
"answer_date": "2010-01-14T23:40:25.970Z",
"answer_score": 5201
} |
Please answer the following Stack Overflow question:
Title: How do I install pip on Windows?
<p><a href="https://pip.pypa.io/en/stable/" rel="noreferrer"><code>pip</code></a> is a replacement for <a href="http://setuptools.readthedocs.io/en/latest/easy_install.html" rel="noreferrer"><code>easy_install</code></a>. But should I install <code>pip</code> using <code>easy_install</code> on Windows? Is there a better way?</p> | <h2>Python 2.7.9+ and 3.4+</h2>
<p>Good news! <a href="https://docs.python.org/3/whatsnew/3.4.html" rel="noreferrer">Python 3.4</a> (released March 2014) and <a href="https://docs.python.org/2/whatsnew/2.7.html#pep-477-backport-ensurepip-pep-453-to-python-2-7" rel="noreferrer">Python 2.7.9</a> (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29" rel="noreferrer">Ruby</a>, <a href="http://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a>, <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a>, <a href="http://en.wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a>, <a href="http://en.wikipedia.org/wiki/Go_%28programming_language%29" rel="noreferrer">Go</a>—almost every other contemporary language with a majority open-source community. Thank you, Python.</p>
<p>If you do find that pip is not available when using Python 3.4+ or Python 2.7.9+, simply execute e.g.:</p>
<pre><code>py -3 -m ensurepip
</code></pre>
<p>Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this <a href="https://stackoverflow.com/questions/2436731/does-python-have-a-package-module-management-system/13445719#13445719">in the Stack Overflow question <em>Does Python have a package/module management system?</em></a>.</p>
<p>And, alas for everyone using Python 2.7.8 or earlier (a sizable portion of the community). There's no plan to ship Pip to you. Manual instructions follow.</p>
<h2>Python 2 ≤ 2.7.8 and Python 3 ≤ 3.3</h2>
<p>Flying in the face of its <a href="http://www.python.org/about/" rel="noreferrer">'batteries included'</a> motto, Python ships without a package manager. To make matters worse, Pip was—until recently—ironically difficult to install.</p>
<h3>Official instructions</h3>
<p>Per <a href="https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip" rel="noreferrer">https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip</a>:</p>
<p>Download <a href="https://bootstrap.pypa.io/get-pip.py" rel="noreferrer"><code>get-pip.py</code></a>, being careful to save it as a <code>.py</code> file rather than <code>.txt</code>. Then, run it from the command prompt:</p>
<pre><code>python get-pip.py
</code></pre>
<p>You possibly need an administrator command prompt to do this. Follow <em><a href="http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx" rel="noreferrer">Start a Command Prompt as an Administrator</a></em> (Microsoft TechNet).</p>
<p>This installs the pip package, which (in Windows) contains ...\Scripts\pip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of 'Alternative Instructions' for adding it to your PATH,</p>
<h3>Alternative instructions</h3>
<p>The official documentation tells users to install Pip and each of its dependencies from source. That's tedious for the experienced and prohibitively difficult for newbies.</p>
<p>For our sake, Christoph Gohlke prepares Windows installers (<code>.msi</code>) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:</p>
<ol>
<li><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools" rel="noreferrer">Install setuptools</a></li>
<li><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip" rel="noreferrer">Install pip</a></li>
</ol>
<p>For me, this installed Pip at <code>C:\Python27\Scripts\pip.exe</code>. Find <code>pip.exe</code> on your computer, then add its folder (for example, <code>C:\Python27\Scripts</code>) to your path (Start / Edit environment variables). Now you should be able to run <code>pip</code> from the command line. Try installing a package:</p>
<pre><code>pip install httpie
</code></pre>
<p>There you go (hopefully)! Solutions for common problems are given below:</p>
<h3>Proxy problems</h3>
<p>If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables <a href="http://docs.python.org/2/library/urllib.html" rel="noreferrer"><code>http_proxy</code> and <code>https_proxy</code></a>. Most Python applications (and other free software) respect these. Example syntax:</p>
<pre><code>http://proxy_url:port
http://username:password@proxy_url:port
</code></pre>
<p>If you're really unlucky, your proxy might be a Microsoft <a href="https://en.wikipedia.org/wiki/NT_LAN_Manager" rel="noreferrer">NTLM</a> proxy. Free software can't cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. <a href="http://cntlm.sourceforge.net/" rel="noreferrer">http://cntlm.sourceforge.net/</a></p>
<h3>Unable to find vcvarsall.bat</h3>
<p>Python modules can be partly written in C or C++. Pip tries to compile from source. If you don't have a C/C++ compiler installed and configured, you'll see this cryptic error message.</p>
<blockquote>
<p>Error: Unable to find vcvarsall.bat</p>
</blockquote>
<p>You can fix that by <a href="https://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat">installing a C++ compiler</a> such as <a href="http://en.wikipedia.org/wiki/MinGW" rel="noreferrer">MinGW</a> or <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B#32-bit_versions" rel="noreferrer">Visual C++</a>. Microsoft actually ships one specifically for use with Python. Or try <em><a href="http://aka.ms/vcpython27" rel="noreferrer">Microsoft Visual C++ Compiler for Python 2.7</a></em>.</p>
<p>Often though it's easier to check <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="noreferrer">Christoph's site</a> for your package.</p> | {
"question_id": 4750806,
"question_date": "2011-01-20T18:08:59.100Z",
"question_score": 2703,
"tags": "pip",
"answer_id": 12476379,
"answer_date": "2012-09-18T11:45:33.753Z",
"answer_score": 1924
} |
Please answer the following Stack Overflow question:
Title: Is there an equivalent of 'which' on the Windows command line?
<p>As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name.</p>
<p>Is there an equivalent to the UNIX command 'which'?</p>
<p>On UNIX, <code>which command</code> prints the full path of the given command to easily find and repair these shadowing problems.</p> | <p>Windows Server 2003 and later (i.e. anything after Windows XP 32 bit) provide the <code>where.exe</code> program which does some of what <code>which</code> does, though it matches all types of files, not just executable commands. (It does not match built-in shell commands like <code>cd</code>.) It will even accept wildcards, so <code>where nt*</code> finds all files in your <code>%PATH%</code> and current directory whose names start with <code>nt</code>.</p>
<p>Try <code>where /?</code> for help.</p>
<p>Note that Windows PowerShell defines <code>where</code> as an alias for <a href="http://technet.microsoft.com/en-us/library/hh849715.aspx" rel="noreferrer">the <code>Where-Object</code> cmdlet</a>, so if you want <code>where.exe</code>, you need to type the full name instead of omitting the <code>.exe</code> extension. Alternatively, you can set an alias for it:</p>
<pre><code>Set-Alias which where.exe
</code></pre>
<p><strong>Update:</strong> Using <code>Get-Command</code> (alias: <code>gcm</code>) is recommended since it's native to PS and will get all command types: aliases, cmdlets, executables, and functions. Example:</p>
<pre><code>gcm notepad*
</code></pre> | {
"question_id": 304319,
"question_date": "2008-11-20T04:19:35.380Z",
"question_score": 2699,
"tags": "windows|command-line|path-variables",
"answer_id": 304447,
"answer_date": "2008-11-20T05:52:50.717Z",
"answer_score": 2887
} |
Please answer the following Stack Overflow question:
Title: How do I make Git ignore file mode (chmod) changes?
<p>I have a project in which I have to change the mode of files with <code>chmod</code> to 777 while developing, but which should not change in the main repo. </p>
<p>Git picks up on <code>chmod -R 777 .</code> and marks all files as changed. Is there a way to make Git ignore mode changes that have been made to files?</p> | <p>Try:</p>
<pre><code>git config core.fileMode false
</code></pre>
<p>From <a href="https://www.kernel.org/pub/software/scm/git/docs/git-config.html" rel="noreferrer">git-config(1)</a>:</p>
<blockquote>
<pre><code>core.fileMode
Tells Git if the executable bit of files in the working tree
is to be honored.
Some filesystems lose the executable bit when a file that is
marked as executable is checked out, or checks out a
non-executable file with executable bit on. git-clone(1)
or git-init(1) probe the filesystem to see if it handles the
executable bit correctly and this variable is automatically
set as necessary.
A repository, however, may be on a filesystem that handles
the filemode correctly, and this variable is set to true when
created, but later may be made accessible from another
environment that loses the filemode (e.g. exporting ext4
via CIFS mount, visiting a Cygwin created repository with Git
for Windows or Eclipse). In such a case it may be necessary
to set this variable to false. See git-update-index(1).
The default is true (when core.filemode is not specified
in the config file).
</code></pre>
</blockquote>
<p>The <code>-c</code> flag can be used to set this option for one-off commands:</p>
<pre><code>git -c core.fileMode=false diff
</code></pre>
<p>Typing the <code>-c core.fileMode=false</code> can be bothersome and so you can set this flag for all git repos or just for one git repo:</p>
<pre><code># this will set your the flag for your user for all git repos (modifies `$HOME/.gitconfig`)
git config --global core.fileMode false
# this will set the flag for one git repo (modifies `$current_git_repo/.git/config`)
git config core.fileMode false
</code></pre>
<p>Additionally, <code>git clone</code> and <code>git init</code> explicitly set <code>core.fileMode</code> to <code>true</code> in the repo config as discussed in <a href="https://stackoverflow.com/questions/30392318/git-global-core-filemode-false-overridden-locally-on-clone">Git global core.fileMode false overridden locally on clone</a></p>
<h2>Warning</h2>
<p><code>core.fileMode</code> is not the best practice and should be used carefully. This setting only covers the executable bit of mode and never the read/write bits. In many cases you think you need this setting because you did something like <code>chmod -R 777</code>, making all your files executable. But in most projects <strong>most files don't need and should not be executable for security reasons</strong>.</p>
<p>The proper way to solve this kind of situation is to handle folder and file permission separately, with something like:</p>
<pre class="lang-sh prettyprint-override"><code>find . -type d -exec chmod a+rwx {} \; # Make folders traversable and read/write
find . -type f -exec chmod a+rw {} \; # Make files read/write
</code></pre>
<p>If you do that, you'll never need to use <code>core.fileMode</code>, except in very rare environment.</p> | {
"question_id": 1580596,
"question_date": "2009-10-16T21:43:38.243Z",
"question_score": 2696,
"tags": "git|ignore|chmod",
"answer_id": 1580644,
"answer_date": "2009-10-16T21:53:40.683Z",
"answer_score": 4498
} |
Please answer the following Stack Overflow question:
Title: Do I cast the result of malloc?
<p>In <a href="http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array">this question</a>, someone suggested in a <a href="http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array#comment388297_571961">comment</a> that I should <em><strong>not</strong></em> cast the result of <code>malloc</code>. i.e., I should do this:</p>
<pre><code>int *sieve = malloc(sizeof(*sieve) * length);
</code></pre>
<p>rather than:</p>
<pre><code>int *sieve = (int *) malloc(sizeof(*sieve) * length);
</code></pre>
<p>Why would this be the case?</p> | <h3>TL;DR</h3>
<pre><code>int *sieve = (int *) malloc(sizeof(int) * length);
</code></pre>
<p>has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:</p>
<pre><code>int *sieve = malloc(sizeof *sieve * length);
</code></pre>
<h3>Long version</h3>
<p><strong>No</strong>; you <em>don't</em> cast the result, since:</p>
<ul>
<li>It is unnecessary, as <code>void *</code> is automatically and safely promoted to any other pointer type in this case.</li>
<li>It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).</li>
<li>It makes you repeat yourself, which is generally bad.</li>
<li>It can hide an error if you forgot to include <code><stdlib.h></code>. This can cause crashes (or, worse, <em>not</em> cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return <code>int</code>.</li>
</ul>
<p>As a clarification, note that I said "you don't cast", not "you don't <em>need</em> to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.</p>
<p>Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.</p>
<p>To add further, your code needlessly repeats the type information (<code>int</code>) which can cause errors. It's better to de-reference the pointer being used to store the return value, to "lock" the two together:</p>
<pre><code>int *sieve = malloc(length * sizeof *sieve);
</code></pre>
<p>This also moves the <code>length</code> to the front for increased visibility, and drops the redundant parentheses with <code>sizeof</code>; they <em>are only needed</em> when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: <code>sizeof</code> is not a function! :)</p>
<hr />
<p>While moving <code>length</code> to the front <em>may</em> increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:</p>
<pre><code>int *sieve = malloc(sizeof *sieve * length);
</code></pre>
<p>Since keeping the <code>sizeof</code> first, in this case, ensures multiplication is done with at least <code>size_t</code> math.</p>
<p>Compare: <code>malloc(sizeof *sieve * length * width)</code> vs. <code>malloc(length * width * sizeof *sieve)</code> the second may overflow the <code>length * width</code> when <code>width</code> and <code>length</code> are smaller types than <code>size_t</code>.</p> | {
"question_id": 605845,
"question_date": "2009-03-03T10:13:02.940Z",
"question_score": 2696,
"tags": "c|malloc|casting",
"answer_id": 605858,
"answer_date": "2009-03-03T10:17:53.817Z",
"answer_score": 2451
} |
Please answer the following Stack Overflow question:
Title: How can I get query string values in JavaScript?
<p>Is there a plugin-less way of retrieving <a href="http://en.wikipedia.org/wiki/Query_string" rel="nofollow noreferrer">query string</a> values via jQuery (or without)? </p>
<p>If so, how? If not, is there a plugin which can do so?</p> | <p><strong>Update: Jan-2022</strong></p>
<p>Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="noreferrer"><code>Proxy()</code></a> is <a href="https://jsben.ch/MeP5G" rel="noreferrer">faster</a> than using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries" rel="noreferrer"><code>Object.fromEntries()</code></a> and better supported</p>
<pre><code>const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
</code></pre>
<p><strong>Update: June-2021</strong></p>
<p>For a specific case when you need all query params:</p>
<pre><code>const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
</code></pre>
<p><strong>Update: Sep-2018</strong></p>
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility" rel="noreferrer">URLSearchParams</a> which is simple and has <a href="https://caniuse.com/urlsearchparams" rel="noreferrer">decent (but not complete) browser support</a>.</p>
<pre><code>const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
</code></pre>
<p><strong>Original</strong></p>
<p>You don't need jQuery for that purpose. You can use just some pure JavaScript:</p>
<pre><code>function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code>// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
</code></pre>
<p>NOTE: If a parameter is present several times (<code>?foo=lorem&foo=ipsum</code>), you will get the first value (<code>lorem</code>). There is no standard about this and usages vary, see for example this question: <a href="https://stackoverflow.com/questions/1746507/authoritative-position-of-duplicate-http-get-query-keys">Authoritative position of duplicate HTTP GET query keys</a>.</p>
<p>NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, <a href="https://stackoverflow.com/questions/3939715/case-insensitive-regex-in-javascript">add 'i' modifier to RegExp</a></p>
<p>NOTE: If you're getting a no-useless-escape eslint error, you can replace <code>name = name.replace(/[\[\]]/g, '\\$&');</code> with <code>name = name.replace(/[[\]]/g, '\\$&')</code>.</p>
<hr />
<p>This is an update based on the new <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer">URLSearchParams specs</a> to achieve the same result more succinctly. See answer titled "<a href="https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#12151322">URLSearchParams</a>" below.</p> | {
"question_id": 901115,
"question_date": "2009-05-23T08:10:48.453Z",
"question_score": 2695,
"tags": "javascript|url|plugins|query-string",
"answer_id": 901144,
"answer_date": "2009-05-23T08:35:46.217Z",
"answer_score": 9900
} |
Please answer the following Stack Overflow question:
Title: How can I transition height: 0; to height: auto; using CSS?
<p>I am trying to make a <code><ul></code> slide down using CSS transitions.</p>
<p>The <code><ul></code> starts off at <code>height: 0;</code>. On hover, the height is set to <code>height:auto;</code>. However, this is causing it to simply appear, <em>not</em> transition,</p>
<p>If I do it from <code>height: 40px;</code> to <code>height: auto;</code>, then it will slide up to <code>height: 0;</code>, and then suddenly jump to the correct height.</p>
<p>How else could I do this without using JavaScript?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#child0 {
height: 0;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent0:hover #child0 {
height: auto;
}
#child40 {
height: 40px;
overflow: hidden;
background-color: #dedede;
-moz-transition: height 1s ease;
-webkit-transition: height 1s ease;
-o-transition: height 1s ease;
transition: height 1s ease;
}
#parent40:hover #child40 {
height: auto;
}
h1 {
font-weight: bold;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>The only difference between the two snippets of CSS is one has height: 0, the other height: 40.
<hr>
<div id="parent0">
<h1>Hover me (height: 0)</h1>
<div id="child0">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div>
<hr>
<div id="parent40">
<h1>Hover me (height: 40)</h1>
<div id="child40">Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>Some content
<br>
</div>
</div></code></pre>
</div>
</div>
</p> | <p>Use <code>max-height</code> in the transition and not <code>height</code>. And set a value on <code>max-height</code> to something bigger than your box will ever get.</p>
<p>See <a href="http://jsfiddle.net/thechrisjordan/3Fc7D/23/" rel="noreferrer">JSFiddle demo</a> provided by Chris Jordan in another <a href="https://stackoverflow.com/a/20226830/18706">answer</a> here.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu #list {
max-height: 0;
transition: max-height 0.15s ease-out;
overflow: hidden;
background: #d5d5d5;
}
#menu:hover #list {
max-height: 500px;
transition: max-height 0.25s ease-in;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">
<a>hover me</a>
<ul id="list">
<!-- Create a bunch, or not a bunch, of li's to see the timing. -->
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 3508605,
"question_date": "2010-08-18T02:50:35.293Z",
"question_score": 2686,
"tags": "css|css-transitions",
"answer_id": 8331169,
"answer_date": "2011-11-30T18:42:56.333Z",
"answer_score": 3418
} |
Please answer the following Stack Overflow question:
Title: How do I refresh a page using JavaScript?
<p>How do I refresh a page using JavaScript?</p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/reload" rel="noreferrer"><code>location.reload()</code></a>.</p>
<p>For example, to reload whenever an element with <code>id="something"</code> is clicked:</p>
<pre><code>$('#something').click(function() {
location.reload();
});
</code></pre>
<p>The <code>reload()</code> function takes an optional parameter that can be set to <code>true</code> to force a reload from the server rather than the cache. The parameter defaults to <code>false</code>, so by default the page may reload from the browser's cache.</p> | {
"question_id": 5404839,
"question_date": "2011-03-23T11:55:31.870Z",
"question_score": 2681,
"tags": "javascript|jquery|refresh|reload",
"answer_id": 5404869,
"answer_date": "2011-03-23T11:57:51.837Z",
"answer_score": 4113
} |
Please answer the following Stack Overflow question:
Title: Check if a given key already exists in a dictionary
<p>I wanted to test if a key exists in a dictionary before updating the value for the key.
I wrote the following code:</p>
<pre><code>if 'key1' in dict.keys():
print "blah"
else:
print "boo"
</code></pre>
<p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p> | <p><a href="https://docs.python.org/reference/expressions.html#membership-test-operations" rel="noreferrer"><code>in</code></a> tests for the existence of a key in a <a href="https://docs.python.org/library/stdtypes.html#dict" rel="noreferrer"><code>dict</code></a>:</p>
<pre><code>d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
</code></pre>
<hr />
<p>Use <a href="https://docs.python.org/library/stdtypes.html#dict.get" rel="noreferrer"><code>dict.get()</code></a> to provide a default value when the key does not exist:</p>
<pre><code>d = {}
for i in range(10):
d[i] = d.get(i, 0) + 1
</code></pre>
<hr />
<p>To provide a default value for <em>every</em> key, either use <a href="https://docs.python.org/library/stdtypes.html#dict.setdefault" rel="noreferrer"><code>dict.setdefault()</code></a> on each assignment:</p>
<pre><code>d = {}
for i in range(10):
d[i] = d.setdefault(i, 0) + 1
</code></pre>
<p>or use <a href="https://docs.python.org/library/collections.html#collections.defaultdict" rel="noreferrer"><code>defaultdict</code></a> from the <a href="https://docs.python.org/library/collections.html" rel="noreferrer"><code>collections</code></a> module:</p>
<pre><code>from collections import defaultdict
d = defaultdict(int)
for i in range(10):
d[i] += 1
</code></pre> | {
"question_id": 1602934,
"question_date": "2009-10-21T19:05:09.543Z",
"question_score": 2679,
"tags": "python|dictionary",
"answer_id": 1602964,
"answer_date": "2009-10-21T19:10:21.600Z",
"answer_score": 4894
} |
Please answer the following Stack Overflow question:
Title: Why shouldn't I use mysql_* functions in PHP?
<p>What are the technical reasons for why one shouldn't use <code>mysql_*</code> functions? (e.g. <code>mysql_query()</code>, <code>mysql_connect()</code> or <code>mysql_real_escape_string()</code>)?</p>
<p>Why should I use something else even if they work on my site?</p>
<p>If they don't work on my site, why do I get errors like </p>
<blockquote>
<p>Warning: mysql_connect(): No such file or directory</p>
</blockquote> | <p>The MySQL extension:</p>
<ul>
<li>Is not under active development</li>
<li>Is <strong>officially <a href="https://wiki.php.net/rfc/mysql_deprecation" rel="noreferrer">deprecated</a></strong> as of PHP 5.5 (released June 2013).</li>
<li>Has been <strong><a href="https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7#extmysql" rel="noreferrer">removed</a> entirely</strong> as of PHP 7.0 (released December 2015)
<ul>
<li>This means that as of <a href="https://www.php.net/eol.php" rel="noreferrer">31 Dec 2018</a> it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, you are using a version which doesn't get security problems fixed.</li>
</ul></li>
<li>Lacks an OO interface</li>
<li>Doesn't support:
<ul>
<li>Non-blocking, asynchronous queries</li>
<li><strong><a href="http://php.net/manual/en/mysqli.quickstart.prepared-statements.php" rel="noreferrer">Prepared statements</a> or parameterized queries</strong></li>
<li>Stored procedures</li>
<li>Multiple Statements</li>
<li>Transactions</li>
<li>The "new" password authentication method (on by default in MySQL 5.6; required in 5.7)</li>
<li>Any of the new functionality in MySQL 5.1 or later</li>
</ul></li>
</ul>
<p>Since it is deprecated, using it makes your code less future proof. </p>
<p>Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.</p>
<p>See <a href="http://php.net/manual/en/mysqlinfo.api.choosing.php" rel="noreferrer"><strong>the comparison of SQL extensions</strong></a>.</p> | {
"question_id": 12859942,
"question_date": "2012-10-12T13:18:39.307Z",
"question_score": 2672,
"tags": "php|mysql",
"answer_id": 12860046,
"answer_date": "2012-10-12T13:23:43.763Z",
"answer_score": 2208
} |
Please answer the following Stack Overflow question:
Title: Open a URL in a new tab (and not a new window)
<p>I'm trying to open a <a href="https://en.wikipedia.org/wiki/URL" rel="noreferrer">URL</a> in a new tab, as opposed to a popup window.</p>
<p>I've seen related questions where the responses would look something like:</p>
<pre><code>window.open(url,'_blank');
window.open(url);
</code></pre>
<p>But none of them worked for me, the browser still tried to open a popup window.</p> | <p>Nothing an author can do can choose to open in a new tab instead of a new window; it is a <em>user preference</em>. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)</p>
<p>CSS3 proposed <a href="https://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224/#target-new" rel="noreferrer">target-new</a>, but <a href="https://www.w3.org/TR/2014/NOTE-css3-hyperlinks-20141014/" rel="noreferrer">the specification was abandoned</a>.</p>
<p><a href="https://stackoverflow.com/a/64718494/19068">The <strong>reverse</strong> is not true</a>; by specifying certain window features for the window in the third argument of <code>window.open()</code>, you can trigger a new window when the preference is for tabs.</p> | {
"question_id": 4907843,
"question_date": "2011-02-05T15:52:13.953Z",
"question_score": 2670,
"tags": "javascript|tabs|href",
"answer_id": 4907854,
"answer_date": "2011-02-05T15:53:41.147Z",
"answer_score": 1110
} |
Please answer the following Stack Overflow question:
Title: What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?
<p><a href="https://docs.npmjs.com/files/package.json" rel="noreferrer">This documentation</a> answers my question very poorly. I didn't understand those explanations. Can someone say in simpler words? Maybe with examples if it's hard to choose simple words?</p>
<p><strong>EDIT</strong> also added <code>peerDependencies</code>, which is closely related and might cause confusion.</p> | <p>Summary of important behavior differences:</p>
<ul>
<li><p><a href="https://github.com/npm/npm/blob/2e3776bf5676bc24fec6239a3420f377fe98acde/doc/files/package.json.md#dependencies" rel="noreferrer"><code>dependencies</code></a> are installed on both:</p>
<ul>
<li><code>npm install</code> from a directory that contains <code>package.json</code></li>
<li><code>npm install $package</code> on any other directory</li>
</ul>
</li>
<li><p><a href="https://github.com/npm/npm/blob/2e3776bf5676bc24fec6239a3420f377fe98acde/doc/files/package.json.md#devdependencies" rel="noreferrer"><code>devDependencies</code></a> are:</p>
<ul>
<li>also installed on <code>npm install</code> on a directory that contains <code>package.json</code>, unless you pass the <code>--production</code> flag (go upvote <a href="https://stackoverflow.com/a/31229205/895245">Gayan Charith's answer</a>), or if the <code>NODE_ENV=production</code> environment variable is set</li>
<li>not installed on <code>npm install "$package"</code> on any other directory, unless you give it the <code>--dev</code> option.</li>
<li>are not installed transitively.</li>
</ul>
</li>
<li><p><a href="https://github.com/npm/npm/blob/2e3776bf5676bc24fec6239a3420f377fe98acde/doc/files/package.json.md#peerdependencies" rel="noreferrer"><code>peerDependencies</code></a>:</p>
<ul>
<li>before 3.0: are always installed if missing, and raise an error if multiple incompatible versions of the dependency would be used by different dependencies.</li>
<li><a href="http://blog.npmjs.org/post/110924823920/npm-weekly-5" rel="noreferrer">expected to start on 3.0</a> (untested): give a warning if missing on <code>npm install</code>, and you have to solve the dependency yourself manually. When running, if the dependency is missing, you get an error (mentioned by <a href="https://stackoverflow.com/users/1997767/nextgentech">@nextgentech</a>) This explains it nicely: <a href="https://flaviocopes.com/npm-peer-dependencies/" rel="noreferrer">https://flaviocopes.com/npm-peer-dependencies/</a></li>
<li><a href="https://github.blog/2021-02-02-npm-7-is-now-generally-available/" rel="noreferrer">in version 7</a> peerDependencies are automatically installed unless an upstream dependency conflict is present that cannot be automatically resolved</li>
</ul>
</li>
<li><p>Transitivity (mentioned by <a href="https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencies/22004559#comment57650997_22004559">Ben Hutchison</a>):</p>
<ul>
<li><p><code>dependencies</code> are installed transitively: if A requires B, and B requires C, then C gets installed, otherwise, B could not work, and neither would A.</p>
</li>
<li><p><code>devDependencies</code> is not installed transitively. E.g. we don't need to test B to test A, so B's testing dependencies can be left out.</p>
</li>
</ul>
</li>
</ul>
<p>Related options not discussed here:</p>
<ul>
<li><code>bundledDependencies</code> which is discussed on the following question: <em><a href="https://stackoverflow.com/questions/11207638/advantages-of-bundleddependencies-over-normal-dependencies-in-npm?lq=1">Advantages of bundledDependencies over normal dependencies in npm</a></em></li>
<li><a href="https://docs.npmjs.com/files/package.json#optionaldependencies" rel="noreferrer"><code>optionalDependencies</code></a> (mentioned <a href="https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencies/22004559#comment62749434_18875674">by Aidan Feldman</a>)</li>
</ul>
<h2>devDependencies</h2>
<p><code>dependencies</code> are required to run, <code>devDependencies</code> only to develop, e.g.: unit tests, CoffeeScript to JavaScript transpilation, minification, ...</p>
<p>If you are going to develop a package, you download it (e.g. via <code>git clone</code>), go to its root which contains <code>package.json</code>, and run:</p>
<pre><code>npm install
</code></pre>
<p>Since you have the actual source, it is clear that you want to develop it, so by default, both <code>dependencies</code> (since you must, of course, run to develop) and <code>devDependency</code> dependencies are also installed.</p>
<p>If however, you are only an end user who just wants to install a package to use it, you will do from any directory:</p>
<pre><code>npm install "$package"
</code></pre>
<p>In that case, you normally don't want the development dependencies, so you just get what is needed to use the package: <code>dependencies</code>.</p>
<p>If you really want to install development packages in that case, you can set the <code>dev</code> configuration option to <code>true</code>, possibly from the command line as:</p>
<pre><code>npm install "$package" --dev
</code></pre>
<p>The option is <code>false</code> by default since this is a much less common case.</p>
<h2>peerDependencies</h2>
<p>(Tested before 3.0)</p>
<p>Source: <a href="https://nodejs.org/en/blog/npm/peer-dependencies/" rel="noreferrer">https://nodejs.org/en/blog/npm/peer-dependencies/</a></p>
<p>With regular dependencies, you can have multiple versions of the dependency: it's simply installed inside the <code>node_modules</code> of the dependency.</p>
<p>E.g. if <code>dependency1</code> and <code>dependency2</code> both depend on <code>dependency3</code> at different versions the project tree will look like:</p>
<pre><code>root/node_modules/
|
+- dependency1/node_modules/
| |
| +- dependency3 v1.0/
|
|
+- dependency2/node_modules/
|
+- dependency3 v2.0/
</code></pre>
<p>Plugins, however, are packages that normally don't require the other package, which is called the <em>host</em> in this context. Instead:</p>
<ul>
<li>plugins are required <em>by the host</em></li>
<li>plugins offer a standard interface that the host expects to find</li>
<li>only the host will be called directly by the user, so there must be a single version of it.</li>
</ul>
<p>E.g. if <code>dependency1</code> and <code>dependency2</code> peer depend on <code>dependency3</code>, the project tree will look like:</p>
<pre><code>root/node_modules/
|
+- dependency1/
|
+- dependency2/
|
+- dependency3 v1.0/
</code></pre>
<p>This happens even though you never mention <code>dependency3</code> in your <code>package.json</code> file.</p>
<p>I think this is an instance of the <a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">Inversion of Control</a> design pattern.</p>
<p>A prototypical example of peer dependencies is Grunt, the host, and its plugins.</p>
<p>For example, on a Grunt plugin like <a href="https://github.com/gruntjs/grunt-contrib-uglify" rel="noreferrer">https://github.com/gruntjs/grunt-contrib-uglify</a>, you will see that:</p>
<ul>
<li><code>grunt</code> is a <code>peer-dependency</code></li>
<li>the only <code>require('grunt')</code> is under <code>tests/</code>: it's not actually used by the program.</li>
</ul>
<p>Then, when the user will use a plugin, he will implicitly require the plugin from the <code>Gruntfile</code> by adding a <code>grunt.loadNpmTasks('grunt-contrib-uglify')</code> line, but it's <code>grunt</code> that the user will call directly.</p>
<p>This would not work then if each plugin required a different Grunt version.</p>
<h2>Manual</h2>
<p>I think the documentation answers the question quite well, maybe you are just not familiar enough with node / other package managers. I probably only understand it because I know a bit about Ruby bundler.</p>
<p>The key line is:</p>
<blockquote>
<p>These things will be installed when doing npm link or npm install from the root of a package and can be managed like any other npm configuration parameter. See npm-config(7) for more on the topic.</p>
</blockquote>
<p>And then under npm-config(7) find <code>dev</code>:</p>
<pre><code>Default: false
Type: Boolean
Install dev-dependencies along with packages.
</code></pre> | {
"question_id": 18875674,
"question_date": "2013-09-18T14:57:06.917Z",
"question_score": 2666,
"tags": "node.js|npm|dependencies|package.json",
"answer_id": 22004559,
"answer_date": "2014-02-25T04:25:31.627Z",
"answer_score": 3010
} |
Please answer the following Stack Overflow question:
Title: Renaming column names in Pandas
<p>I want to change the column labels of a Pandas DataFrame from</p>
<pre><code>['$a', '$b', '$c', '$d', '$e']
</code></pre>
<p>to</p>
<pre><code>['a', 'b', 'c', 'd', 'e']
</code></pre> | <p>Just assign it to the <code>.columns</code> attribute:</p>
<pre><code>>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20
>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20
</code></pre> | {
"question_id": 11346283,
"question_date": "2012-07-05T14:21:15.090Z",
"question_score": 2665,
"tags": "python|pandas|replace|dataframe|rename",
"answer_id": 11346337,
"answer_date": "2012-07-05T14:23:27.910Z",
"answer_score": 2448
} |
Please answer the following Stack Overflow question:
Title: How can I recursively find all files in current and subfolders based on wildcard matching?
<p>How can I recursively find all files in current and subfolders based on wildcard matching?</p> | <p>Use <a href="http://linux.die.net/man/1/find" rel="noreferrer"><code>find</code></a>:</p>
<pre><code>find . -name "foo*"
</code></pre>
<p><code>find</code> needs a starting point, so the <code>.</code> (dot) points to the current directory.</p> | {
"question_id": 5905054,
"question_date": "2011-05-05T23:01:34.770Z",
"question_score": 2663,
"tags": "linux|shell",
"answer_id": 5905066,
"answer_date": "2011-05-05T23:03:37.033Z",
"answer_score": 3807
} |
Please answer the following Stack Overflow question:
Title: How can I fix 'android.os.NetworkOnMainThreadException'?
<p>I got an error while running my Android project for RssReader. </p>
<p>Code:</p>
<pre><code>URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
</code></pre>
<p>And it shows the below error:</p>
<pre><code>android.os.NetworkOnMainThreadException
</code></pre>
<p>How can I fix this issue?</p> | <p><strong>NOTE : AsyncTask was deprecated in API level 30.<br />
<a href="https://developer.android.com/reference/android/os/AsyncTask" rel="noreferrer">AsyncTask | Android Developers</a></strong></p>
<p>This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="noreferrer"><code>AsyncTask</code></a>:</p>
<pre><code>class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
} finally {
is.close();
}
}
protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
</code></pre>
<p>How to execute the task:</p>
<p>In <code>MainActivity.java</code> file you can add this line within your <code>oncreate()</code> method</p>
<pre><code>new RetrieveFeedTask().execute(urlToRssFeed);
</code></pre>
<p>Don't forget to add this to <code>AndroidManifest.xml</code> file:</p>
<pre><code><uses-permission android:name="android.permission.INTERNET"/>
</code></pre> | {
"question_id": 6343166,
"question_date": "2011-06-14T12:02:00.203Z",
"question_score": 2659,
"tags": "java|android|android-networking|networkonmainthread",
"answer_id": 6343299,
"answer_date": "2011-06-14T12:15:05.223Z",
"answer_score": 2660
} |
Please answer the following Stack Overflow question:
Title: How do I check if a string contains a specific word?
<p>Consider:</p>
<pre><code>$a = 'How are you?';
if ($a contains 'are')
echo 'true';
</code></pre>
<p>Suppose I have the code above, what is the correct way to write the statement <code>if ($a contains 'are')</code>?</p> | <p><strong>Now with PHP 8 you can do this using <a href="https://www.php.net/manual/en/function.str-contains" rel="noreferrer">str_contains</a>:</strong></p>
<pre><code>if (str_contains('How are you', 'are')) {
echo 'true';
}
</code></pre>
<p><a href="https://wiki.php.net/rfc/str_contains" rel="noreferrer">RFC</a></p>
<p><strong>Before PHP 8</strong></p>
<p>You can use the <a href="http://php.net/manual/en/function.strpos.php" rel="noreferrer"><code>strpos()</code></a> function which is used to find the occurrence of one string inside another one:</p>
<pre><code>$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
</code></pre>
<p>Note that the use of <code>!== false</code> is deliberate (neither <code>!= false</code> nor <code>=== true</code> will return the desired result); <code>strpos()</code> returns either the offset at which the needle string begins in the haystack string, or the boolean <code>false</code> if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like <code>!strpos($a, 'are')</code>.</p> | {
"question_id": 4366730,
"question_date": "2010-12-06T13:14:05.093Z",
"question_score": 2658,
"tags": "php|string|substring|contains|string-matching",
"answer_id": 4366748,
"answer_date": "2010-12-06T13:15:58.250Z",
"answer_score": 7857
} |
Please answer the following Stack Overflow question:
Title: How do I parse a string to a float or int?
<ul>
<li>How can I convert a <code>str</code> to <code>float</code>?
<pre><code>"545.2222" → 545.2222
</code></pre>
</li>
<li>How can I convert a <code>str</code> to <code>int</code>?
<pre><code>"31" → 31
</code></pre>
</li>
</ul>
<hr />
<p><sub>For the reverse, see <a href="https://stackoverflow.com/questions/961632">Convert integer to string in Python</a> and <a href="https://stackoverflow.com/questions/1317558">Converting a float to a string without rounding it</a>.</sub></p>
<p><sub>Please instead use <a href="https://stackoverflow.com/questions/20449427">How can I read inputs as numbers?</a> to close duplicate questions where OP received a string <em>from user input</em> and immediately wants to convert it, or was hoping for <code>input</code> (in 3.x) to convert the type automatically.</sub></p> | <pre><code>>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
</code></pre> | {
"question_id": 379906,
"question_date": "2008-12-19T01:52:26.213Z",
"question_score": 2642,
"tags": "python|parsing|floating-point|type-conversion|integer",
"answer_id": 379910,
"answer_date": "2008-12-19T01:54:51.420Z",
"answer_score": 3006
} |
Please answer the following Stack Overflow question:
Title: How do I vertically center text with CSS?
<p>I have a <code><div></code> element which contains text and I want to align the contents of this <code><div></code> vertically center.</p>
<p>Here is my <code><div></code> style:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
Lorem ipsum dolor sit
</div></code></pre>
</div>
</div>
</p>
<p>What is the best way to achieve this goal?</p> | <p>You can try this basic approach:</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 {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
Hello World!
</div></code></pre>
</div>
</div>
</p>
<p>It only works for a single line of text though, because we set the line's height to the same height as the containing box element.</p>
<hr>
<h2>A more versatile approach</h2>
<p>This is another way to align text vertically. This solution will work for a single line and multiple lines of text, but it still requires a fixed height container:</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 {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>Hello World!</span>
</div></code></pre>
</div>
</div>
</p>
<p>The CSS just sizes the <code><div></code>, vertically center aligns the <code><span></code> by setting the <code><div></code>'s line-height equal to its height, and makes the <code><span></code> an inline-block with <code>vertical-align: middle</code>. Then it sets the line-height back to normal for the <code><span></code>, so its contents will flow naturally inside the block.</p>
<hr>
<h2>Simulating table display</h2>
<p>And here is another option, which may not work on older <a href="http://caniuse.com/css-table" rel="noreferrer">browsers that don't support <code>display: table</code> and <code>display: table-cell</code></a> (basically just Internet Explorer 7). Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
display: table;
height: 100px;
width: 100%;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: table-cell;
vertical-align: middle;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>Hello World!</span>
</div></code></pre>
</div>
</div>
</p>
<hr>
<h2>Using absolute positioning</h2>
<p>This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, <em><a href="http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/" rel="noreferrer">Absolute Horizontal And Vertical Centering In CSS</a></em>.</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 {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100%;
border: 2px dashed #f69c55;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>Hello World!</span>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 8865458,
"question_date": "2012-01-14T21:25:10.070Z",
"question_score": 2642,
"tags": "html|css|vertical-alignment",
"answer_id": 8865463,
"answer_date": "2012-01-14T21:26:33.427Z",
"answer_score": 3212
} |
Please answer the following Stack Overflow question:
Title: How can I remove a key from a Python dictionary?
<p>Is there a one-line way of deleting a key from a dictionary without raising a <code>KeyError</code>?</p>
<pre><code>if 'key' in my_dict:
del my_dict['key']
</code></pre> | <p>To delete a key regardless of whether it is in the dictionary, use the two-argument form of <a href="http://docs.python.org/library/stdtypes.html#dict.pop" rel="noreferrer"><code>dict.pop()</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>my_dict.pop('key', None)
</code></pre>
<p>This will return <code>my_dict[key]</code> if <code>key</code> exists in the dictionary, and <code>None</code> otherwise. If the second parameter is not specified (i.e. <code>my_dict.pop('key')</code>) and <code>key</code> does not exist, a <code>KeyError</code> is raised.</p>
<p>To delete a key that is guaranteed to exist, you can also use:</p>
<pre><code>del my_dict['key']
</code></pre>
<p>This will raise a <code>KeyError</code> if the key is not in the dictionary.</p> | {
"question_id": 11277432,
"question_date": "2012-06-30T20:27:59.470Z",
"question_score": 2635,
"tags": "python|dictionary|unset",
"answer_id": 11277439,
"answer_date": "2012-06-30T20:29:18.237Z",
"answer_score": 4225
} |
Please answer the following Stack Overflow question:
Title: How do I split a string on a delimiter in Bash?
<p>I have this string stored in a variable:</p>
<pre><code>IN="[email protected];[email protected]"
</code></pre>
<p>Now I would like to split the strings by <code>;</code> delimiter so that I have:</p>
<pre><code>ADDR1="[email protected]"
ADDR2="[email protected]"
</code></pre>
<p>I don't necessarily need the <code>ADDR1</code> and <code>ADDR2</code> variables. If they are elements of an array that's even better.</p>
<hr>
<p>After suggestions from the answers below, I ended up with the following which is what I was after:</p>
<pre><code>#!/usr/bin/env bash
IN="[email protected];[email protected]"
mails=$(echo $IN | tr ";" "\n")
for addr in $mails
do
echo "> [$addr]"
done
</code></pre>
<p>Output:</p>
<pre><code>> [[email protected]]
> [[email protected]]
</code></pre>
<p>There was a solution involving setting <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">Internal_field_separator</a> (IFS) to <code>;</code>. I am not sure what happened with that answer, how do you reset <code>IFS</code> back to default?</p>
<p>RE: <code>IFS</code> solution, I tried this and it works, I keep the old <code>IFS</code> and then restore it:</p>
<pre><code>IN="[email protected];[email protected]"
OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
echo "> [$x]"
done
IFS=$OIFS
</code></pre>
<p>BTW, when I tried </p>
<pre><code>mails2=($IN)
</code></pre>
<p>I only got the first string when printing it in loop, without brackets around <code>$IN</code> it works.</p> | <p>You can set the <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">internal field separator</a> (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to <code>IFS</code> only takes place to that single command's environment (to <code>read</code> ). It then parses the input according to the <code>IFS</code> variable value into an array, which we can then iterate over.</p>
<p>This example will parse one line of items separated by <code>;</code>, pushing it into an array:</p>
<pre><code>IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
# process "$i"
done
</code></pre>
<p>This other example is for processing the whole content of <code>$IN</code>, each time one line of input separated by <code>;</code>:</p>
<pre><code>while IFS=';' read -ra ADDR; do
for i in "${ADDR[@]}"; do
# process "$i"
done
done <<< "$IN"
</code></pre> | {
"question_id": 918886,
"question_date": "2009-05-28T02:03:43.983Z",
"question_score": 2632,
"tags": "bash|shell|split|scripting",
"answer_id": 918931,
"answer_date": "2009-05-28T02:23:27.017Z",
"answer_score": 1557
} |
Please answer the following Stack Overflow question:
Title: Can (a== 1 && a ==2 && a==3) ever evaluate to true?
<blockquote>
<p><strong>Moderator note:</strong> Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.</p>
</blockquote>
<p>Is it ever possible that <code>(a== 1 && a ==2 && a==3)</code> could evaluate to <code>true</code> in JavaScript?</p>
<p>This is an interview question asked by a major tech company. It happened two weeks back, but I'm still trying to find the answer. I know we never write such code in our day-to-day job, but I'm curious.</p> | <p>If you take advantage of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using" rel="noreferrer">how <code>==</code> works</a>, you could simply create an object with a custom <code>toString</code> (or <code>valueOf</code>) function that changes what it returns each time it is used such that it satisfies all three conditions.</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 a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}</code></pre>
</div>
</div>
</p>
<hr>
<p>The reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling <code>valueOf</code> if it is callable, and failing that, it will call <code>toString</code>. I used <code>toString</code> in this case simply because it's what came to mind, <code>valueOf</code> would make more sense. If I instead returned a string from <code>toString</code>, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.</p> | {
"question_id": 48270127,
"question_date": "2018-01-15T20:20:47.787Z",
"question_score": 2630,
"tags": "javascript|ecmascript-6",
"answer_id": 48270314,
"answer_date": "2018-01-15T20:35:15.337Z",
"answer_score": 3457
} |
Please answer the following Stack Overflow question:
Title: Homebrew install specific version of formula?
<p>How do I install a specific version of a formula in homebrew? For example, postgresql-8.4.4 instead of the latest 9.0.</p> | <p><strong>TLDR:</strong> <code>brew install [email protected]</code> See <a href="https://stackoverflow.com/a/9832084/561309">answer below</a> for more details.</p>
<hr>
<p>*(<em>I’ve re-edited my answer to give a more thorough workflow for installing/using older software versions with homebrew. Feel free to add a note if you found the old version better.</em>)</p>
<p>Let’s start with the simplest case:</p>
<h2>1) Check, whether the version is already installed (but not activated)</h2>
<p>When homebrew installs a new formula, it puts it in a versioned directory like <code>/usr/local/Cellar/postgresql/9.3.1</code>. Only symbolic links to this folder are then installed globally. In principle, this makes it pretty easy to switch between two installed versions. (*)</p>
<p>If you have been using homebrew for longer and never removed older versions (using, for example <code>brew cleanup</code>), chances are that some older version of your program may still be around. If you want to simply activate that previous version, <code>brew switch</code> is the easiest way to do this.</p>
<p>Check with <code>brew info postgresql</code> (or <code>brew switch postgresql <TAB></code>) whether the older version is installed:</p>
<pre><code>$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M)
Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M) *
Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more
</code></pre>
<p>We see that some older version is already installed. We may activate it using <code>brew switch</code>:</p>
<pre><code>$ brew switch postgresql 9.1.5
Cleaning /usr/local/Cellar/postgresql/9.1.5
Cleaning /usr/local/Cellar/postgresql/9.3.2
384 links created for /usr/local/Cellar/postgresql/9.1.5
</code></pre>
<p>Let’s double-check what is activated:</p>
<pre><code>$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M) *
Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M)
Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more
</code></pre>
<p>Note that the star <code>*</code> has moved to the newly activated version</p>
<p>(*) <em>Please note that <code>brew switch</code> only works as long as all dependencies of the older version are still around. In some cases, a rebuild of the older version may become necessary. Therefore, using <code>brew switch</code> is mostly useful when one wants to switch between two versions not too far apart.</em></p>
<h2>2) Check, whether the version is available as a tap</h2>
<p>Especially for larger software projects, it is very probably that there is a high enough demand for several (potentially API incompatible) major versions of a certain piece of software. As of March 2012, <a href="https://github.com/Homebrew/homebrew/wiki/Homebrew-0.9" rel="noreferrer">Homebrew 0.9</a> provides a mechanism for this: <code>brew tap</code> & the <a href="https://github.com/Homebrew/homebrew-versions" rel="noreferrer">homebrew versions</a> repository.</p>
<p>That versions repository may include backports of older versions for several formulae. (Mostly only the large and famous ones, but of course they’ll also have several formulae for postgresql.)</p>
<p><code>brew search postgresql</code> will show you where to look:</p>
<pre><code>$ brew search postgresql
postgresql
homebrew/versions/postgresql8 homebrew/versions/postgresql91
homebrew/versions/postgresql9 homebrew/versions/postgresql92
</code></pre>
<p>We can simply install it by typing</p>
<pre><code>$ brew install homebrew/versions/postgresql8
Cloning into '/usr/local/Library/Taps/homebrew-versions'...
remote: Counting objects: 1563, done.
remote: Compressing objects: 100% (943/943), done.
remote: Total 1563 (delta 864), reused 1272 (delta 620)
Receiving objects: 100% (1563/1563), 422.83 KiB | 339.00 KiB/s, done.
Resolving deltas: 100% (864/864), done.
Checking connectivity... done.
Tapped 125 formula
==> Downloading http://ftp.postgresql.org/pub/source/v8.4.19/postgresql-8.4.19.tar.bz2
# …
</code></pre>
<p>Note that this has automatically <em>tapped</em> the <code>homebrew/versions</code> tap. (Check with <code>brew tap</code>, remove with <code>brew untap homebrew/versions</code>.) The following would have been equivalent:</p>
<pre><code>$ brew tap homebrew/versions
$ brew install postgresql8
</code></pre>
<p>As long as the backported version formulae stay up-to-date, this approach is probably the best way to deal with older software.</p>
<h2>3) Try some formula from the past</h2>
<p>The following approaches are listed mostly for completeness. Both try to resurrect some undead formula from the brew repository. Due to changed dependencies, API changes in the formula spec or simply a change in the download URL, things may or may not work.</p>
<p>Since the whole formula directory is a git repository, one can install specific versions using plain git commands. However, we need to find a way to get to a commit where the old version was available.</p>
<p><strong>a) historic times</strong></p>
<p>Between <strong>August 2011 and October 2014</strong>, homebrew had a <code>brew versions</code> command, which spat out all available versions with their respective SHA hashes. As of October 2014, you have to do a <code>brew tap homebrew/boneyard</code> before you can use it. As the name of the tap suggests, you should probably only do this as a last resort.</p>
<p>E.g.</p>
<pre><code>$ brew versions postgresql
Warning: brew-versions is unsupported and may be removed soon.
Please use the homebrew-versions tap instead:
https://github.com/Homebrew/homebrew-versions
9.3.2 git checkout 3c86d2b Library/Formula/postgresql.rb
9.3.1 git checkout a267a3e Library/Formula/postgresql.rb
9.3.0 git checkout ae59e09 Library/Formula/postgresql.rb
9.2.4 git checkout e3ac215 Library/Formula/postgresql.rb
9.2.3 git checkout c80b37c Library/Formula/postgresql.rb
9.2.2 git checkout 9076baa Library/Formula/postgresql.rb
9.2.1 git checkout 5825f62 Library/Formula/postgresql.rb
9.2.0 git checkout 2f6cbc6 Library/Formula/postgresql.rb
9.1.5 git checkout 6b8d25f Library/Formula/postgresql.rb
9.1.4 git checkout c40c7bf Library/Formula/postgresql.rb
9.1.3 git checkout 05c7954 Library/Formula/postgresql.rb
9.1.2 git checkout dfcc838 Library/Formula/postgresql.rb
9.1.1 git checkout 4ef8fb0 Library/Formula/postgresql.rb
9.0.4 git checkout 2accac4 Library/Formula/postgresql.rb
9.0.3 git checkout b782d9d Library/Formula/postgresql.rb
</code></pre>
<p>As you can see, it advises against using it. Homebrew spits out all versions it can find with its internal heuristic and shows you a way to retrieve the old formulae. Let’s try it.</p>
<pre><code># First, go to the homebrew base directory
$ cd $( brew --prefix )
# Checkout some old formula
$ git checkout 6b8d25f Library/Formula/postgresql.rb
$ brew install postgresql
# … installing
</code></pre>
<p>Now that the older postgresql version is installed, we can re-install the latest formula in order to keep our repository clean:</p>
<pre><code>$ git checkout -- Library/Formula/postgresql.rb
</code></pre>
<p><code>brew switch</code> is your friend to change between the old and the new.</p>
<p><strong>b) prehistoric times</strong></p>
<p>For special needs, we may also try our own digging through the homebrew repo.</p>
<pre><code>$ cd Library/Taps/homebrew/homebrew-core && git log -S'8.4.4' -- Formula/postgresql.rb
</code></pre>
<p><code>git log -S</code> looks for all commits in which the string <code>'8.4.4'</code> was either added or removed in the file <code>Library/Taps/homebrew/homebrew-core/Formula/postgresql.rb</code>. We get two commits as a result.</p>
<pre><code>commit 7dc7ccef9e1ab7d2fc351d7935c96a0e0b031552
Author: Aku Kotkavuo
Date: Sun Sep 19 18:03:41 2010 +0300
Update PostgreSQL to 9.0.0.
Signed-off-by: Adam Vandenberg
commit fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
Author: David Höppner
Date: Sun May 16 12:35:18 2010 +0200
postgresql: update version to 8.4.4
</code></pre>
<p>Obviously, <code>fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422</code> is the commit we’re interested in. As this commit is pretty old, we’ll try to downgrade the complete homebrew installation (that way, the formula API is more or less guaranteed to be valid):</p>
<pre><code>$ git checkout -b postgresql-8.4.4 fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
$ brew install postgresql
$ git checkout master
$ git branch -d postgresql-8.4.4
</code></pre>
<p>You may skip the last command to keep the reference in your git repository.</p>
<p>One note: When checking out the older commit, you temporarily downgrade your homebrew installation. So, you should be careful as some commands in homebrew might be different to the most recent version.</p>
<h2>4) Manually write a formula</h2>
<p><a href="https://docs.brew.sh/How-to-Create-and-Maintain-a-Tap" rel="noreferrer">It’s not too hard</a> and you may then upload it to your own repository. Used to be <a href="https://docs.brew.sh/Versions.html" rel="noreferrer">Homebrew-Versions</a>, but that is now discontinued.</p>
<h2>A.) Bonus: Pinning</h2>
<p>If you want to keep a certain version of, say postgresql, around and stop it from being updated when you do the natural <code>brew update; brew upgrade</code> procedure, you can <em>pin</em> a formula:</p>
<pre><code>$ brew pin postgresql
</code></pre>
<p>Pinned formulae are listed in <code>/usr/local/Library/PinnedKegs/</code> and once you want to bring in the latest changes and updates, you can <em>unpin</em> it again:</p>
<pre><code>$ brew unpin postgresql
</code></pre> | {
"question_id": 3987683,
"question_date": "2010-10-21T12:58:19.160Z",
"question_score": 2628,
"tags": "homebrew",
"answer_id": 4158763,
"answer_date": "2010-11-11T20:04:23.700Z",
"answer_score": 2869
} |
Please answer the following Stack Overflow question:
Title: Using async/await with a forEach loop
<p>Are there any issues with using <code>async</code>/<code>await</code> in a <code>forEach</code> loop? I'm trying to loop through an array of files and <code>await</code> on the contents of each file.</p>
<pre><code>import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
</code></pre>
<p>This code does work, but could something go wrong with this? I had someone tell me that you're not supposed to use <code>async</code>/<code>await</code> in a higher-order function like this, so I just wanted to ask if there was any issue with this.</p> | <p>Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do. It just fires off multiple asynchronous calls, but the <code>printFiles</code> function does immediately return after that.</p>
<h3>Reading in sequence</h3>
<p>If you want to read the files in sequence, <strong>you cannot use <code>forEach</code></strong> indeed. Just use a modern <code>for … of</code> loop instead, in which <code>await</code> will work as expected:</p>
<pre><code>async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
</code></pre>
<h3>Reading in parallel</h3>
<p>If you want to read the files in parallel, <strong>you cannot use <code>forEach</code></strong> indeed. Each of the <code>async</code> callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use <code>map</code> instead, and you can await the array of promises that you'll get with <code>Promise.all</code>:</p>
<pre><code>async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
</code></pre> | {
"question_id": 37576685,
"question_date": "2016-06-01T18:55:58.750Z",
"question_score": 2628,
"tags": "javascript|node.js|promise|async-await|ecmascript-2017",
"answer_id": 37576787,
"answer_date": "2016-06-01T19:02:09.033Z",
"answer_score": 4759
} |
Please answer the following Stack Overflow question:
Title: How do I get the last element of a list?
<p>How do I get the last element of a list?</p> | <p><code>some_list[-1]</code> is the shortest and most Pythonic.</p>
<p>In fact, you can do much more with this syntax. The <code>some_list[-n]</code> syntax gets the nth-to-last element. So <code>some_list[-1]</code> gets the last element, <code>some_list[-2]</code> gets the second to last, etc, all the way down to <code>some_list[-len(some_list)]</code>, which gives you the first element.</p>
<p>You can also set list elements in this way. For instance:</p>
<pre><code>>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
</code></pre>
<p>Note that getting a list item by index will raise an <a href="https://docs.python.org/3/library/exceptions.html#IndexError" rel="noreferrer"><code>IndexError</code></a> if the expected item doesn't exist. This means that <code>some_list[-1]</code> will raise an exception if <code>some_list</code> is empty, because an empty list can't have a last element.</p> | {
"question_id": 930397,
"question_date": "2009-05-30T19:28:53.667Z",
"question_score": 2625,
"tags": "python|list|indexing",
"answer_id": 930398,
"answer_date": "2009-05-30T19:29:55.660Z",
"answer_score": 3796
} |
Please answer the following Stack Overflow question:
Title: Does a finally block always get executed in Java?
<p>Considering this code, can I be <em>absolutely sure</em> that the <code>finally</code> block always executes, no matter what <code>something()</code> is?</p>
<pre><code>try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
</code></pre> | <p>Yes, <code>finally</code> will be called after the execution of the <code>try</code> or <code>catch</code> code blocks.</p>
<p>The only times <code>finally</code> won't be called are:</p>
<ol>
<li>If you invoke <code>System.exit()</code></li>
<li>If you invoke <code>Runtime.getRuntime().halt(exitStatus)</code></li>
<li>If the JVM crashes first</li>
<li>If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the <code>try</code> or <code>catch</code> block</li>
<li>If the OS forcibly terminates the JVM process; e.g., <code>kill -9 <pid></code> on UNIX</li>
<li>If the host system dies; e.g., power failure, hardware error, OS panic, et cetera</li>
<li>If the <code>finally</code> block is going to be executed by a daemon thread and all other non-daemon threads exit before <code>finally</code> is called</li>
</ol> | {
"question_id": 65035,
"question_date": "2008-09-15T17:43:54.513Z",
"question_score": 2623,
"tags": "java|error-handling|return|try-catch-finally",
"answer_id": 65049,
"answer_date": "2008-09-15T17:45:39.203Z",
"answer_score": 2940
} |
Please answer the following Stack Overflow question:
Title: Extract filename and extension in Bash
<p>I want to get the filename (without extension) and the extension separately.</p>
<p>The best solution I found so far is:</p>
<pre><code>NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
</code></pre>
<p>This is wrong because it doesn't work if the file name contains multiple <code>.</code> characters. If, let's say, I have <code>a.b.js</code>, it will consider <code>a</code> and <code>b.js</code>, instead of <code>a.b</code> and <code>js</code>.</p>
<p>It can be easily done in Python with</p>
<pre><code>file, ext = os.path.splitext(path)
</code></pre>
<p>but I'd prefer not to fire up a Python interpreter just for this, if possible.</p>
<p>Any better ideas?</p> | <p>First, get file name without the path:</p>
<pre><code>filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
</code></pre>
<p>Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:</p>
<pre><code>filename="${fullfile##*/}"
</code></pre>
<p>You may want to check the documentation :</p>
<ul>
<li>On the web at section "<a href="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">3.5.3 Shell Parameter Expansion</a>"</li>
<li>In the bash manpage at section called "Parameter Expansion"</li>
</ul> | {
"question_id": 965053,
"question_date": "2009-06-08T14:00:29.207Z",
"question_score": 2616,
"tags": "bash|string|filenames",
"answer_id": 965072,
"answer_date": "2009-06-08T14:05:19.073Z",
"answer_score": 4152
} |
Please answer the following Stack Overflow question:
Title: Scroll to an element with jQuery
<p>I have this <code>input</code> element:</p>
<pre><code> <input type="text" class="textfield" value="" id="subject" name="subject">
</code></pre>
<p>Then I have some other elements, like other tag's & <code><textarea></code> tag's, etc...</p>
<p>When the user clicks on the <code><input id="#subject"></code>, the page should scroll to the page's last element, and it should do so with a nice animation <em>(It should be a scroll to bottom and not to top)</em>.</p>
<p>The last item of the page is a <code>submit</code> button with <code>#submit</code>:</p>
<pre><code><input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
</code></pre>
<p>The animation should not be too fast and should be fluid.</p>
<p>I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.</p> | <p>Assuming you have a button with the id <code>button</code>, try this example:</p>
<pre><code>$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
</code></pre>
<p>I got the code from the article <em><a href="https://www.abeautifulsite.net/posts/smoothly-scroll-to-an-element-without-a-jquery-plugin-2" rel="noreferrer">Smoothly scroll to an element without a jQuery plugin</a></em>. And I have tested it on the example below.</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><html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html></code></pre>
</div>
</div>
</p> | {
"question_id": 6677035,
"question_date": "2011-07-13T09:49:44.753Z",
"question_score": 2615,
"tags": "javascript|jquery|scroll",
"answer_id": 6677069,
"answer_date": "2011-07-13T09:52:36.840Z",
"answer_score": 4430
} |
Please answer the following Stack Overflow question:
Title: PowerShell says "execution of scripts is disabled on this system."
<p>I am trying to run a <code>cmd</code> file that calls a PowerShell script from <code>cmd.exe</code>, but I am getting this error:</p>
<blockquote>
<p><code>Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system.</p>
</blockquote>
<p>I ran this command:</p>
<pre class="lang-none prettyprint-override"><code>Set-ExecutionPolicy -ExecutionPolicy Unrestricted
</code></pre>
<p>When I run <code>Get-ExecutionPolicy</code> from PowerShell, it returns <code>Unrestricted</code>.</p>
<pre class="lang-none prettyprint-override"><code>Get-ExecutionPolicy
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Unrestricted
</code></pre>
<hr />
<blockquote>
<p>cd "C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts"
powershell .\Management_Install.ps1 1</p>
<p>WARNING: Running x86 PowerShell...</p>
<p>File <code>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system. Please see "<code>get-help about_signing</code>" for more details.</p>
<p>At line:1 char:25</p>
<ul>
<li><p><code>.\Management_Install.ps1</code> <<<< 1</p>
<ul>
<li><p>CategoryInfo : NotSpecified: (:) [], PSSecurityException</p>
</li>
<li><p>FullyQualifiedErrorId : RuntimeException</p>
</li>
</ul>
</li>
</ul>
<p>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts> PAUSE</p>
<p>Press any key to continue . . .</p>
</blockquote>
<hr />
<p>The system is <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2.</p>
<p>What am I doing wrong?</p> | <p>If you're using <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 then there is an <em>x64</em> and <em>x86</em> version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?</p>
<p>As an <em>Administrator</em>, you can set the execution policy by typing this into your PowerShell window:</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned
</code></pre>
<p>For more information, see <em><a href="https://docs.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy" rel="noreferrer">Using the Set-ExecutionPolicy Cmdlet</a></em>.</p>
<p>When you are done, you can set the policy back to its default value with:</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy Restricted
</code></pre>
<p>You may see an error:</p>
<pre class="lang-None prettyprint-override"><code>Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
To change the execution policy for the default (LocalMachine) scope,
start Windows PowerShell with the "Run as administrator" option.
To change the execution policy for the current user,
run "Set-ExecutionPolicy -Scope CurrentUser".
</code></pre>
<p>So you may need to run the command like this (as seen in comments):</p>
<pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
</code></pre> | {
"question_id": 4037939,
"question_date": "2010-10-27T21:39:29.397Z",
"question_score": 2606,
"tags": "powershell|windows-server-2008-r2",
"answer_id": 4038991,
"answer_date": "2010-10-28T01:16:25.983Z",
"answer_score": 3253
} |
Please answer the following Stack Overflow question:
Title: Adding a table row in jQuery
<p>I'm using jQuery to add an additional row to a table as the last row.</p>
<p>I have done it this way:</p>
<pre><code>$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
</code></pre>
<p>Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?</p> | <p>The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a <code>tbody</code> for example:</p>
<pre><code><table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
</code></pre>
<p>You would end up with the following:</p>
<pre><code><table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
<tr>...</tr>
</table>
</code></pre>
<p>I would therefore recommend this approach instead:</p>
<pre><code>$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
</code></pre>
<p>You can include anything within the <code>after()</code> method as long as it's valid HTML, including multiple rows as per the example above.</p>
<p><strong>Update:</strong> Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a <code>tbody</code> in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no <code>tbody</code> unless you have specified one yourself.</p>
<p>DaRKoN_ <a href="https://stackoverflow.com/questions/171027/jquery-add-table-row/468240#468240">suggests</a> appending to the <code>tbody</code> rather than adding content after the last <code>tr</code>. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple <code>tbody</code> elements and the row would get added to each of them.</p>
<p>Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.</p>
<p>I think the safest solution is probably to ensure your <code>table</code> always includes at least one <code>tbody</code> in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple <code>tbody</code> elements):</p>
<pre><code>$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');
</code></pre> | {
"question_id": 171027,
"question_date": "2008-10-04T21:33:10.247Z",
"question_score": 2606,
"tags": "javascript|jquery|html-table",
"answer_id": 171049,
"answer_date": "2008-10-04T21:49:32.520Z",
"answer_score": 2275
} |
Please answer the following Stack Overflow question:
Title: How to mkdir only if a directory does not already exist?
<p>I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the <code>mkdir</code> command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that <code>mkdir</code> throws when it tries to create an existing directory. </p>
<p>How can I best do this?</p> | <p>Try <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html" rel="noreferrer"><code>mkdir -p</code></a>:</p>
<pre><code>mkdir -p foo
</code></pre>
<p>Note that this will also create any intermediate directories that don't exist; for instance,</p>
<pre><code>mkdir -p foo/bar/baz
</code></pre>
<p>will create directories <code>foo</code>, <code>foo/bar</code>, and <code>foo/bar/baz</code> if they don't exist.</p>
<p>Some implementation like GNU <code>mkdir</code> include <code>mkdir --parents</code> as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.</p>
<p>If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/test.html" rel="noreferrer"><code>test</code></a> for the existence of the directory first:</p>
<pre><code>[ -d foo ] || mkdir foo
</code></pre> | {
"question_id": 793858,
"question_date": "2009-04-27T14:47:44.957Z",
"question_score": 2602,
"tags": "shell|scripting|ksh|aix|mkdir",
"answer_id": 793867,
"answer_date": "2009-04-27T14:49:46.437Z",
"answer_score": 4283
} |
Please answer the following Stack Overflow question:
Title: Compare two dates with JavaScript
<p>Can someone suggest a way to compare the values of <strong>two dates</strong> greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.</p> | <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer">Date object</a> will do what you want - construct one for each date, then compare them using the <code>></code>, <code><</code>, <code><=</code> or <code>>=</code>.</p>
<p>The <code>==</code>, <code>!=</code>, <code>===</code>, and <code>!==</code> operators require you to use <code>date.getTime()</code> as in</p>
<pre><code>var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
</code></pre>
<p>to be clear just checking for equality directly with the date objects won't work</p>
<pre><code>var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
</code></pre>
<p>I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.</p>
<hr />
<p>For the curious, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer"><code>date.getTime()</code> documentation</a>:</p>
<blockquote>
<p>Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)</p>
</blockquote> | {
"question_id": 492994,
"question_date": "2009-01-29T19:14:06.757Z",
"question_score": 2594,
"tags": "javascript|date|datetime|compare",
"answer_id": 493018,
"answer_date": "2009-01-29T19:20:10.787Z",
"answer_score": 3094
} |
Please answer the following Stack Overflow question:
Title: What does O(log n) mean exactly?
<p>I am learning about Big O Notation running times and amortized times. I understand the notion of <em>O(n)</em> linear time, meaning that the size of the input affects the growth of the algorithm proportionally...and the same goes for, for example, quadratic time <em>O(n<sup>2</sup>)</em> etc..even algorithms, such as permutation generators, with <em>O(n!)</em> times, that grow by factorials.</p>
<p>For example, the following function is <em>O(n)</em> because the algorithm grows in proportion to its input <em>n</em>:</p>
<pre><code>f(int n) {
int i;
for (i = 0; i < n; ++i)
printf("%d", i);
}
</code></pre>
<p>Similarly, if there was a nested loop, the time would be O(n<sup>2</sup>).</p>
<p>But what exactly is <em>O(log n)</em>? For example, what does it mean to say that the height of a complete binary tree is <em>O(log n)</em>?</p>
<p>I do know (maybe not in great detail) what Logarithm is, in the sense that: log<sub>10</sub> 100 = 2, but I cannot understand how to identify a function with a logarithmic time.</p> | <blockquote>
<p>I cannot understand how to identify a function with a log time.</p>
</blockquote>
<p>The most common attributes of logarithmic running-time function are that:</p>
<ul>
<li>the choice of the next element on which to perform some action is one of several possibilities, and</li>
<li>only one will need to be chosen.</li>
</ul>
<p>or</p>
<ul>
<li>the elements on which the action is performed are digits of n</li>
</ul>
<p>This is why, for example, looking up people in a phone book is O(log n). You don't need to check <em>every</em> person in the phone book to find the right one; instead, you can simply divide-and-conquer by looking based on where their name is alphabetically, and in every section you only need to explore a subset of each section before you eventually find someone's phone number.</p>
<p>Of course, a bigger phone book will still take you a longer time, but it won't grow as quickly as the proportional increase in the additional size.</p>
<hr/>
<p>We can expand the phone book example to compare other kinds of operations and <em>their</em> running time. We will assume our phone book has <em>businesses</em> (the "Yellow Pages") which have unique names and <em>people</em> (the "White Pages") which may not have unique names. A phone number is assigned to at most one person or business. We will also assume that it takes constant time to flip to a specific page.</p>
<p>Here are the running times of some operations we might perform on the phone book, from fastest to slowest:</p>
<ul>
<li><p><strong>O(1) (in the worst case):</strong> Given the page that a business's name is on and the business name, find the phone number.</p></li>
<li><p><strong>O(1) (in the average case):</strong> Given the page that a person's name is on and their name, find the phone number.</p></li>
<li><p><strong>O(log n):</strong> Given a person's name, find the phone number by picking a random point about halfway through the part of the book you haven't searched yet, then checking to see whether the person's name is at that point. Then repeat the process about halfway through the part of the book where the person's name lies. (This is a binary search for a person's name.)</p></li>
<li><p><strong>O(n):</strong> Find all people whose phone numbers contain the digit "5".</p></li>
<li><p><strong>O(n):</strong> Given a phone number, find the person or business with that number.</p></li>
<li><p><strong>O(n log n):</strong> There was a mix-up at the printer's office, and our phone book had all its pages inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each page and then putting that page in the appropriate spot in a new, empty phone book.</p></li>
</ul>
<p>For the below examples, we're now at the printer's office. Phone books are waiting to be mailed to each resident or business, and there's a sticker on each phone book identifying where it should be mailed to. Every person or business gets one phone book.</p>
<ul>
<li><p><strong>O(n log n):</strong> We want to personalize the phone book, so we're going to find each person or business's name in their designated copy, then circle their name in the book and write a short thank-you note for their patronage.</p></li>
<li><p><strong>O(n<sup>2</sup>):</strong> A mistake occurred at the office, and every entry in each of the phone books has an extra "0" at the end of the phone number. Take some white-out and remove each zero.</p></li>
<li><p><strong>O(n · n!):</strong> We're ready to load the phonebooks onto the shipping dock. Unfortunately, the robot that was supposed to load the books has gone haywire: it's putting the books onto the truck in a random order! Even worse, it loads all the books onto the truck, then checks to see if they're in the right order, and if not, it unloads them and starts over. (This is the dreaded <strong><a href="http://en.wikipedia.org/wiki/Bogosort" rel="noreferrer">bogo sort</a></strong>.)</p></li>
<li><p><strong>O(n<sup>n</sup>):</strong> You fix the robot so that it's loading things correctly. The next day, one of your co-workers plays a prank on you and wires the loading dock robot to the automated printing systems. Every time the robot goes to load an original book, the factory printer makes a duplicate run of all the phonebooks! Fortunately, the robot's bug-detection systems are sophisticated enough that the robot doesn't try printing even more copies when it encounters a duplicate book for loading, but it still has to load every original and duplicate book that's been printed.</p></li>
</ul> | {
"question_id": 2307283,
"question_date": "2010-02-21T20:05:38.990Z",
"question_score": 2592,
"tags": "algorithm|time-complexity|big-o",
"answer_id": 2307314,
"answer_date": "2010-02-21T20:14:59.797Z",
"answer_score": 3224
} |
Please answer the following Stack Overflow question:
Title: How do I import an SQL file using the command line in MySQL?
<p>I have a <code>.sql</code> file with an export from <code>phpMyAdmin</code>. I want to import it into a different server using the command line.</p>
<p>I have a <a href="http://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 installation. I placed the <code>.sql</code> file on the <strong><em>C drive</em></strong>, and I tried this command</p>
<pre><code>database_name < file.sql
</code></pre>
<p>It is not working. I get syntax errors.</p>
<ul>
<li>How can I import this file without a problem?</li>
<li>Do I need to create a database first?</li>
</ul> | <p>Try:</p>
<pre><code>mysql -u username -p database_name < file.sql
</code></pre>
<p>Check <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-command-options.html" rel="noreferrer">MySQL Options</a>.</p>
<p><strong>Note 1:</strong> It is better to use the full path of the SQL file <code>file.sql</code>.</p>
<p><strong>Note 2:</strong> Use <code>-R</code> and <code>--triggers</code> to keep the routines and triggers of original database. They are not copied by default.</p>
<p><strong>Note 3</strong> You may have to create the (empty) database from MySQL if it doesn't exist already and the exported SQL don't contain <code>CREATE DATABASE</code> (exported with <code>--no-create-db</code> or <code>-n</code> option), before you can import it.</p> | {
"question_id": 17666249,
"question_date": "2013-07-16T00:43:48.420Z",
"question_score": 2590,
"tags": "mysql|sql|command-line|import",
"answer_id": 17666279,
"answer_date": "2013-07-16T00:48:01.723Z",
"answer_score": 4681
} |
Please answer the following Stack Overflow question:
Title: How do I determine whether an array contains a particular value in Java?
<p>I have a <code>String[]</code> with values like so:</p>
<pre><code>public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
</code></pre>
<p>Given <code>String s</code>, is there a good way of testing whether <code>VALUES</code> contains <code>s</code>?</p> | <pre><code>Arrays.asList(yourArray).contains(yourValue)
</code></pre>
<p>Warning: this doesn't work for arrays of primitives (see the comments).</p>
<hr>
<h2>Since <a href="/questions/tagged/java-8" class="post-tag" title="show questions tagged 'java-8'" rel="tag">java-8</a> you can now use Streams.</h2>
<pre><code>String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
</code></pre>
<p>To check whether an array of <code>int</code>, <code>double</code> or <code>long</code> contains a value use <code>IntStream</code>, <code>DoubleStream</code> or <code>LongStream</code> respectively.</p>
<h2>Example</h2>
<pre><code>int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
</code></pre> | {
"question_id": 1128723,
"question_date": "2009-07-15T00:03:21.820Z",
"question_score": 2589,
"tags": "java|arrays",
"answer_id": 1128728,
"answer_date": "2009-07-15T00:04:49.150Z",
"answer_score": 3262
} |
Please answer the following Stack Overflow question:
Title: Set a default parameter value for a JavaScript function
<p>I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:</p>
<pre><code>def read_file(file, delete_after = false)
# code
end
</code></pre>
<p>Does this work in JavaScript?</p>
<pre><code>function read_file(file, delete_after = false) {
// Code
}
</code></pre> | <p>From <a href="https://www.ecma-international.org/ecma-262/6.0/" rel="noreferrer">ES6/ES2015</a>, default parameters are in the language specification.</p>
<pre><code>function read_file(file, delete_after = false) {
// Code
}
</code></pre>
<p>just works.</p>
<p>Reference: <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters" rel="noreferrer">Default Parameters - MDN</a></p>
<blockquote>
<p>Default function parameters allow formal parameters to be initialized with default values if <strong>no value</strong> or <strong>undefined</strong> is passed.</p>
</blockquote>
<p>In ES6, you can <a href="http://exploringjs.com/es6/ch_parameter-handling.html#sec_named-parameters" rel="noreferrer">simulate default <em>named</em> parameters via destructuring</a>:</p>
<pre><code>// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
// Use the variables `start`, `end` and `step` here
···
}
// sample call using an object
myFor({ start: 3, end: 0 });
// also OK
myFor();
myFor({});
</code></pre>
<p><strong>Pre ES2015</strong>,</p>
<p>There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null. (<code>typeof null == "object"</code>)</p>
<pre><code>function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
</code></pre> | {
"question_id": 894860,
"question_date": "2009-05-21T20:07:17.740Z",
"question_score": 2588,
"tags": "javascript|function|parameters|arguments|default-parameters",
"answer_id": 894877,
"answer_date": "2009-05-21T20:10:52.287Z",
"answer_score": 3512
} |
Please answer the following Stack Overflow question:
Title: Find (and kill) process locking port 3000 on Mac
<p>How do I find (and kill) processes that listen to/use my TCP ports? I'm on macOS.</p>
<p>Sometimes, after a crash or some bug, my Rails app is locking port 3000. I can't find it using <code>ps -ef</code>...</p>
<p>When running</p>
<pre><code>rails server
</code></pre>
<p>I get</p>
<pre><code>Address already in use - bind(2) (Errno::EADDRINUSE)
</code></pre>
<p>The same issue happens when stopping Node.js process. Even after the process is stopped and the app stops running, port <code>3000</code> is locked. When starting the app again, getting</p>
<pre><code>Address already in use (Errno::EADDRINUSE)
</code></pre> | <ol>
<li><p>You can try <code>netstat</code></p>
<pre><code>netstat -vanp tcp | grep 3000
</code></pre>
</li>
<li><p>For <strong>macOS El Capitan</strong> and newer (or if your netstat doesn't support <code>-p</code>), use <code>lsof</code></p>
<pre><code>lsof -i tcp:3000
</code></pre>
</li>
</ol> | {
"question_id": 3855127,
"question_date": "2010-10-04T12:19:16.317Z",
"question_score": 2581,
"tags": "node.js|macos|process",
"answer_id": 3855359,
"answer_date": "2010-10-04T12:48:57.843Z",
"answer_score": 4145
} |
Please answer the following Stack Overflow question:
Title: How do I sort a list of dictionaries by a value of the dictionary?
<p>How do I sort a list of dictionaries by a specific key's value? Given:</p>
<pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
</code></pre>
<p>When sorted by <code>name</code>, it should become:</p>
<pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
</code></pre> | <p>The <a href="https://docs.python.org/library/functions.html#sorted" rel="noreferrer"><code>sorted()</code></a> function takes a <code>key=</code> parameter</p>
<pre><code>newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
</code></pre>
<p>Alternatively, you can use <a href="https://docs.python.org/library/operator.html#operator.itemgetter" rel="noreferrer"><code>operator.itemgetter</code></a> instead of defining the function yourself</p>
<pre><code>from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
</code></pre>
<p>For completeness, add <code>reverse=True</code> to sort in descending order</p>
<pre><code>newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
</code></pre> | {
"question_id": 72899,
"question_date": "2008-09-16T14:27:47.470Z",
"question_score": 2572,
"tags": "python|list|sorting|dictionary|data-structures",
"answer_id": 73050,
"answer_date": "2008-09-16T14:39:44.273Z",
"answer_score": 3346
} |
Please answer the following Stack Overflow question:
Title: How do I call one constructor from another in Java?
<p>Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?</p> | <p>Yes, it is possible:</p>
<pre><code>public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
</code></pre>
<p>To chain to a particular superclass constructor instead of one in the same class, use <code>super</code> instead of <code>this</code>. Note that <strong>you can only chain to one constructor</strong>, and <strong>it has to be the first statement in your constructor body</strong>.</p>
<p>See also <a href="https://stackoverflow.com/questions/284896">this related question</a>, which is about C# but where the same principles apply.</p> | {
"question_id": 285177,
"question_date": "2008-11-12T20:10:19.577Z",
"question_score": 2569,
"tags": "java|constructor",
"answer_id": 285184,
"answer_date": "2008-11-12T20:12:14.610Z",
"answer_score": 3294
} |
Please answer the following Stack Overflow question:
Title: How to upgrade all Python packages with pip
<p>Is it possible to upgrade all Python packages at one time with <strong><a href="https://pypi.python.org/pypi/pip" rel="noreferrer"><code>pip</code></a></strong>?</p>
<p><strong>Note</strong>: that there is <a href="https://github.com/pypa/pip/issues/4551" rel="noreferrer">a feature request</a> for this on the official issue tracker.</p> | <p>There isn't a built-in flag yet, but you can use:</p>
<pre><code>pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
</code></pre>
<p>For older versions of <code>pip</code>:</p>
<pre><code>pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U
</code></pre>
<hr />
<ul>
<li><p>The <code>grep</code> is to skip editable ("-e") package definitions, as suggested by @jawache. (Yes, you could replace <code>grep</code>+<code>cut</code> with <code>sed</code> or <code>awk</code> or <code>perl</code> or...).</p>
</li>
<li><p>The <code>-n1</code> flag for <code>xargs</code> prevents stopping everything if updating one package fails (thanks <a href="https://stackoverflow.com/users/339505/andsens">@andsens</a>).</p>
</li>
</ul>
<hr />
<p><strong>Note:</strong> there are infinite potential variations for this. I'm trying to keep this answer short and simple, but please do suggest variations in the comments!</p> | {
"question_id": 2720014,
"question_date": "2010-04-27T09:23:25.477Z",
"question_score": 2561,
"tags": "python|pip",
"answer_id": 3452888,
"answer_date": "2010-08-10T19:56:49.130Z",
"answer_score": 2726
} |
Please answer the following Stack Overflow question:
Title: Generate random string/characters in JavaScript
<p>I want a 5 character string composed of characters picked randomly from the set <code>[a-zA-Z0-9]</code>.</p>
<p>What's the best way to do this with JavaScript?</p> | <p>I think this will work for you:</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 makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
console.log(makeid(5));</code></pre>
</div>
</div>
</p> | {
"question_id": 1349404,
"question_date": "2009-08-28T21:14:41.053Z",
"question_score": 2557,
"tags": "javascript|string|random",
"answer_id": 1349426,
"answer_date": "2009-08-28T21:21:03.160Z",
"answer_score": 3395
} |
Please answer the following Stack Overflow question:
Title: When to use margin vs padding in CSS
<p>When writing CSS, is there a particular rule or guideline that should be used in deciding when to use <code>margin</code> and when to use <code>padding</code>?</p> | <p><strong>TL;DR:</strong> <em>By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.</em></p>
<p>To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't. </p>
<p>Consider two elements one above the other each with padding of <code>1em</code>. This padding is considered to be part of the element and is always preserved. </p>
<p>So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element. </p>
<p>Thus the content of the two elements will end up being <code>2em</code> apart.</p>
<p>Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap. </p>
<p>So in this example, you will end up with the content of the first element followed by <code>1em</code> of combined margin followed by the content of the second element. So the content of the two elements is only <code>1em</code> apart. </p>
<p>This can be really useful when you know that you want to say <code>1em</code> of spacing around an element, regardless of what element it is next to.</p>
<p>The other two big differences are that padding is included in the click region and background color/image, but not the margin.</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.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }
div.padding > div { padding-top: 20px; }
div.margin > div { margin-top: 20px; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Default</h3>
<div class="box">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>padding-top: 20px</h3>
<div class="box padding">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>margin-top: 20px; </h3>
<div class="box margin">
<div>A</div>
<div>B</div>
<div>C</div>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 2189452,
"question_date": "2010-02-03T03:20:12.533Z",
"question_score": 2555,
"tags": "css|padding|margin",
"answer_id": 9183818,
"answer_date": "2012-02-07T20:59:55.510Z",
"answer_score": 1765
} |
Please answer the following Stack Overflow question:
Title: How do I get a substring of a string in Python?
<p>I want to get a new string from the third character to the end of the string, e.g. <code>myString[2:end]</code>. If omitting the second part means 'till the end', and if you omit the first part, does it start from the start?</p> | <pre><code>>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
</code></pre>
<p>Python calls this concept "slicing" and it works on more than just strings. Take a look <a href="https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">here</a> for a comprehensive introduction.</p> | {
"question_id": 663171,
"question_date": "2009-03-19T17:29:41.583Z",
"question_score": 2548,
"tags": "python|string|substring",
"answer_id": 663175,
"answer_date": "2009-03-19T17:30:44.780Z",
"answer_score": 3605
} |
Please answer the following Stack Overflow question:
Title: Make a div fill the height of the remaining screen space
<p>I am working on a web application where I want the content to fill the height of the entire screen.</p>
<p>The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.</p>
<p>I have a header <code>div</code> and a content <code>div</code>. At the moment I am using a table for the layout like so:</p>
<p>CSS and HTML</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#page {
height: 100%; width: 100%
}
#tdcontent {
height: 100%;
}
#content {
overflow: auto; /* or overflow: hidden; */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="page">
<tr>
<td id="tdheader">
<div id="header">...</div>
</td>
</tr>
<tr>
<td id="tdcontent">
<div id="content">...</div>
</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
<p>The entire height of the page is filled, and no scrolling is required.</p>
<p>For anything inside the content div, setting <code>top: 0;</code> will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting <code>header</code> inside <code>content</code> will not allow this to work.</p>
<p>Is there a way to achieve the same effect without using the <code>table</code>?</p>
<p><strong>Update:</strong></p>
<p>Elements inside the content <code>div</code> will have heights set to percentages as well. So something at 100% inside the <code>div</code> will fill it to the bottom. As will two elements at 50%.</p>
<p><strong>Update 2:</strong></p>
<p>For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside <code>#content</code> would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.</p> | <h3>2015 update: the flexbox approach</h3>
<p>There are two other answers briefly mentioning <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">flexbox</a>; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now.</p>
<blockquote>
<p>Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.</p>
<p>(taken from <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes</a>)</p>
</blockquote>
<p>All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim.</p>
<p>To check current support you can also see here:
<a href="http://caniuse.com/#feat=flexbox" rel="noreferrer">http://caniuse.com/#feat=flexbox</a></p>
<h3>Working example</h3>
<p>With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
height: 100%;
margin: 0;
}
.box {
display: flex;
flex-flow: column;
height: 100%;
}
.box .row {
border: 1px dotted grey;
}
.box .row.header {
flex: 0 1 auto;
/* The above is shorthand for:
flex-grow: 0,
flex-shrink: 1,
flex-basis: auto
*/
}
.box .row.content {
flex: 1 1 auto;
}
.box .row.footer {
flex: 0 1 40px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` -->
<div class="box">
<div class="row header">
<p><b>header</b>
<br />
<br />(sized to content)</p>
</div>
<div class="row content">
<p>
<b>content</b>
(fills remaining space)
</p>
</div>
<div class="row footer">
<p><b>footer</b> (fixed height)</p>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>In the CSS above, the <a href="https://developer.mozilla.org/en/CSS/flex" rel="noreferrer">flex</a> property shorthands the <a href="https://developer.mozilla.org/en/CSS/flex-grow" rel="noreferrer">flex-grow</a>, <a href="https://developer.mozilla.org/en/CSS/flex-shrink" rel="noreferrer">flex-shrink</a>, and <a href="https://developer.mozilla.org/en/CSS/flex-basis" rel="noreferrer">flex-basis</a> properties to establish the flexibility of the flex items. Mozilla has a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer">good introduction to the flexible boxes model</a>.</p> | {
"question_id": 90178,
"question_date": "2008-09-18T05:06:17.897Z",
"question_score": 2541,
"tags": "html|css|html-table",
"answer_id": 24979148,
"answer_date": "2014-07-27T08:14:37.147Z",
"answer_score": 1569
} |
Please answer the following Stack Overflow question:
Title: Docker: Copying files from Docker container to host
<p>I'm thinking of using Docker to build my dependencies on a Continuous Integration (CI) server, so that I don't have to install all the runtimes and libraries on the agents themselves. </p>
<p>To achieve this I would need to copy the build artifacts that are built inside the container back into the host. Is that possible?</p> | <p>In order to copy a file from a container to the host, you can use the command</p>
<pre><code>docker cp <containerId>:/file/path/within/container /host/path/target
</code></pre>
<p>Here's an example:</p>
<pre><code>$ sudo docker cp goofy_roentgen:/out_read.jpg .
</code></pre>
<p>Here <strong>goofy_roentgen</strong> is the container name I got from the following command:</p>
<pre><code>$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1b4ad9311e93 bamos/openface "/bin/bash" 33 minutes ago Up 33 minutes 0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->9000/tcp goofy_roentgen
</code></pre>
<p>You can also use (part of) the <strong>Container ID</strong>. The following command is equivalent to the first</p>
<pre><code>$ sudo docker cp 1b4a:/out_read.jpg .
</code></pre> | {
"question_id": 22049212,
"question_date": "2014-02-26T17:46:52.947Z",
"question_score": 2541,
"tags": "docker|docker-container|file-copying",
"answer_id": 22050116,
"answer_date": "2014-02-26T18:31:40.647Z",
"answer_score": 4220
} |
Please answer the following Stack Overflow question:
Title: How do I safely merge a Git branch into master?
<p>A new branch from <code>master</code> is created, we call it <code>test</code>.</p>
<p>There are several developers who either commit to <code>master</code> or create other branches and later merge into <code>master</code>.</p>
<p>Let's say work on <code>test</code> is taking several days and you want to continuously keep <code>test</code> updated with commits inside <code>master</code>.</p>
<p>I would do <code>git pull origin master</code> from <code>test</code>. </p>
<p><strong>Question 1:</strong> Is this the right approach? Other developers could have easily worked on same files as I have worked btw.</p>
<hr>
<p>My work on <code>test</code> is done and I am ready to merge it back to <code>master</code>. Here are the two ways I can think of:</p>
<p><strong>A:</strong> </p>
<pre><code>git checkout test
git pull origin master
git push origin test
git checkout master
git pull origin test
</code></pre>
<p><strong>B:</strong> </p>
<pre><code>git checkout test
git pull origin master
git checkout master
git merge test
</code></pre>
<p>I am not using <code>--rebase</code> because from my understanding, rebase will get the changes from <code>master</code> and stack mine on top of that hence it could overwrite changes other people made.</p>
<p><strong>Question 2:</strong> Which one of these two methods is right? What is the difference there?</p>
<p>The goal in all of this is to keep my <code>test</code> branch updated with the things happening in <code>master</code> and later I could merge them back into <code>master</code> hoping to keep the timeline as linear as possible.</p> | <p>How I would do this</p>
<pre><code>git checkout master
git pull origin master
git merge test
git push origin master
</code></pre>
<p>If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that <code>test</code> is only for you? So no reason to publish it.</p>
<p>git always tries to respect yours and others changes, and so will <code>--rebase</code>. I don't think I can explain it appropriately, so have a look at <a href="http://git-scm.com/book/en/Git-Branching-Rebasing" rel="noreferrer">the Git book - Rebasing</a> or <a href="http://gitready.com/intermediate/2009/01/31/intro-to-rebase.html" rel="noreferrer">git-ready: Intro into rebasing</a> for a little description. It's a quite cool feature</p> | {
"question_id": 5601931,
"question_date": "2011-04-09T00:01:01.027Z",
"question_score": 2535,
"tags": "git|git-branch|git-merge|branching-and-merging",
"answer_id": 5602109,
"answer_date": "2011-04-09T00:45:29.660Z",
"answer_score": 3530
} |
Please answer the following Stack Overflow question:
Title: How can I determine if a variable is 'undefined' or 'null'?
<p>How do I determine if variable is <code>undefined</code> or <code>null</code>?</p>
<p>My code is as follows:</p>
<pre class="lang-js prettyprint-override"><code>var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
</code></pre>
<pre class="lang-html prettyprint-override"><code><div id="esd-names">
<div id="name"></div>
</div>
</code></pre>
<p>But if I do this, the JavaScript interpreter halts execution.</p> | <p>You can use the qualities of the <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison" rel="noreferrer">abstract equality operator</a> to do this:</p>
<pre><code>if (variable == null){
// your code here.
}
</code></pre>
<p>Because <code>null == undefined</code> is true, the above code will catch both <code>null</code> and <code>undefined</code>.</p> | {
"question_id": 2647867,
"question_date": "2010-04-15T18:12:16.507Z",
"question_score": 2531,
"tags": "javascript|jquery|variables|null|undefined",
"answer_id": 2647888,
"answer_date": "2010-04-15T18:14:35.087Z",
"answer_score": 3379
} |
Please answer the following Stack Overflow question:
Title: Deep cloning objects
<p>I want to do something like:</p>
<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();
</code></pre>
<p>And then make changes to the new object that are not reflected in the original object.</p>
<p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p>
<p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p> | <p>Whereas one approach is to implement the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="noreferrer"><code>ICloneable</code></a> interface (described <a href="https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568">here</a>, so I won't regurgitate), here's a nice deep clone object copier I found on <a href="http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects" rel="noreferrer">The Code Project</a> a while ago and incorporated it into our code.
As mentioned elsewhere, it requires your objects to be serializable.</p>
<pre><code>using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
/// <summary>
/// Perform a deep copy of the object via serialization.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>A deep copy of the object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", nameof(source));
}
// Don't serialize a null object, simply return the default for that object
if (ReferenceEquals(source, null)) return default;
using var Stream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
</code></pre>
<p>The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex.</p>
<p>In case of you prefer to use the new <a href="http://en.wikipedia.org/wiki/Extension_method" rel="noreferrer">extension methods</a> of C# 3.0, change the method to have the following signature:</p>
<pre><code>public static T Clone<T>(this T source)
{
// ...
}
</code></pre>
<p>Now the method call simply becomes <code>objectBeingCloned.Clone();</code>.</p>
<p><strong>EDIT</strong> (January 10 2015) Thought I'd revisit this, to mention I recently started using (Newtonsoft) Json to do this, it <a href="http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/" rel="noreferrer">should be</a> lighter, and avoids the overhead of [Serializable] tags. (<strong>NB</strong> @atconway has pointed out in the comments that private members are not cloned using the JSON method)</p>
<pre><code>/// <summary>
/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneJson<T>(this T source)
{
// Don't serialize a null object, simply return the default for that object
if (ReferenceEquals(source, null)) return default;
// initialize inner objects individually
// for example in default constructor some list property initialized with some values,
// but in 'source' these items are cleaned -
// without ObjectCreationHandling.Replace default constructor values will be added to result
var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}
</code></pre> | {
"question_id": 78536,
"question_date": "2008-09-17T00:06:27.547Z",
"question_score": 2530,
"tags": "c#|.net|clone",
"answer_id": 78612,
"answer_date": "2008-09-17T00:18:28.830Z",
"answer_score": 1879
} |
Please answer the following Stack Overflow question:
Title: Validate decimal numbers in JavaScript - IsNumeric()
<p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p>
<p>Bonus points for:</p>
<ol>
<li>Clarity. Solution should be clean and simple.</li>
<li>Cross-platform.</li>
</ol>
<p>Test cases:</p>
<pre><code>01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
</code></pre> | <p><a href="https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921">@Joel's answer</a> is pretty close, but it will fail in the following cases:</p>
<pre><code>// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
</code></pre>
<p>Some time ago I had to implement an <code>IsNumeric</code> function, to find out if a variable contained a numeric value, <strong>regardless of its type</strong>, it could be a <code>String</code> containing a numeric value (I had to consider also exponential notation, etc.), a <code>Number</code> object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. <code>+true == 1;</code> but <code>true</code> shouldn't be considered as <code>"numeric"</code>).</p>
<p>I think is worth sharing this set of <a href="http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/" rel="noreferrer"><strong>+30 unit tests</strong></a> made to numerous function implementations, and also share the one that passes all my tests:</p>
<pre><code>function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</code></pre>
<p><strong>P.S.</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN" rel="noreferrer">isNaN</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite" rel="noreferrer">isFinite</a> have a confusing behavior due to forced conversion to number. In ES6, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN" rel="noreferrer">Number.isNaN</a> & <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite" rel="noreferrer">Number.isFinite</a> would fix these issues. Keep that in mind when using them. </p>
<hr>
<p><strong>Update</strong> :
<a href="https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215" rel="noreferrer">Here's how jQuery does it now (2.2-stable)</a>: </p>
<pre><code>isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
</code></pre>
<p><strong>Update</strong> :
<a href="https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172" rel="noreferrer">Angular 4.3</a>:</p>
<pre><code>export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
</code></pre> | {
"question_id": 18082,
"question_date": "2008-08-20T14:21:13.793Z",
"question_score": 2526,
"tags": "javascript|validation|numbers",
"answer_id": 1830844,
"answer_date": "2009-12-02T05:36:22.517Z",
"answer_score": 2973
} |
Please answer the following Stack Overflow question:
Title: How do you display code snippets in MS Word preserving format and syntax highlighting?
<p>Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.</p>
<p>I have tried to include code as regular text which looks awful and gets in the way when editing regular text. I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects. The code looks much better and is easier to avoid while editing the rest of the text. However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.</p>
<p>Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.</p> | <p>Here is the best way, for me, to add code inside word:</p>
<ol>
<li>Go to <code>Insert</code> tab, <code>Text</code> section, click <code>Object</code> button (it's on the right)</li>
<li>Choose <code>OpenDocument Text</code> which will open a new embedded word document</li>
<li>Copy and paste your code from Visual Studio / Eclipse inside this embedded word page</li>
<li>Save and close</li>
</ol>
<h3>Advantages</h3>
<p>The result looks very nice. Here are the advantages of this method:</p>
<ul>
<li>The code keeps its original layout and colors</li>
<li>The code is separated from the rest of the document, as if it was a picture or a chart</li>
<li>Spelling errors won't be highlighted in the code (this is cool !)</li>
</ul>
<p>And it takes only few seconds.</p> | {
"question_id": 387453,
"question_date": "2008-12-22T21:45:26.690Z",
"question_score": 2522,
"tags": "ms-word|code-formatting",
"answer_id": 2653406,
"answer_date": "2010-04-16T13:54:06.967Z",
"answer_score": 2542
} |
Please answer the following Stack Overflow question:
Title: Do a "git export" (like "svn export")?
<p>I've been wondering whether there is a good "git export" solution that creates a copy of a tree without the <code>.git</code> repository directory. There are at least three methods I know of:</p>
<ol>
<li><code>git clone</code> followed by removing the <code>.git</code> repository directory.</li>
<li><a href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html" rel="noreferrer"><code>git checkout-index</code></a> alludes to this functionality but starts with "Just read the desired tree into the index..." which I'm not entirely sure how to do.</li>
<li><a href="http://code.google.com/p/git-export/" rel="noreferrer"><code>git-export</code></a> is a third-party script that essentially does a <code>git clone</code> into a temporary location followed by <code>rsync --exclude='.git'</code> into the final destination.</li>
</ol>
<p>None of these solutions really strike me as being satisfactory. The closest one to <code>svn export</code> might be option 1, because both require the target directory to be empty first. But option 2 seems even better, assuming I can figure out what it means to read a tree into the index.</p> | <p>Probably the simplest way to achieve this is with <a href="https://git-scm.com/docs/git-archive" rel="noreferrer"><code>git archive</code></a>. If you really need just the expanded tree you can do something like this.</p>
<pre><code>git archive master | tar -x -C /somewhere/else
</code></pre>
<p>Most of the time that I need to 'export' something from git, I want a compressed archive in any case so I do something like this.</p>
<pre><code>git archive master | bzip2 >source-tree.tar.bz2
</code></pre>
<p>ZIP archive:</p>
<pre><code>git archive --format zip --output /full/path/to/zipfile.zip master
</code></pre>
<p><a href="https://git-scm.com/docs/git-archive" rel="noreferrer"><code>git help archive</code></a> for more details, it's quite flexible.</p>
<hr>
<p>Be aware that even though the archive will not contain the .git directory, it will, however, contain other hidden git-specific files like .gitignore, .gitattributes, etc. If you don't want them in the archive, make sure you use the export-ignore attribute in a .gitattributes file and commit this before doing your archive. <a href="http://feeding.cloud.geek.nz/2010/02/excluding-files-from-git-archive.html" rel="noreferrer">Read more...</a></p>
<hr>
<p>Note: If you are interested in exporting the index, the command is</p>
<pre><code>git checkout-index -a -f --prefix=/destination/path/
</code></pre>
<p>(See <a href="https://stackoverflow.com/a/160719/413020" title="Greg's answer">Greg's answer</a> for more details)</p> | {
"question_id": 160608,
"question_date": "2008-10-02T02:21:33.897Z",
"question_score": 2498,
"tags": "git|export|git-archive|svn-export",
"answer_id": 163769,
"answer_date": "2008-10-02T18:13:14.263Z",
"answer_score": 2526
} |
Please answer the following Stack Overflow question:
Title: Check if a variable is a string in JavaScript
<p>How can I determine whether a variable is a string or something else in JavaScript?</p> | <p>You can use <code>typeof</code> operator:</p>
<pre><code>var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"
</code></pre>
<p>Example from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof" rel="noreferrer">this webpage</a>. (Example was slightly modified though).</p>
<p>This won't work as expected in the case of strings created with <code>new String()</code>, but this is seldom used and recommended against<sup>[1][2]</sup>. See the other answers for how to handle these, if you so desire.</p>
<hr>
<ol>
<li>The Google JavaScript Style Guide <a href="https://google.github.io/styleguide/jsguide.html#disallowed-features-wrapper-objects" rel="noreferrer">says to never use primitive object wrappers</a>.</li>
<li>Douglas Crockford <a href="http://www.crockford.com/javascript/recommend.html" rel="noreferrer">recommended that primitive object wrappers be deprecated</a>.</li>
</ol> | {
"question_id": 4059147,
"question_date": "2010-10-30T14:36:34.840Z",
"question_score": 2491,
"tags": "javascript|string",
"answer_id": 4059166,
"answer_date": "2010-10-30T14:40:41.200Z",
"answer_score": 2246
} |
Please answer the following Stack Overflow question:
Title: How do I create an HTML button that acts like a link?
<p>How do I create an HTML button that acts like a link? So that clicking the button redirects the user to a page.</p>
<p>I want it to be accessible, and with minimal extra characters or parameters in the URL.</p> | <h2>HTML</h2>
<p>The plain HTML way is to put it in a <code><form></code> wherein you specify the desired target URL in the <code>action</code> attribute.</p>
<pre><code><form action="https://google.com">
<input type="submit" value="Go to Google" />
</form>
</code></pre>
<p>If necessary, set CSS <code>display: inline;</code> on the form to keep it in the flow with the surrounding text. Instead of <code><input type="submit"></code> in above example, you can also use <code><button type="submit"></code>. The only difference is that the <code><button></code> element allows children.</p>
<p>You'd intuitively expect to be able to use <code><button href="https://google.com"></code> analogous with the <code><a></code> element, but unfortunately no, this attribute does not exist according to <a href="https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element" rel="noreferrer">HTML specification</a>.</p>
<h2>CSS</h2>
<p>If CSS is allowed, simply use an <code><a></code> which you style to look like a button using among others the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/appearance" rel="noreferrer"><code>appearance</code></a> property (<a href="https://caniuse.com/#feat=css-appearance" rel="noreferrer">it's only not supported in Internet Explorer</a>).</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="https://google.com" class="button">Go to Google</a></code></pre>
</div>
</div>
</p>
<p>Or pick one of those many CSS libraries like <a href="https://getbootstrap.com/docs/5.1/components/buttons/" rel="noreferrer">Bootstrap</a>.</p>
<pre><code><a href="https://google.com" class="btn btn-primary">Go to Google</a>
</code></pre>
<h2>JavaScript</h2>
<p>If JavaScript is allowed, set the <code>window.location.href</code>.</p>
<pre><code><input type="button" onclick="location.href='https://google.com';" value="Go to Google" />
</code></pre>
<p>Instead of <code><input type="button"></code> in above example, you can also use <code><button></code>. The only difference is that the <code><button></code> element allows children.</p> | {
"question_id": 2906582,
"question_date": "2010-05-25T16:39:47.890Z",
"question_score": 2488,
"tags": "html|button|hyperlink|anchor",
"answer_id": 2906586,
"answer_date": "2010-05-25T16:40:49.587Z",
"answer_score": 2663
} |
Please answer the following Stack Overflow question:
Title: Disable/enable an input with jQuery?
<pre><code>$input.disabled = true;
</code></pre>
<p>or </p>
<pre><code>$input.disabled = "disabled";
</code></pre>
<p>Which is the standard way? And, conversely, how do you enable a disabled input?</p> | <h2>jQuery 1.6+</h2>
<p>To change the <code>disabled</code> property you should use the <a href="http://api.jquery.com/prop" rel="noreferrer"><code>.prop()</code></a> function.</p>
<pre><code>$("input").prop('disabled', true);
$("input").prop('disabled', false);
</code></pre>
<h2>jQuery 1.5 and below</h2>
<p>The <code>.prop()</code> function doesn't exist, but <a href="http://api.jquery.com/attr" rel="noreferrer"><code>.attr()</code></a> does similar:</p>
<p>Set the disabled attribute.</p>
<pre><code>$("input").attr('disabled','disabled');
</code></pre>
<p>To enable again, the proper method is to use <a href="//api.jquery.com/removeAttr" rel="noreferrer"><code>.removeAttr()</code></a></p>
<pre><code>$("input").removeAttr('disabled');
</code></pre>
<h2>In any version of jQuery</h2>
<p>You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:</p>
<pre><code>// assuming an event handler thus 'this'
this.disabled = true;
</code></pre>
<p>The advantage to using the <code>.prop()</code> or <code>.attr()</code> methods is that you can set the property for a bunch of selected items.</p>
<hr>
<p><strong>Note:</strong> In 1.6 there is a <a href="//api.jquery.com/removeProp" rel="noreferrer"><code>.removeProp()</code></a> method that sounds a lot like <code>removeAttr()</code>, but it <strong>SHOULD NOT BE USED</strong> on native properties like <code>'disabled'</code> Excerpt from the documentation:</p>
<blockquote>
<p>Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.</p>
</blockquote>
<p>In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5</p> | {
"question_id": 1414365,
"question_date": "2009-09-12T05:21:54.273Z",
"question_score": 2486,
"tags": "javascript|jquery|html-input|disabled-input",
"answer_id": 1414366,
"answer_date": "2009-09-12T05:23:34.067Z",
"answer_score": 4059
} |
Please answer the following Stack Overflow question:
Title: Get all unique values in a JavaScript array (remove duplicates)
<p>I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found <a href="https://stackoverflow.com/questions/1890203">this other script</a> here on Stack Overflow that looks almost exactly like it, but it doesn't fail.</p>
<p>So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?</p>
<pre><code>Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
</code></pre>
<h3>More answers from duplicate question:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/9229645">Remove duplicate values from JS array</a></li>
</ul>
<h3>Similar question:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/840781">Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array</a></li>
</ul> | <p>With <em>JavaScript 1.6</em> / <em>ECMAScript 5</em> you can use the native <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer" title="filter"><code>filter</code></a> method of an Array in the following way to get an array with unique values:</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 onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);
console.log(unique); // ['a', 1, 2, '1']</code></pre>
</div>
</div>
</p>
<p>The native method <code>filter</code> will loop through the array and leave only those entries that pass the given callback function <code>onlyUnique</code>.</p>
<p><code>onlyUnique</code> checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.</p>
<p>This solution works without any extra library like jQuery or prototype.js.</p>
<p>It works for arrays with mixed value types too.</p>
<p>For old Browsers (<ie9), that do not support the native methods <code>filter</code> and <code>indexOf</code> you can find work arounds in the MDN documentation for <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer" title="filter">filter</a> and <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer">indexOf</a>.</p>
<p>If you want to keep the last occurrence of a value, simply replace <code>indexOf</code> with <code>lastIndexOf</code>.</p>
<p>With ES6 this can be shorten to:</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>// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i);
console.log(unique); // unique is ['a', 1, 2, '1']</code></pre>
</div>
</div>
</p>
<p>Thanks to <a href="https://stackoverflow.com/users/124119/camilo-martin">Camilo Martin</a> for hint in comment.</p>
<p>ES6 has a native object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="noreferrer"><code>Set</code></a> to store unique values. To get an array with unique values you could now do this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray = ['a', 1, 'a', 2, '1'];
let unique = [...new Set(myArray)];
console.log(unique); // unique is ['a', 1, 2, '1']</code></pre>
</div>
</div>
</p>
<p>The constructor of <code>Set</code> takes an iterable object, like an Array, and the spread operator <code>...</code> transform the set back into an Array. Thanks to <a href="https://stackoverflow.com/users/1737158/lukas-liesis">Lukas Liese</a> for hint in comment.</p> | {
"question_id": 1960473,
"question_date": "2009-12-25T04:28:23.840Z",
"question_score": 2483,
"tags": "javascript|unique|arrays",
"answer_id": 14438954,
"answer_date": "2013-01-21T12:46:24.917Z",
"answer_score": 4136
} |
Please answer the following Stack Overflow question:
Title: How do I give text or an image a transparent background using CSS?
<p>Is it possible, using CSS only, to make the <code>background</code> of an element semi-transparent but have the content (text & images) of the element opaque?</p>
<p>I'd like to accomplish this without having the text and the background as two separate elements.</p>
<p>When trying:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
position: absolute;
background-color: green;
filter: alpha(opacity=60);
opacity: 0.6;
}
span {
color: white;
filter: alpha(opacity=100);
opacity: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
<span>Hello world</span>
</p></code></pre>
</div>
</div>
</p>
<p>It looks like child elements are subjected to the opacity of their parents, so <code>opacity:1</code> is relative to the <code>opacity:0.6</code> of the parent.</p> | <p>Either use a semi-transparent <a href="http://en.wikipedia.org/wiki/Portable_Network_Graphics" rel="noreferrer">PNG</a> or <a href="https://en.wikipedia.org/wiki/Scalable_Vector_Graphics" rel="noreferrer">SVG</a> image or use CSS:</p>
<pre class="lang-css prettyprint-override"><code>background-color: rgba(255, 0, 0, 0.5);
</code></pre>
<p>Here's an article from css3.info, <em><a href="http://www.css3.info/opacity_rgba_and_compromise" rel="noreferrer">Opacity, RGBA and compromise</a></em> (2007-06-03).</p>
<p>Beware that the text still <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast" rel="noreferrer">needs sufficient contrast</a> with the background, once the underlying background shines through.</p>
<hr />
<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><p style="background-color: rgba(255, 0, 0, 0.5);">
<span>Hello, World!</span>
</p></code></pre>
</div>
</div>
</p> | {
"question_id": 806000,
"question_date": "2009-04-30T09:00:02.460Z",
"question_score": 2475,
"tags": "html|css|opacity",
"answer_id": 806189,
"answer_date": "2009-04-30T09:52:43.940Z",
"answer_score": 2376
} |
Please answer the following Stack Overflow question:
Title: How do I "git clone" a repo, including its submodules?
<p>How do I clone a git repository so that it also clones its submodules?</p>
<p>Running <code>git clone $REPO_URL</code> merely creates empty submodule directories.</p> | <p>With version 2.13 of Git and later, <code>--recurse-submodules</code> can be used instead of <code>--recursive</code>:</p>
<pre><code>git clone --recurse-submodules -j8 git://github.com/foo/bar.git
cd bar
</code></pre>
<p><sup>Editor’s note: <code>-j8</code> is an optional performance optimization that became available in version 2.8, and fetches up to 8 submodules at a time in parallel — see <code>man git-clone</code>.</sup></p>
<p>With version 1.9 of Git up until version 2.12 (<code>-j</code> flag only available in version 2.8+):</p>
<pre><code>git clone --recursive -j8 git://github.com/foo/bar.git
cd bar
</code></pre>
<p>With version 1.6.5 of Git and later, you can use:</p>
<pre><code>git clone --recursive git://github.com/foo/bar.git
cd bar
</code></pre>
<p>For already cloned repos, or older Git versions, use:</p>
<pre><code>git clone git://github.com/foo/bar.git
cd bar
git submodule update --init --recursive
</code></pre> | {
"question_id": 3796927,
"question_date": "2010-09-26T07:13:25.943Z",
"question_score": 2473,
"tags": "git|git-submodules",
"answer_id": 4438292,
"answer_date": "2010-12-14T10:43:12.717Z",
"answer_score": 3504
} |
Please answer the following Stack Overflow question:
Title: Catch multiple exceptions at once?
<p>It is discouraged to simply catch <code>System.Exception</code>. Instead, only the "known" exceptions should be caught.</p>
<p>Now, this sometimes leads to unnecessary repetitive code, for example:</p>
<pre><code>try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
</code></pre>
<p>I wonder: Is there a way to catch both exceptions and only call the <code>WebId = Guid.Empty</code> call once?</p>
<p>The given example is rather simple, as it's only a <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer"><code>GUID</code></a>. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the <code>object</code>. However, if there is an unexpected exception, I still want to throw that higher.</p> | <p>Catch <code>System.Exception</code> and switch on the types</p>
<pre><code>catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
throw;
}
</code></pre> | {
"question_id": 136035,
"question_date": "2008-09-25T20:56:08.513Z",
"question_score": 2473,
"tags": "c#|.net|exception",
"answer_id": 136092,
"answer_date": "2008-09-25T21:01:49.530Z",
"answer_score": 2384
} |
Please answer the following Stack Overflow question:
Title: How to list only the names of files that changed between two commits
<p>I have a bunch of commits in the repository. I want to see a list of files changed between two commits - from <em>SHA1</em> to <em>SHA2</em>.</p>
<p>What command should I use?</p> | <pre><code>git diff --name-only SHA1 SHA2
</code></pre>
<p>where you only need to include enough of the SHA hash to identify the commits. You can also do, for example</p>
<pre><code>git diff --name-only HEAD~10 HEAD~5
</code></pre>
<p>to see the differences between the tenth latest commit and the fifth latest (or so).</p> | {
"question_id": 1552340,
"question_date": "2009-10-12T01:48:06.630Z",
"question_score": 2470,
"tags": "git|git-diff",
"answer_id": 1552353,
"answer_date": "2009-10-12T01:51:34.630Z",
"answer_score": 3321
} |
Please answer the following Stack Overflow question:
Title: Get selected text from a drop-down list (select box) using jQuery
<p>How can I get the selected text (not the selected value) from a <strong>drop-down list</strong> in jQuery?</p> | <pre><code>$("#yourdropdownid option:selected").text();
</code></pre> | {
"question_id": 1643227,
"question_date": "2009-10-29T12:02:09.297Z",
"question_score": 2468,
"tags": "javascript|jquery|dom|drop-down-menu|jquery-selectors",
"answer_id": 1643247,
"answer_date": "2009-10-29T12:05:38.997Z",
"answer_score": 3970
} |
Please answer the following Stack Overflow question:
Title: How to make a great R reproducible example
<p>When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on Stack Overflow, a <a href="https://stackoverflow.com/help/mcve">reproducible example</a> is often asked and always helpful.</p>
<p>What are your tips for creating an excellent example? How do you paste data structures from <a href="/questions/tagged/r" class="post-tag" title="show questions tagged 'r'" rel="tag">r</a> in a text format? What other information should you include?</p>
<p>Are there other tricks in addition to using <code>dput()</code>, <code>dump()</code> or <code>structure()</code>? When should you include <code>library()</code> or <code>require()</code> statements? Which reserved words should one avoid, in addition to <code>c</code>, <code>df</code>, <code>data</code>, etc.?</p>
<p>How does one make a great <a href="/questions/tagged/r" class="post-tag" title="show questions tagged 'r'" rel="tag">r</a> reproducible example?</p> | <p>Basically, a <a href="https://stackoverflow.com/help/minimal-reproducible-example"><strong>minimal reproducible example (MRE)</strong></a> should enable others to <em>exactly</em> reproduce your issue on their machines.</p>
<p><strong>Please do not post images of your data, code, or console output!</strong></p>
<h1>tl;dr</h1>
<p>A MRE consists of the following items:</p>
<ul>
<li>a <strong>minimal dataset</strong>, necessary to demonstrate the problem</li>
<li>the <strong>minimal <em>runnable</em> code</strong> necessary to reproduce the issue, which can be run on the given dataset</li>
<li>all <strong>necessary information</strong> on the used <code>library</code>s, the R version, and the OS it is run on, perhaps a <code>sessionInfo()</code></li>
<li>in the case of random processes, a <strong>seed</strong> (set by <code>set.seed()</code>) to enable others to replicate exactly the same results as you do</li>
</ul>
<p>For examples of good MREs, see section "Examples" at the bottom of help pages on the function you are using. Simply type e.g. <code>help(mean)</code>, or short <code>?mean</code> into your R console.</p>
<h1>Providing a minimal dataset</h1>
<p>Usually, sharing huge data sets is not necessary and may rather discourage others from reading your question. Therefore, it is better to use built-in datasets or create a small "toy" example that resembles your original data, which is actually what is meant by <em>minimal</em>. If for some reason you really need to share your original data, you should use a method, such as <code>dput()</code>, that allows others to get an exact copy of your data.</p>
<h3>Built-in datasets</h3>
<p>You can use one of the built-in datasets. A comprehensive list of built-in datasets can be seen with <code>data()</code>. There is a short description of every data set, and more information can be obtained, e.g. with <code>?iris</code>, for the 'iris' data set that comes with R. Installed packages might contain additional datasets.</p>
<h3>Creating example data sets</h3>
<p><em>Preliminary note:</em> Sometimes you may need special formats (i.e. classes), such as factors, dates, or time series. For these, make use of functions like: <code>as.factor</code>, <code>as.Date</code>, <code>as.xts</code>, ... <em>Example:</em></p>
<pre><code>d <- as.Date("2020-12-30")
</code></pre>
<p>where</p>
<pre><code>class(d)
# [1] "Date"
</code></pre>
<p><strong>Vectors</strong></p>
<pre><code>x <- rnorm(10) ## random vector normal distributed
x <- runif(10) ## random vector uniformly distributed
x <- sample(1:100, 10) ## 10 random draws out of 1, 2, ..., 100
x <- sample(LETTERS, 10) ## 10 random draws out of built-in latin alphabet
</code></pre>
<p><strong>Matrices</strong></p>
<pre><code>m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))
m
# A B C D
# A 1 4 7 10
# B 2 5 8 11
# C 3 6 9 12
</code></pre>
<p><strong>Data frames</strong></p>
<pre><code>set.seed(42) ## for sake of reproducibility
n <- 6
dat <- data.frame(id=1:n,
date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
group=rep(LETTERS[1:2], n/2),
age=sample(18:30, n, replace=TRUE),
type=factor(paste("type", 1:n)),
x=rnorm(n))
dat
# id date group age type x
# 1 1 2020-12-26 A 27 type 1 0.0356312
# 2 2 2020-12-27 B 19 type 2 1.3149588
# 3 3 2020-12-28 A 20 type 3 0.9781675
# 4 4 2020-12-29 B 26 type 4 0.8817912
# 5 5 2020-12-30 A 26 type 5 0.4822047
# 6 6 2020-12-31 B 28 type 6 0.9657529
</code></pre>
<p><sup><strong>Note:</strong> Although it is widely used, better do not name your data frame <code>df</code>, because <code>df()</code> is an R function for the density (i.e. height of the curve at point <code>x</code>) of the F distribution and you might get a clash with it.</sup></p>
<h3>Copying original data</h3>
<p>If you have a specific reason, or data that would be too difficult to construct an example from, you could provide a small subset of your original data, best by using <code>dput</code>.</p>
<p><strong>Why use <code>dput()</code>?</strong></p>
<p><code>dput</code> throws all information needed to exactly reproduce your data on your console. You may simply copy the output and paste it into your question.</p>
<p>Calling <code>dat</code> (from above) produces output that still lacks information about variable classes and other features if you share it in your question. Furthermore, the spaces in the <code>type</code> column make it difficult to do anything with it. Even when we set out to use the data, we won't manage to get important features of your data right.</p>
<pre><code> id date group age type x
1 1 2020-12-26 A 27 type 1 0.0356312
2 2 2020-12-27 B 19 type 2 1.3149588
3 3 2020-12-28 A 20 type 3 0.9781675
</code></pre>
<p><strong>Subset your data</strong></p>
<p>To share a subset, use <code>head()</code>, <code>subset()</code> or the indices <code>iris[1:4, ]</code>. Then wrap it into <code>dput()</code> to give others something that can be put in R immediately. <em>Example</em></p>
<pre><code>dput(iris[1:4, ]) # first four rows of the iris data set
</code></pre>
<p><em>Console output to share in your question:</em></p>
<pre><code>structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), row.names = c(NA,
4L), class = "data.frame")
</code></pre>
<p>When using <code>dput</code>, you may also want to include only relevant columns, e.g. dput(mtcars[1:3, c(2, 5, 6)])</p>
<p><sub><strong>Note:</strong> If your data frame has a factor with many levels, the <code>dput</code> output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the subset of your data. To solve this issue, you can use the <code>droplevels()</code> function. Notice below how species is a factor with only one level, e.g. <code>dput(droplevels(iris[1:4, ]))</code>. One other caveat for <code>dput</code> is that it will not work for keyed <code>data.table</code> objects or for grouped <code>tbl_df</code> (class <code>grouped_df</code>) from the <code>tidyverse</code>. In these cases you can convert back to a regular data frame before sharing, <code>dput(as.data.frame(my_data))</code>.</sub></p>
<h1>Producing minimal code</h1>
<p>Combined with the minimal data (see above), your code should exactly reproduce the problem on another machine by simply copying and pasting it.</p>
<p>This should be the easy part but often isn't. What you should not do:</p>
<ul>
<li>showing all kinds of data conversions; make sure the provided data is already in the correct format (unless that is the problem, of course)</li>
<li>copy-paste a whole script that gives an error somewhere. Try to locate which lines exactly result in the error. More often than not, you'll find out what the problem is yourself.</li>
</ul>
<p>What you should do:</p>
<ul>
<li>add which packages you use if you use any (using <code>library()</code>)</li>
<li>test run your code in a fresh R session to ensure the code is runnable. People should be able to copy-paste your data and your code in the console and get the same as you have.</li>
<li>if you open connections or create files, add some code to close them or delete the files (using <code>unlink()</code>)</li>
<li>if you change options, make sure the code contains a statement to revert them back to the original ones. (eg <code>op <- par(mfrow=c(1,2)) ...some code... par(op)</code> )</li>
</ul>
<h1>Providing necessary information</h1>
<p>In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of <code>sessionInfo()</code> can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible, also the necessary information on the setup.</p>
<p>If you are running R in <em>R Studio</em>, using <code>rstudioapi::versionInfo()</code> can help report your RStudio version.</p>
<p>If you have a problem with a specific package, you may want to provide the package version by giving the output of <code>packageVersion("name of the package")</code>.</p>
<h1>Seed</h1>
<p>Using <code>set.seed()</code> you may specify a seed<sup>1</sup>, i.e. the specific state, R's random number generator is fixed. This makes it possible for random functions, such as <code>sample()</code>, <code>rnorm()</code>, <code>runif()</code> and lots of others, to always return the same result, <em>Example:</em></p>
<pre><code>set.seed(42)
rnorm(3)
# [1] 1.3709584 -0.5646982 0.3631284
set.seed(42)
rnorm(3)
# [1] 1.3709584 -0.5646982 0.3631284
</code></pre>
<p><sup>1</sup><sub> <strong>Note:</strong> The output of <code>set.seed()</code> differs between R >3.6.0 and previous versions. Specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the <code>RNGversion()</code>-function before <code>set.seed()</code> (e.g.: <code>RNGversion("3.5.2")</code>).</sub></p> | {
"question_id": 5963269,
"question_date": "2011-05-11T11:12:02.357Z",
"question_score": 2468,
"tags": "r|r-faq",
"answer_id": 5963610,
"answer_date": "2011-05-11T11:40:18.877Z",
"answer_score": 1905
} |
Please answer the following Stack Overflow question:
Title: How do I show the changes which have been staged?
<p>I staged a few changes to be committed. How do I see the diffs of all files which are staged for the next commit? Is there a handy one-liner for this?</p>
<p><a href="http://git-scm.com/docs/git-status" rel="noreferrer"><code>git status</code></a> only shows names of files which are staged, but I want to see the actual diffs.</p>
<p>The <a href="http://git-scm.com/docs/git-diff" rel="noreferrer"><code>git-diff(1)</code></a> man page says:</p>
<blockquote>
<p>git diff [--options] [--] […]</p>
<p>This form is to view the changes you made relative to the index (staging area for the next commit). In other words, the differences are what you <em>could</em> tell git to further add to the index but you still haven't. You can stage these changes by using git-add(1).</p>
</blockquote> | <p>It should just be:</p>
<pre><code>git diff --cached
</code></pre>
<p><code>--cached</code> means show the changes in the cache/index (i.e. staged changes) against the current <code>HEAD</code>. <code>--staged</code> is a synonym for <code>--cached</code>.</p>
<p><code>--staged</code> and <code>--cached</code> does not point to <code>HEAD</code>, just difference with respect to <code>HEAD</code>. If you cherry pick what to commit using <code>git add --patch</code> (or <code>git add -p</code>), <code>--staged</code> will return what is staged.</p> | {
"question_id": 1587846,
"question_date": "2009-10-19T09:57:27.417Z",
"question_score": 2464,
"tags": "git|diff|dvcs|git-diff|git-stage",
"answer_id": 1587877,
"answer_date": "2009-10-19T10:07:10.820Z",
"answer_score": 2977
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.