input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How to list all Git tags?
<p>In my repository, I have created tags using the following commands. </p>
<pre><code>git tag v1.0.0 -m 'finally a stable release'
git tag v2.0.0 -m 'oops, there was still a major bug!'
</code></pre>
<p>How do you list all the tags in the repository?</p> | <pre><code>git tag
</code></pre>
<p>should be enough. See <a href="http://git-scm.com/docs/git-tag" rel="noreferrer"><code>git tag</code> man page</a></p>
<hr />
<p>You also have:</p>
<pre><code>git tag -l <pattern>
</code></pre>
<blockquote>
<p>List tags with names that match the given pattern (or all if no pattern is given).<br />
Typing "git tag" without arguments, also lists all tags.</p>
</blockquote>
<hr />
<p>More recently ("<a href="https://stackoverflow.com/a/22634649/6309">How to sort git tags?</a>", for Git 2.0+)</p>
<pre><code>git tag --sort=<type>
</code></pre>
<blockquote>
<p>Sort in a specific order.</p>
<p>Supported type is:</p>
<ul>
<li>"<code>refname</code>" (lexicographic order),</li>
<li>"<code>version:refname</code>" or "<code>v:refname</code>" (tag names are treated as versions).</li>
</ul>
<p>Prepend "<code>-</code>" to reverse sort order.</p>
</blockquote>
<hr />
<p>That lists both:</p>
<ul>
<li><strong><a href="http://git-scm.com/book/en/Git-Basics-Tagging#Annotated-Tags" rel="noreferrer">annotated tags</a></strong>: full objects stored in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).</li>
<li><strong><a href="http://git-scm.com/book/en/Git-Basics-Tagging#Lightweight-Tags" rel="noreferrer">lightweight tags</a></strong>: simple pointer to an existing commit</li>
</ul>
<p>Note: the <a href="http://www.gitready.com/beginner/2009/02/03/tagging.html" rel="noreferrer">git ready article on tagging</a> disapproves of lightweight tag.</p>
<blockquote>
<p>Without arguments, git tag creates a “lightweight” tag that is basically a branch that never moves.<br />
Lightweight tags are still useful though, perhaps for marking a known good (or bad) version, or a bunch of commits you may need to use in the future.<br />
Nevertheless, <strong>you probably don’t want to push these kinds of tags</strong>.</p>
<p>Normally, you want to at least pass the -a option to create an unsigned tag, or sign the tag with your GPG key via the -s or -u options.</p>
</blockquote>
<hr />
<p>That being said, <strong><a href="https://stackoverflow.com/users/19563/charles-bailey">Charles Bailey</a></strong> points out that a '<code>git tag -m "..."</code>' actually implies a proper (unsigned annotated) tag (option '<code>-a</code>'), and not a lightweight one. So you are good with your initial command.</p>
<hr />
<p>This differs from:</p>
<pre><code>git show-ref --tags -d
</code></pre>
<p>Which lists tags with their commits (see "<a href="https://stackoverflow.com/q/8796522/6309">Git Tag list, display commit sha1 hashes</a>").<br />
Note the <code>-d</code> in order to dereference the annotated tag object (which have their own commit SHA1) and display the actual tagged commit.</p>
<p>Similarly, <code>git show --name-only <aTag></code> would list the tag and associated commit.</p>
<p>Note: <a href="https://stackoverflow.com/a/72649946/6309">use Git 2.37</a> with <code>git show-ref --heads/--tags</code>.</p> | {
"question_id": 1064499,
"question_date": "2009-06-30T15:52:36.140Z",
"question_score": 823,
"tags": "git|git-tag",
"answer_id": 1064505,
"answer_date": "2009-06-30T15:53:32.410Z",
"answer_score": 1140
} |
Please answer the following Stack Overflow question:
Title: How to access the first property of a Javascript object?
<p>Is there an elegant way to access the first property of an object...</p>
<ol>
<li>where you don't know the name of your properties</li>
<li>without using a loop like <code>for .. in</code> or jQuery's <code>$.each</code></li>
</ol>
<p>For example, I need to access <code>foo1</code> object without knowing the name of foo1:</p>
<pre><code>var example = {
foo1: { /* stuff1 */},
foo2: { /* stuff2 */},
foo3: { /* stuff3 */}
};
</code></pre> | <pre><code>var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
Object.values(obj)[0]; // returns 'someVal'
</code></pre>
<p>Using this you can access also other properties by indexes. Be aware tho! <code>Object.keys</code> or <code>Object.values</code> return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read <a href="https://stackoverflow.com/a/23202095">https://stackoverflow.com/a/23202095</a> for details on this.</p> | {
"question_id": 983267,
"question_date": "2009-06-11T19:55:12.820Z",
"question_score": 823,
"tags": "javascript|object",
"answer_id": 11509718,
"answer_date": "2012-07-16T17:48:22.943Z",
"answer_score": 1763
} |
Please answer the following Stack Overflow question:
Title: How to apply !important using .css()?
<p>I am having trouble applying a style that is <code>!important</code>. I’ve tried:</p>
<pre class="lang-js prettyprint-override"><code>$("#elem").css("width", "100px !important");
</code></pre>
<p>This does <strong>nothing</strong>; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite <code>cssText</code> (which would mean I’d need to parse it first, etc.)?</p>
<p><strong>Edit</strong>: I should add that I have a stylesheet with an <code>!important</code> style that I am trying to override with an <code>!important</code> style inline, so using <code>.width()</code> and the like does not work since it gets overridden by my external <code>!important</code> style.</p>
<p>Also, the value that will override the previous value <strong>is computed</strong>, so I cannot simply create another external style.</p> | <p>Most of these answers are now outdated, IE7 support is not an issue.</p>
<p>The best way to do this that <strong>supports IE11+ and all modern browsers</strong> is:</p>
<pre><code>const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');
</code></pre>
<hr>
<p>Or if you want, you can create a small jQuery plugin that does this.
This plugin closely matches jQuery's own <code>css()</code> method in the parameters it supports:</p>
<pre><code>/**
* Sets a CSS style on the selected element(s) with !important priority.
* This supports camelCased CSS style property names and calling with an object
* like the jQuery `css()` method.
* Unlike jQuery's css() this does NOT work as a getter.
*
* @param {string|Object<string, string>} name
* @param {string|undefined} value
*/
jQuery.fn.cssImportant = function(name, value) {
const $this = this;
const applyStyles = (n, v) => {
// Convert style name from camelCase to dashed-case.
const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
return m1 + "-" + upper.toLowerCase() + m2;
});
// Loop over each element in the selector and set the styles.
$this.each(function(){
this.style.setProperty(dashedName, v, 'important');
});
};
// If called with the first parameter that is an object,
// Loop over the entries in the object and apply those styles.
if(jQuery.isPlainObject(name)){
for(const [n, v] of Object.entries(name)){
applyStyles(n, v);
}
} else {
// Otherwise called with style name and value.
applyStyles(name, value);
}
// This is required for making jQuery plugin calls chainable.
return $this;
};
</code></pre>
<pre><code>// Call the new plugin:
$('#elem').cssImportant('height', '100px');
// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});
// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');
</code></pre>
<p><a href="https://jsfiddle.net/8rytensh/8/" rel="noreferrer">Example jsfiddle here</a>.</p> | {
"question_id": 2655925,
"question_date": "2010-04-16T20:31:13.060Z",
"question_score": 823,
"tags": "javascript|jquery|html|css",
"answer_id": 59073080,
"answer_date": "2019-11-27T15:04:10.720Z",
"answer_score": 26
} |
Please answer the following Stack Overflow question:
Title: How can I deal with this Git warning? "Pulling without specifying how to reconcile divergent branches is discouraged"
<p>After a <code>git pull origin master</code>, I get the following message:</p>
<pre><code>warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:
git config pull.rebase false # merge (the default strategy)
git config pull.rebase true # rebase
git config pull.ff only # fast-forward only
You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), 51.49 KiB | 850.00 KiB/s, done.
</code></pre>
<p>The pull seems successful, but I am unsure.</p>
<p>What can I do to fix this?</p> | <blockquote>
<p>In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD.</p>
</blockquote>
<p>When you do a <code>git pull origin master</code>, <br>
<code>git pull</code> performs a merge, which often creates a merge commit. Therefore, by default, pulling from the remote is <em>not</em> a harmless operation: it can create a new commit SHA hash value that didn’t exist before. This behavior can confuse a user, because what feels like it should be a harmless download operation actually changes the commit history in unpredictable ways.</p>
<p>To avoid this, you need</p>
<pre><code>git pull --ff-only
</code></pre>
<p>(or not? read on to see which one fits your requirements)</p>
<p>With <code>git pull --ff-only</code>, Git will update your branch only if it can be “fast-forwarded” without creating new commits. If this can’t be done, <code>git pull --ff-only</code> simply aborts with an error message.</p>
<p>You can configure your Git client to always use <code>--ff-only</code> by default, so you get this behavior even if you forget the command-line flag:</p>
<pre><code>git config --global pull.ff only
</code></pre>
<p>Note: The <code>--global</code> flag applies the change for all repositories on your machine. If you want this behaviour only for the repository you're in, omit the flag.</p>
<p>Taken from <a href="https://blog.sffc.xyz/post/185195398930/why-you-should-use-git-pull-ff-only" rel="noreferrer">here</a>
<br></p>
<hr />
<br>
<p>This warning was added in Git 2.27.</p>
<p>This is what the complete warning looks like:</p>
<blockquote>
<p>Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull: <br> <br>
git config pull.rebase false # merge (the default strategy) <br>
git config pull.rebase true # rebase <br>
git config pull.ff only # fast-forward only <br> <br>
You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.</p>
</blockquote>
<p>The warning presents three commands as options, all of these will suppress the warning. But they serve different purposes:</p>
<pre><code>git config pull.rebase false # merge (the default strategy)
</code></pre>
<p>This keeps the default behaviour and suppresses the warning.</p>
<pre><code>git config pull.rebase true # rebase
</code></pre>
<p>This actually commits on top of the remote branch, maintaining a single branch both locally and remotely (unlike the default behaviour where two different branches are involved - one on local and the other on remote - and, to combine the two, a merge is performed).</p>
<pre><code>git config pull.ff only # fast-forward only
</code></pre>
<p>This only performs the pull if the local branch can be fast-forwarded. If not, it simply aborts with an error message (and does not create any commits).</p>
<hr />
<p><strong>Update:</strong> <br></p>
<p>If you have Git 2.29 or above, you can now set <code>pull.ff</code> to <code>false</code>, <code>true</code> or <code>only</code> to get rid of the warning.</p>
<pre><code>git config pull.ff true
</code></pre>
<p><code>true</code> - This is the default behaviour. Pull is fast-forwarded if possible, otherwise it's merged.</p>
<pre><code>git config pull.ff false
</code></pre>
<p><code>false</code> - Pull is never fast-forwarded, and a merge is always created.</p>
<pre><code>git config pull.ff only
</code></pre>
<p><code>only</code> - Pull is fast-forwarded if possible, otherwise operation is aborted with an error message.</p>
<hr />
<p><strong>Note:</strong> You may want to keep an eye on <a href="https://stackoverflow.com/users/6309/vonc">VonC</a>'s answer <a href="https://stackoverflow.com/a/64163084/10625611">here</a> for updates on changes made to this feature in future updates.</p> | {
"question_id": 62653114,
"question_date": "2020-06-30T08:18:57.140Z",
"question_score": 823,
"tags": "git",
"answer_id": 62653400,
"answer_date": "2020-06-30T08:34:10.610Z",
"answer_score": 814
} |
Please answer the following Stack Overflow question:
Title: What is the difference between range and xrange functions in Python 2.X?
<p>Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about</p>
<pre><code>for i in range(0, 20):
for i in xrange(0, 20):
</code></pre> | <p><strong>In Python 2.x:</strong></p>
<ul>
<li><p><code>range</code> creates a list, so if you do <code>range(1, 10000000)</code> it creates a list in memory with <code>9999999</code> elements.</p>
</li>
<li><p><code>xrange</code> is a sequence object that evaluates lazily.</p>
</li>
</ul>
<p><strong>In Python 3:</strong></p>
<ul>
<li><code>range</code> does the equivalent of Python 2's <code>xrange</code>. To get the list, you have to explicitly use <code>list(range(...))</code>.</li>
<li><code>xrange</code> no longer exists.</li>
</ul> | {
"question_id": 94935,
"question_date": "2008-09-18T17:52:51.143Z",
"question_score": 823,
"tags": "python|loops|range|python-2.x|xrange",
"answer_id": 94962,
"answer_date": "2008-09-18T17:55:13.913Z",
"answer_score": 982
} |
Please answer the following Stack Overflow question:
Title: Hiding the scroll bar on an HTML page
<p>Can CSS be used to hide the scroll bar? How would you do this?</p> | <p>Set <strong><a href="https://developer.mozilla.org/docs/Web/CSS/overflow#values" rel="nofollow noreferrer"><code>overflow: hidden;</code></a></strong> on the <code>body</code> tag like this:</p>
<pre><code><style type="text/css">
body {
overflow: hidden;
}
</style>
</code></pre>
<p>The code above "hides" both the horizontal and vertical scrollbars.</p>
<p>If you want to hide <strong>only the vertical scrollbar</strong>, use <a href="https://developer.mozilla.org/docs/Web/CSS/overflow-y" rel="nofollow noreferrer"><code>overflow-y</code></a>:</p>
<pre><code><style type="text/css">
body {
overflow-y: hidden;
}
</style>
</code></pre>
<p>And if you want to hide <strong>only the horizontal scrollbar</strong>, use <a href="https://developer.mozilla.org/docs/Web/CSS/overflow-x" rel="nofollow noreferrer"><code>overflow-x</code></a>:</p>
<pre><code><style type="text/css">
body {
overflow-x: hidden;
}
</style>
</code></pre>
<hr />
<blockquote>
<p>Content is clipped if necessary to fit the padding box. No scrollbars are provided, and no support for allowing the user to scroll (such as by dragging or using a scroll wheel) is allowed. The content can be scrolled programmatically (for example, by setting the value of a property such as <a href="https://developer.mozilla.org/docs/Web/API/HTMLElement/offsetLeft" rel="nofollow noreferrer"><code>offsetLeft</code></a>), so <em>the element <strong>is</strong> still a scroll container</em>. <sub>(<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/overflow#values" rel="nofollow noreferrer">source</a>)</sub></p>
</blockquote> | {
"question_id": 3296644,
"question_date": "2010-07-21T05:57:43.340Z",
"question_score": 822,
"tags": "css|browser|scrollbar",
"answer_id": 3296701,
"answer_date": "2010-07-21T06:09:27.763Z",
"answer_score": 432
} |
Please answer the following Stack Overflow question:
Title: Finding diff between current and last version
<p>Using Git, how can you find the difference between the current and the last version?</p>
<pre><code>git diff last version:HEAD
</code></pre> | <p>I don't really understand the meaning of "last version".</p>
<p>As the previous commit can be accessed with HEAD^, I think that you are looking for something like:</p>
<pre><code>git diff HEAD^ HEAD
</code></pre>
<p>That also can be applied for a :commithash</p>
<pre><code>git diff $commithash^ $commithash
</code></pre>
<p>As of Git 1.8.5, <code>@</code> is an alias for <code>HEAD</code>, so you can use:</p>
<pre><code>git diff @~..@
</code></pre>
<p>The following will also work:</p>
<pre><code>git show
</code></pre>
<p>If you want to know the diff between head and any commit you can use:</p>
<pre><code>git diff commit_id HEAD
</code></pre>
<p>And this will launch your visual diff tool (if configured):</p>
<pre><code>git difftool HEAD^ HEAD
</code></pre>
<p>Since comparison to HEAD is default you can omit it (as pointed out by <a href="https://stackoverflow.com/a/26771459/5124673">Orient</a>):</p>
<pre><code>git diff @^
git diff HEAD^
git diff commit_id
</code></pre>
<h2>Warnings</h2>
<ul>
<li>@ScottF and @Panzercrisis explain in the comments that on Windows the <code>~</code> character must be used instead of <code>^</code>.</li>
</ul> | {
"question_id": 9903541,
"question_date": "2012-03-28T08:15:24.363Z",
"question_score": 822,
"tags": "git",
"answer_id": 9903611,
"answer_date": "2012-03-28T08:19:39.120Z",
"answer_score": 1453
} |
Please answer the following Stack Overflow question:
Title: Can the :not() pseudo-class have multiple arguments?
<p>I'm trying to select <code>input</code> elements of all <code>type</code>s except <code>radio</code> and <code>checkbox</code>.</p>
<p>Many people have shown that you can put multiple arguments in <code>:not</code>, but using <code>type</code> doesn't seem to work anyway I try it.</p>
<pre class="lang-css prettyprint-override"><code>form input:not([type="radio"], [type="checkbox"]) {
/* css here */
}
</code></pre>
<p>Any ideas?</p> | <p>Why :not just use two <code>:not</code>:</p>
<pre><code>input:not([type="radio"]):not([type="checkbox"])
</code></pre>
<p><sub><em>Yes, it is intentional</em></sub></p> | {
"question_id": 5684160,
"question_date": "2011-04-16T02:43:33.953Z",
"question_score": 822,
"tags": "css|css-selectors",
"answer_id": 5684168,
"answer_date": "2011-04-16T02:45:19.237Z",
"answer_score": 1641
} |
Please answer the following Stack Overflow question:
Title: Random number generator only generating one random number
<p>I have the following function:</p>
<pre><code>//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
</code></pre>
<p>How I call it:</p>
<pre><code>byte[] mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);
</code></pre>
<p>If I step that loop with the debugger during runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the <code>mac</code> array have equal value.</p>
<p>Why does that happen?</p> | <p>Every time you do <code>new Random()</code> it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single <a href="https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8" rel="noreferrer">Random</a> instance and keep using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=netframework-4.8#System_Random_Next" rel="noreferrer">Next</a> on the <strong>same</strong> instance.</p>
<pre><code>//Function to get a random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}
</code></pre>
<hr>
<p>Edit (see comments): why do we need a <code>lock</code> here?</p>
<p>Basically, <code>Next</code> is going to change the internal state of the <code>Random</code> instance. If we do that at the same time from multiple threads, you <em>could</em> argue "we've just made the outcome even more random", but what we are <em>actually</em> doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which <em>might</em> be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since <code>Random</code> does <strong>not</strong> make any guarantees of thread-safety. Thus there are two valid approaches:</p>
<ul>
<li>Synchronize so that we don't access it at the same time from different threads</li>
<li>Use different <code>Random</code> instances per thread</li>
</ul>
<p>Either can be fine; but mutexing a <strong>single</strong> instance from multiple callers at the same time is just asking for trouble.</p>
<p>The <code>lock</code> achieves the first (and simpler) of these approaches; however, another approach might be: </p>
<pre><code>private static readonly ThreadLocal<Random> appRandom
= new ThreadLocal<Random>(() => new Random());
</code></pre>
<p>this is then per-thread, so you don't need to synchronize. </p> | {
"question_id": 767999,
"question_date": "2009-04-20T12:11:24.717Z",
"question_score": 822,
"tags": "c#|random",
"answer_id": 768001,
"answer_date": "2009-04-20T12:12:30.317Z",
"answer_score": 1131
} |
Please answer the following Stack Overflow question:
Title: Remove border from IFrame
<p>How would I remove the border from an iframe embedded in my web app? An example of the iframe is:</p>
<pre><code><iframe src="myURL" width="300" height="300">Browser not compatible.</iframe>
</code></pre>
<p>I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.</p> | <p>Add the <code>frameBorder</code> attribute (note the <strong>capital ‘B’</strong>).</p>
<p>So it would look like:</p>
<pre><code><iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>
</code></pre> | {
"question_id": 65034,
"question_date": "2008-09-15T17:43:53.263Z",
"question_score": 821,
"tags": "html|css|iframe|internet-explorer-6|noborder",
"answer_id": 65052,
"answer_date": "2008-09-15T17:45:47.487Z",
"answer_score": 1267
} |
Please answer the following Stack Overflow question:
Title: How to run multiple .BAT files within a .BAT file
<p>I'm trying to get my <code>commit-build.bat</code> to execute other .BAT files as part of our build process.</p>
<p>Content of <code>commit-build.bat</code>:</p>
<pre><code>"msbuild.bat"
"unit-tests.bat"
"deploy.bat"
</code></pre>
<p>This seems simple enough, but <code>commit-build.bat</code> only executes the first item in the list (<code>msbuild.bat</code>).</p>
<p>I have run each of the files separately with no problems.</p> | <p>Use:</p>
<pre><code>call msbuild.bat
call unit-tests.bat
call deploy.bat
</code></pre>
<p>When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.</p> | {
"question_id": 1103994,
"question_date": "2009-07-09T13:47:14.427Z",
"question_score": 820,
"tags": "batch-file|cmd",
"answer_id": 1104009,
"answer_date": "2009-07-09T13:48:37.703Z",
"answer_score": 1390
} |
Please answer the following Stack Overflow question:
Title: Can I catch multiple Java exceptions in the same catch clause?
<p>In Java, I want to do something like this:</p>
<pre><code>try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
</code></pre>
<p>...instead of:</p>
<pre><code>try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
</code></pre>
<p>Is there any way to do this?</p> | <p>This has been possible <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" rel="noreferrer">since Java 7</a>. The syntax for a multi-catch block is:</p>
<pre class="lang-java prettyprint-override"><code>try {
...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
someCode();
}
</code></pre>
<p>Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.</p>
<p>Also note that you cannot catch both <code>ExceptionA</code> and <code>ExceptionB</code> in the same block if <code>ExceptionB</code> is inherited, either directly or indirectly, from <code>ExceptionA</code>. The compiler will complain:</p>
<pre class="lang-none prettyprint-override"><code>Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
</code></pre>
<p>The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.</p> | {
"question_id": 3495926,
"question_date": "2010-08-16T18:07:03.113Z",
"question_score": 820,
"tags": "java|exception|try-catch|multi-catch",
"answer_id": 3495968,
"answer_date": "2010-08-16T18:11:12.373Z",
"answer_score": 1292
} |
Please answer the following Stack Overflow question:
Title: Interface vs Base class
<p>When should I use an interface and when should I use a base class? </p>
<p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p>
<p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p> | <p>
Let's take your example of a Dog and a Cat class, and let's illustrate using C#:</p>
<p>Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:</p>
<pre class="lang-cs prettyprint-override"><code>public abstract class Mammal
</code></pre>
<p>This base class will probably have default methods such as:</p>
<ul>
<li>Feed</li>
<li>Mate</li>
</ul>
<p>All of which are behavior that have more or less the same implementation between either species. To define this you will have:</p>
<pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal
public class Cat : Mammal
</code></pre>
<p>Now let's suppose there are other mammals, which we will usually see in a zoo:</p>
<pre class="lang-cs prettyprint-override"><code>public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
</code></pre>
<p>This will still be valid because at the core of the functionality <code>Feed()</code> and <code>Mate()</code> will still be the same.</p>
<p>However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:</p>
<pre class="lang-cs prettyprint-override"><code>public interface IPettable
{
IList<Trick> Tricks{get; set;}
void Bathe();
void Train(Trick t);
}
</code></pre>
<p>The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. </p>
<p>Your Dog and Cat definitions should now look like:</p>
<pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
</code></pre>
<p>Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.</p>
<p>Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly <em>as required</em> basis.</p> | {
"question_id": 56867,
"question_date": "2008-09-11T15:20:30.803Z",
"question_score": 820,
"tags": "oop|interface|language-agnostic|base-class|static-typing",
"answer_id": 56912,
"answer_date": "2008-09-11T15:36:14.540Z",
"answer_score": 534
} |
Please answer the following Stack Overflow question:
Title: How to force cp to overwrite without confirmation
<p>I'm trying to use the <code>cp</code> command and force an overwrite.</p>
<p>I have tried <code>cp -rf /foo/* /bar</code>, but I am still prompted to confirm each overwrite.</p> | <p>You can do <code>yes | cp -rf xxx yyy</code>, but my gutfeeling says that if you do it as root - your <code>.bashrc</code> or <code>.profile</code> has an alias of <code>cp</code> to <code>cp -i</code>, most modern systems (primarily RH-derivatives) do that to root profiles. </p>
<p>You can check existing aliases by running <code>alias</code> at the command prompt, or <code>which cp</code> to check aliases only for <code>cp</code>.</p>
<p>If you do have an alias defined, running <code>unalias cp</code> will abolish that for the current session, otherwise you can just remove it from your shell profile.</p>
<p>You can temporarily bypass an alias and use the non-aliased version of a command by prefixing it with <code>\</code>, e.g. <code>\cp whatever</code></p> | {
"question_id": 8488253,
"question_date": "2011-12-13T11:17:47.500Z",
"question_score": 819,
"tags": "linux|command-line|overwrite|cp",
"answer_id": 8488292,
"answer_date": "2011-12-13T11:20:39.130Z",
"answer_score": 1318
} |
Please answer the following Stack Overflow question:
Title: How to delete a stash created with git stash create?
<p>Git stash seems to do a lot of what I want, except that it is a little hard to script, as the if you have no changes, then <code>git stash; git stash pop</code> will do something different than if you do have changes in your repository.</p>
<p>It appears that <code>git stash create</code> is the answer to that problem, and everything works, except for one thing… I can't get rid of the created stash. Is there any way to get rid of the stash?</p>
<p>To make it 100% clear what I am doing:</p>
<p>Create the stash:</p>
<pre><code>~/tmp/a(master) $ git stash create
60629375d0eb12348f9d31933dd348ad0f038435
~/tmp/a(master) $ git st
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: b
#
~/tmp/a(master) $ git reset --hard
HEAD is now at 555d572 log message
</code></pre>
<p>Use the stash:</p>
<pre><code>~/tmp/a(master) $ git apply 60629375d0eb12348f9d31933dd348ad0f038435
fatal: can't open patch '60629375d0eb12348f9d31933dd348ad0f038435': No such file or directory
~/tmp/a(master) $ git stash apply 60629375d0eb12348f9d31933dd348ad0f038435
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: b
#
</code></pre>
<p>Delete the stash: (except that this last bit doesn't work)</p>
<pre><code>~/tmp/a(master) $ git stash drop !$
git stash drop 60629375d0eb12348f9d31933dd348ad0f038435
'60629375d0eb12348f9d31933dd348ad0f038435' is not a stash reference
</code></pre> | <p><strong>To delete a normal stash created with <code>git stash</code> , you want <code>git stash drop</code> or <code>git stash drop stash@{n}</code>. See below for more details.</strong></p>
<hr>
<p>You don't need to delete a stash created with <code>git stash create</code>. From the docs:</p>
<blockquote>
<p>Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "save" above.</p>
</blockquote>
<p>Since nothing references the stash commit, it will get garbage collected eventually.</p>
<hr>
<p>A stash created with <code>git stash</code> or <code>git stash save</code> is saved to <code>refs/stash</code>, and can be deleted with <code>git stash drop</code>. As with all Git objects, the actual stash contents aren't deleted from your computer until a <code>gc</code> prunes those objects after they expire (default is 2 weeks later).</p>
<p>Older stashes are saved in the <code>refs/stash</code> <a href="https://git-scm.com/docs/git-reflog" rel="noreferrer">reflog</a> (try <code>cat .git/logs/refs/stash</code>), and can be deleted with <code>git stash drop stash@{n}</code>, where <code>n</code> is the number shown by <code>git stash list</code>.</p> | {
"question_id": 5737002,
"question_date": "2011-04-20T21:43:46.113Z",
"question_score": 818,
"tags": "git|git-stash",
"answer_id": 5737046,
"answer_date": "2011-04-20T21:49:12.367Z",
"answer_score": 590
} |
Please answer the following Stack Overflow question:
Title: Service vs IntentService in the Android platform
<p>I am seeking an example of something that can be done with an <code>IntentService</code> that cannot be done with a <code>Service</code> (and vice-versa)?</p>
<p>I also believe that an <code>IntentService</code> runs in a different thread and a <code>Service</code> does not. So, as far as I can see, starting a service within its own thread is like starting an <code>IntentService</code>. Is that correct?</p> | <p>Tejas Lagvankar wrote a nice <a href="http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html">post</a> about this subject.
Below are some key differences between Service and IntentService.</p>
<p><strong>When to use?</strong></p>
<ul>
<li><p>The <em>Service</em> can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.</p></li>
<li><p>The <em>IntentService</em> can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).</p></li>
</ul>
<p><strong>How to trigger?</strong></p>
<ul>
<li><p>The <em>Service</em> is triggered by calling method <code>startService()</code>.</p></li>
<li><p>The <em>IntentService</em> is triggered using an Intent, it spawns a new worker thread and the method <code>onHandleIntent()</code> is called on this thread.</p></li>
</ul>
<p><strong>Triggered From</strong></p>
<ul>
<li>The <em>Service</em> and <em>IntentService</em> may be triggered from any thread, activity or other application component.</li>
</ul>
<p><strong>Runs On</strong></p>
<ul>
<li><p>The <em>Service</em> runs in background but it runs on the Main Thread of the application. </p></li>
<li><p>The <em>IntentService</em> runs on a separate worker thread.</p></li>
</ul>
<p><strong>Limitations / Drawbacks</strong></p>
<ul>
<li><p>The <em>Service</em> may block the Main Thread of the application.</p></li>
<li><p>The <em>IntentService</em> cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.</p></li>
</ul>
<p><strong>When to stop?</strong></p>
<ul>
<li><p>If you implement a <em>Service</em>, it is your responsibility to stop the service when its work is done, by calling <code>stopSelf()</code> or <code>stopService()</code>. (If you only want to provide binding, you don't need to implement this method).</p></li>
<li><p>The <em>IntentService</em> stops the service after all start requests have been handled, so you never have to call <code>stopSelf()</code>.</p></li>
</ul> | {
"question_id": 15524280,
"question_date": "2013-03-20T13:00:26.747Z",
"question_score": 818,
"tags": "android|multithreading|android-service|android-intentservice",
"answer_id": 15772151,
"answer_date": "2013-04-02T18:57:02.880Z",
"answer_score": 1420
} |
Please answer the following Stack Overflow question:
Title: How to generate a random string in Ruby
<p>I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":</p>
<pre><code>value = ""; 8.times{value << (65 + rand(25)).chr}
</code></pre>
<p>but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:</p>
<pre><code>value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
</code></pre>
<p>but it looks like trash.</p>
<p>Does anyone have a better method?</p> | <pre><code>(0...8).map { (65 + rand(26)).chr }.join
</code></pre>
<p>I spend too much time golfing.</p>
<pre><code>(0...50).map { ('a'..'z').to_a[rand(26)] }.join
</code></pre>
<p>And a last one that's even more confusing, but more flexible and wastes fewer cycles:</p>
<pre><code>o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join
</code></pre>
<p>If you want to generate some random text then use the following:</p>
<pre><code>50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ")
</code></pre>
<p>this code generates 50 random word string with words length less than 10 characters and then join with space</p> | {
"question_id": 88311,
"question_date": "2008-09-17T22:24:44.803Z",
"question_score": 817,
"tags": "ruby|random|passwords",
"answer_id": 88341,
"answer_date": "2008-09-17T22:29:05.073Z",
"answer_score": 1032
} |
Please answer the following Stack Overflow question:
Title: How to commit my current changes to a different branch in Git
<p>Sometimes it happens that I make some changes in my working directory, and I realize that these changes should be committed in a branch different to the current one. This usually happens when I want to try out new things or do some testing and I forget to create a new branch beforehand, but I don't want to commit dirty code to the master branch.</p>
<p>So, <strong>how can I make that uncommitted changes (or changes stored in the index) be committed to a different branch than the current one?</strong></p> | <p>The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for <code>git stash</code>:</p>
<pre><code>git stash
git checkout other-branch
git stash pop
</code></pre>
<p>The first <code>stash</code> hides away your changes (basically making a temporary commit), and the subsequent <code>stash pop</code> re-applies them. This lets Git use its merge capabilities.</p>
<p>If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.</p>
<p>On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:</p>
<pre><code># Unstage everything (warning: this leaves files with conflicts in your tree)
git reset
# Add the things you *do* want to commit here
git add -p # or maybe git add -i
git commit
# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop
# Add the changes meant for this branch
git add -p
git commit
# And throw away the rest
git reset --hard
</code></pre>
<p>Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:</p>
<pre><code>git add -p
git commit
git stash
git checkout other-branch
git stash pop
</code></pre>
<p>And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding <code>$(__git_ps1)</code> to your <a href="https://en.wikipedia.org/wiki/Command-line_interface#Command_prompt" rel="noreferrer">PS1</a> environment variable in your <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Aliases_and_functions" rel="noreferrer">bashrc</a> file. (See for example the <a href="https://git-scm.com/book/en/v2/Appendix-A%3A-Git-in-Other-Environments-Git-in-Bash" rel="noreferrer">Git in Bash</a> documentation.)</p> | {
"question_id": 2944469,
"question_date": "2010-05-31T15:26:26.293Z",
"question_score": 817,
"tags": "git|branch|commit",
"answer_id": 2945904,
"answer_date": "2010-05-31T20:48:11.653Z",
"answer_score": 1296
} |
Please answer the following Stack Overflow question:
Title: Distinct() with lambda?
<p>Right, so I have an enumerable and wish to get distinct values from it.</p>
<p>Using <code>System.Linq</code>, there's, of course, an extension method called <code>Distinct</code>. In the simple case, it can be used with no parameters, like:</p>
<pre><code>var distinctValues = myStringList.Distinct();
</code></pre>
<p>Well and good, but if I have an enumerable of objects for which I need to specify equality, the only available overload is:</p>
<pre><code>var distinctValues = myCustomerList.Distinct(someEqualityComparer);
</code></pre>
<p>The equality comparer argument must be an instance of <code>IEqualityComparer<T></code>. I can do this, of course, but it's somewhat verbose and, well, cludgy.</p>
<p>What I would have expected is an overload that would take a lambda, say a <code>Func<T, T, bool></code>:</p>
<pre><code>var distinctValues = myCustomerList.Distinct((c1, c2) => c1.CustomerId == c2.CustomerId);
</code></pre>
<p>Anyone know if some such extension exists, or some equivalent workaround? Or am I missing something?</p>
<p>Alternatively, is there a way of specifying an <code>IEqualityComparer</code> inline (embarrass me)?</p>
<p><strong>Update</strong></p>
<p>I found a reply by Anders Hejlsberg to a <a href="https://social.msdn.microsoft.com/Forums/en-US/6834054e-e1c1-49db-970c-370a9012c675/distinct-method-suggestion?forum=linqprojectgeneral" rel="noreferrer">post</a> in an MSDN forum on this subject. He says:</p>
<blockquote>
<p>The problem you're going to run into is that when two objects compare
equal they must have the same GetHashCode return value (or else the
hash table used internally by Distinct will not function correctly).
We use IEqualityComparer because it packages compatible
implementations of Equals and GetHashCode into a single interface.</p>
</blockquote>
<p>I suppose that makes sense.</p> | <pre><code>IEnumerable<Customer> filteredList = originalList
.GroupBy(customer => customer.CustomerId)
.Select(group => group.First());
</code></pre> | {
"question_id": 1300088,
"question_date": "2009-08-19T13:50:47.887Z",
"question_score": 817,
"tags": "c#|c#-3.0|lambda|extension-methods",
"answer_id": 4158364,
"answer_date": "2010-11-11T19:19:19.417Z",
"answer_score": 1110
} |
Please answer the following Stack Overflow question:
Title: CSS force image resize and keep aspect ratio
<p>I am working with images, and I ran into a problem with aspect ratios.</p>
<pre><code><img src="big_image.jpg" width="900" height="600" alt="" />
</code></pre>
<p>As you can see, <code>height</code> and <code>width</code> are already specified. I added a CSS rule for images:</p>
<pre><code>img {
max-width: 500px;
}
</code></pre>
<p>But for <code>big_image.jpg</code>, I receive <code>width=500</code> and <code>height=600</code>. How do I set images to be re-sized, whilst keeping their aspect ratios.</p> | <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
display: block;
max-width:230px;
max-height:95px;
width: auto;
height: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
<img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png"></code></pre>
</div>
</div>
</p>
<p>This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).</p> | {
"question_id": 12991351,
"question_date": "2012-10-20T18:20:13.890Z",
"question_score": 816,
"tags": "css|image|aspect-ratio",
"answer_id": 17183996,
"answer_date": "2013-06-19T06:08:31.683Z",
"answer_score": 1003
} |
Please answer the following Stack Overflow question:
Title: How to get a random number in Ruby
<p>How do I generate a random number between <code>0</code> and <code>n</code>?</p> | <p>Use <a href="http://www.ruby-doc.org/core-2.1.3/Kernel.html#method-i-rand" rel="noreferrer"><code>rand(range)</code></a></p>
<p>From <a href="http://www.codeodor.com/index.cfm/2007/3/25/Ruby-random-numbers/1042" rel="noreferrer">Ruby Random Numbers</a>:</p>
<blockquote>
<p>If you needed a random integer to simulate a roll of a six-sided die, you'd use: <code>1 + rand(6)</code>. A roll in craps could be simulated with <code>2 + rand(6) + rand(6)</code>.</p>
<p>Finally, if you just need a random float, just call <code>rand</code> with no arguments.</p>
</blockquote>
<hr>
<p>As <a href="https://stackoverflow.com/users/8279/marc-andre-lafortune">Marc-André Lafortune</a> mentions in <a href="https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866">his answer below (go upvote it)</a>, <a href="http://www.ruby-lang.org/en/news/2009/07/20/ruby-1-9-2-preview-1-released/" rel="noreferrer">Ruby 1.9.2 has its own <code>Random</code> class</a> (that Marc-André himself <a href="http://redmine.ruby-lang.org/issues/show/3104" rel="noreferrer">helped to debug</a>, hence the <a href="http://redmine.ruby-lang.org/versions/show/11" rel="noreferrer">1.9.2 target</a> for that feature).</p>
<p>For instance, in this <a href="http://www.eggheadcafe.com/software/aspnet/35817496/random-integer-within-a-r.aspx" rel="noreferrer">game where you need to guess 10 numbers</a>, you can initialize them with:</p>
<pre><code>10.times.map{ 20 + Random.rand(11) }
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]
</code></pre>
<p>Note: </p>
<ul>
<li><p>Using <code>Random.new.rand(20..30)</code> (using <code>Random.new</code>) generally would not be a good idea, as explained in detail (again) by <a href="https://stackoverflow.com/users/8279/marc-andre-lafortune">Marc-André Lafortune</a>, in <a href="https://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby/2773866#2773866">his answer</a> (again).</p></li>
<li><p>But if you don't use <code>Random.new</code>, then the <a href="http://www.ruby-doc.org/core/classes/Random.src/M000693.html" rel="noreferrer">class method <code>rand</code></a> only takes a <code>max</code> value, not a <code>Range</code>, as <a href="https://stackoverflow.com/users/66725/banister">banister</a> (energetically) points out in the comment (and as documented in the <a href="http://www.ruby-doc.org/core/classes/Random.html" rel="noreferrer">docs for <code>Random</code></a>). Only the <a href="http://www.ruby-doc.org/core/classes/Random.src/M000688.html" rel="noreferrer">instance method</a> can take a <code>Range</code>, as illustrated by <a href="https://stackoverflow.com/questions/5722881/generate-a-random-number-with-7-digits/5723105#5723105">generate a random number with 7 digits</a>.</p></li>
</ul>
<p>This is why the equivalent of <code>Random.new.rand(20..30)</code> would be <code>20 + Random.rand(11)</code>, since <code>Random.rand(int)</code> returns “a random integer greater than or equal to zero and <em>less than the argument</em>.” <code>20..30</code> includes 30, I need to come up with a random number between 0 and 11, excluding 11.</p> | {
"question_id": 198460,
"question_date": "2008-10-13T18:07:24.043Z",
"question_score": 816,
"tags": "ruby-on-rails|ruby|ruby-on-rails-3|ruby-on-rails-4|random",
"answer_id": 198470,
"answer_date": "2008-10-13T18:10:25.520Z",
"answer_score": 980
} |
Please answer the following Stack Overflow question:
Title: How do you remove an invalid remote branch reference from Git?
<p>In my current repo I have the following output:</p>
<pre><code>$ git branch -a
* master
remotes/origin/master
remotes/public/master
</code></pre>
<p>I want to delete <code>remotes/public/master</code> from the branch list:</p>
<pre><code>$ git branch -d remotes/public/master
error: branch 'remotes/public/master' not found.
</code></pre>
<p>Also, the output of <code>git remote</code> is strange, since it does not list <code>public</code>:</p>
<pre><code>$ git remote show
origin
</code></pre>
<p><strong>How can I delete 'remotes/public/master' from the branch list?</strong></p>
<p>Update, tried the <code>git push</code> command:</p>
<pre><code>$ git push public :master
fatal: 'public' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
</code></pre> | <p>You might be needing a cleanup:</p>
<pre><code>git gc --prune=now
</code></pre>
<p>or you might be needing a prune:</p>
<pre><code>git remote prune public
</code></pre>
<blockquote>
<p><strong>prune</strong></p>
<p>Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".</p>
<p>With --dry-run option, report what branches will be pruned, but do no actually prune them.</p>
</blockquote>
<p>However, it appears these should have been cleaned up earlier with </p>
<pre><code>git remote rm public
</code></pre>
<blockquote>
<p><strong>rm</strong></p>
<p>Remove the remote named <name>. All remote tracking branches and configuration settings for the remote
are removed.</p>
</blockquote>
<p>So it might be you hand-edited your config file and this did not occur, or you have privilege problems.</p>
<p>Maybe run that again and see what happens.</p>
<hr>
<h2>Advice Context</h2>
<p>If you take a look in the <a href="https://stackoverflow.com/posts/1072178/revisions">revision logs</a>, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository. </p>
<p>I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and <code>git gc</code> was required to fix up the left behind cruft.</p>
<p><em>Usually</em> <code>git branch -rd origin/badbranch</code> is sufficient for nuking a local tracking branch , or <code>git push origin :badbranch</code> for nuking a remote branch, and <em>usually</em> you will <em>never</em> need to call <code>git gc</code></p> | {
"question_id": 1072171,
"question_date": "2009-07-02T02:39:41.150Z",
"question_score": 816,
"tags": "git|branch|remote-branch",
"answer_id": 1072178,
"answer_date": "2009-07-02T02:42:05.450Z",
"answer_score": 807
} |
Please answer the following Stack Overflow question:
Title: How to change fontFamily of TextView in Android
<p>So I'd like to change the <code>android:fontFamily</code> in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.</p>
<pre><code><TextView
android:id="@+id/HeaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:gravity="center"
android:text="CallerBlocker"
android:textSize="40dp"
android:fontFamily="Arial"
/>
</code></pre>
<p>It seems what I did up there won't really work! BTW <code>android:fontFamily="Arial"</code> was a stupid attempt!</p> | <p>From android 4.1 / 4.2 / 5.0, the following <a href="https://material.google.com/resources/roboto-noto-fonts.html" rel="noreferrer">Roboto</a> font families are available:</p>
<pre><code>android:fontFamily="sans-serif" // roboto regular
android:fontFamily="sans-serif-light" // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black" // roboto black
android:fontFamily="sans-serif-thin" // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium" // roboto medium (android 5.0)
</code></pre>
<p><a href="https://i.stack.imgur.com/M2yxI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M2yxI.png" alt="enter image description here"></a></p>
<p>in combination with</p>
<pre><code>android:textStyle="normal|bold|italic"
</code></pre>
<p>this 16 variants are possible:</p>
<ul>
<li>Roboto regular</li>
<li>Roboto italic</li>
<li>Roboto bold</li>
<li>Roboto bold italic</li>
<li>Roboto-Light </li>
<li>Roboto-Light italic</li>
<li>Roboto-Thin </li>
<li>Roboto-Thin italic</li>
<li>Roboto-Condensed </li>
<li>Roboto-Condensed italic</li>
<li>Roboto-Condensed bold</li>
<li>Roboto-Condensed bold italic</li>
<li>Roboto-Black </li>
<li>Roboto-Black italic</li>
<li>Roboto-Medium</li>
<li>Roboto-Medium italic</li>
</ul>
<p><code>fonts.xml</code></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="font_family_light">sans-serif-light</string>
<string name="font_family_medium">sans-serif-medium</string>
<string name="font_family_regular">sans-serif</string>
<string name="font_family_condensed">sans-serif-condensed</string>
<string name="font_family_black">sans-serif-black</string>
<string name="font_family_thin">sans-serif-thin</string>
</resources>
</code></pre> | {
"question_id": 12128331,
"question_date": "2012-08-26T07:19:17.997Z",
"question_score": 815,
"tags": "android|android-layout|textview|typeface",
"answer_id": 13329907,
"answer_date": "2012-11-11T09:22:26.737Z",
"answer_score": 1736
} |
Please answer the following Stack Overflow question:
Title: How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error
<p>I receive following error when I save the object using Hibernate </p>
<pre><code>object references an unsaved transient instance - save the transient instance before flushing
</code></pre> | <p>You should include <code>cascade="all"</code> (if using xml) or <code>cascade=CascadeType.ALL</code> (if using annotations) on your collection mapping.</p>
<p>This happens because you have a collection in your entity, and that collection has one or more items which are not present in the database. By specifying the above options you tell hibernate to save them to the database when saving their parent.</p> | {
"question_id": 2302802,
"question_date": "2010-02-20T16:17:45.807Z",
"question_score": 815,
"tags": "java|hibernate|jpa|orm|entity",
"answer_id": 2302814,
"answer_date": "2010-02-20T16:25:02.237Z",
"answer_score": 1014
} |
Please answer the following Stack Overflow question:
Title: How to restart Jenkins manually?
<p>I've just started working with Jenkins and have run into a problem. After installing several plugins it said it needs to be restarted and went into a "shutting down" mode, but never restarts.</p>
<p>How do I do a manual restart?</p> | <p>To restart Jenkins manually, you can use either of the following commands (by entering their URL in a browser):</p>
<p><code>(jenkins_url)/safeRestart</code> - Allows all running jobs to complete. New jobs will remain in the queue to run after the restart is complete. </p>
<p><code>(jenkins_url)/restart</code> - Forces a restart without waiting for builds to complete.</p> | {
"question_id": 8072700,
"question_date": "2011-11-09T22:32:22.550Z",
"question_score": 815,
"tags": "jenkins",
"answer_id": 8077830,
"answer_date": "2011-11-10T10:08:36.747Z",
"answer_score": 2232
} |
Please answer the following Stack Overflow question:
Title: How to define a circle shape in an Android XML drawable file?
<p>I have some problems finding the documentation of the definitions of shapes in XML for Android. I would like to define a simple circle filled with a solid color in an XML File to include it into my layout files. </p>
<p>Sadly the Documentation on android.com does not cover the XML attributes of the Shape classes. I think I should use an <a href="https://developer.android.com/reference/android/graphics/drawable/shapes/ArcShape" rel="noreferrer">ArcShape</a> to draw a circle but there is no explanation on how to set the size, the color, or the angle needed to make a circle out of an Arc.</p> | <p>This is a simple circle as a drawable in Android.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#666666"/>
<size
android:width="120dp"
android:height="120dp"/>
</shape>
</code></pre> | {
"question_id": 3185103,
"question_date": "2010-07-06T09:40:32.423Z",
"question_score": 815,
"tags": "android|android-drawable|shapes",
"answer_id": 12121937,
"answer_date": "2012-08-25T12:24:53.533Z",
"answer_score": 1758
} |
Please answer the following Stack Overflow question:
Title: How to read embedded resource text file
<p>How do I read an embedded resource (text file) using <code>StreamReader</code> and return it as a string? My current script uses a Windows form and textbox that allows the user to find and replace text in a text file that is not embedded. </p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
StringCollection strValuesToSearch = new StringCollection();
strValuesToSearch.Add("Apple");
string stringToReplace;
stringToReplace = textBox1.Text;
StreamReader FileReader = new StreamReader(@"C:\MyFile.txt");
string FileContents;
FileContents = FileReader.ReadToEnd();
FileReader.Close();
foreach (string s in strValuesToSearch)
{
if (FileContents.Contains(s))
FileContents = FileContents.Replace(s, stringToReplace);
}
StreamWriter FileWriter = new StreamWriter(@"MyFile.txt");
FileWriter.Write(FileContents);
FileWriter.Close();
}
</code></pre> | <p>You can use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getmanifestresourcestream#System_Reflection_Assembly_GetManifestResourceStream_System_String_" rel="noreferrer"><strong><code>Assembly.GetManifestResourceStream</code></strong> Method</a>:</p>
<ol>
<li><p>Add the following usings</p>
<pre><code>using System.IO;
using System.Reflection;
</code></pre></li>
<li><p>Set property of relevant file:<br>
Parameter <code>Build Action</code> with value <code>Embedded Resource</code></p></li>
<li><p>Use the following code</p>
<pre><code>var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
</code></pre>
<p><code>resourceName</code> is the name of one of the resources embedded in <code>assembly</code>.
For example, if you embed a text file named <code>"MyFile.txt"</code> that is placed in the root of a project with default namespace <code>"MyCompany.MyProduct"</code>, then <code>resourceName</code> is <code>"MyCompany.MyProduct.MyFile.txt"</code>.
You can get a list of all resources in an assembly using the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getmanifestresourcenames" rel="noreferrer"><strong><code>Assembly.GetManifestResourceNames</code></strong> Method</a>.</p></li>
</ol>
<hr>
<p>A no brainer astute to get the <code>resourceName</code> from the file name only (by pass the namespace stuff):</p>
<pre><code>string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("YourFileName.txt"));
</code></pre>
<hr>
<p>A complete example:</p>
<pre class="lang-cs prettyprint-override"><code>public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
</code></pre> | {
"question_id": 3314140,
"question_date": "2010-07-22T22:51:15.427Z",
"question_score": 815,
"tags": ".net|embedded-resource|streamreader",
"answer_id": 3314213,
"answer_date": "2010-07-22T23:03:23.213Z",
"answer_score": 1434
} |
Please answer the following Stack Overflow question:
Title: How to break out of jQuery each loop?
<p>How do I break out of a jQuery <a href="https://api.jquery.com/each/" rel="noreferrer"><code>each</code></a> loop?</p>
<p>I have tried:</p>
<pre><code> return false;
</code></pre>
<p>in the loop but this did not work. Any ideas?</p>
<hr />
<h2>Update 9/5/2020</h2>
<p>I put the <code>return false;</code> in the wrong place. When I put it inside the loop everything worked.</p> | <p>To <code>break</code> a <a href="https://api.jquery.com/jQuery.each" rel="noreferrer"><code>$.each</code></a> or <a href="http://docs.jquery.com/Core/each" rel="noreferrer"><code>$(selector).each</code></a> loop, you have to return <code>false</code> in the loop callback.</p>
<p>Returning <code>true</code> skips to the next iteration, equivalent to a <code>continue</code> in a normal loop.</p>
<pre><code>$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
</code></pre> | {
"question_id": 1784780,
"question_date": "2009-11-23T17:44:37.260Z",
"question_score": 815,
"tags": "jquery|loops|break",
"answer_id": 1784792,
"answer_date": "2009-11-23T17:46:33.683Z",
"answer_score": 1432
} |
Please answer the following Stack Overflow question:
Title: What is "export default" in JavaScript?
<p>File: <a href="https://github.com/wycats/handlebars.js/blob/583141de7cb61eb70eaa6b33c25f475f3048071b/lib/handlebars/safe-string.js" rel="noreferrer">SafeString.js</a></p>
<pre><code>// Build out our basic SafeString type
function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = function() {
return "" + this.string;
};
export default SafeString;
</code></pre>
<p>I have never seen <code>export default</code> before. Are there any equivalent stuff for <code>export default</code> that can be easier to understand?</p> | <p>It's part of the ES6 module system, <a href="https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export#Using_the_default_export" rel="noreferrer">described here</a>. There is a helpful example in that documentation, also:</p>
<blockquote>
<p>If a module defines a default export:</p>
<pre><code>// foo.js
export default function() { console.log("hello!") }
</code></pre>
<p>then you can import that default export by omitting the curly braces:</p>
<pre><code>import foo from "foo";
foo(); // hello!
</code></pre>
</blockquote>
<hr />
<p><strong>Update:</strong> As of June 2015, the module system is defined in <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-modules" rel="noreferrer">§15.2</a> and the <code>export</code> syntax in particular is defined in <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-exports" rel="noreferrer">§15.2.3</a> of the ECMAScript 2015 specification.</p> | {
"question_id": 21117160,
"question_date": "2014-01-14T15:21:21.463Z",
"question_score": 815,
"tags": "javascript|node.js|ecmascript-6",
"answer_id": 21117231,
"answer_date": "2014-01-14T15:25:00.297Z",
"answer_score": 630
} |
Please answer the following Stack Overflow question:
Title: IEnumerable vs List - What to Use? How do they work?
<p>I have some doubts over how Enumerators work, and LINQ. Consider these two simple selects:</p>
<pre><code>List<Animal> sel = (from animal in Animals
join race in Species
on animal.SpeciesKey equals race.SpeciesKey
select animal).Distinct().ToList();
</code></pre>
<p>or</p>
<pre><code>IEnumerable<Animal> sel = (from animal in Animals
join race in Species
on animal.SpeciesKey equals race.SpeciesKey
select animal).Distinct();
</code></pre>
<p>I changed the names of my original objects so that this looks like a more generic example. The query itself is not that important. What I want to ask is this:</p>
<pre><code>foreach (Animal animal in sel) { /*do stuff*/ }
</code></pre>
<ol>
<li><p>I noticed that if I use <code>IEnumerable</code>, when I debug and inspect "sel", which in that case is the IEnumerable, it has some interesting members: "inner", "outer", "innerKeySelector" and "outerKeySelector", these last 2 appear to be delegates. The "inner" member does not have "Animal" instances in it, but rather "Species" instances, which was very strange for me. The "outer" member does contain "Animal" instances. I presume that the two delegates determine which goes in and what goes out of it?</p></li>
<li><p>I noticed that if I use "Distinct", the "inner" contains 6 items (this is incorrect as only 2 are Distinct), but the "outer" does contain the correct values. Again, probably the delegated methods determine this but this is a bit more than I know about IEnumerable.</p></li>
<li><p>Most importantly, which of the two options is the best performance-wise?</p></li>
</ol>
<p>The evil List conversion via <code>.ToList()</code>?</p>
<p>Or maybe using the enumerator directly?</p>
<p>If you can, please also explain a bit or throw some links that explain this use of IEnumerable.</p> | <p><code>IEnumerable</code> describes behavior, while List is an implementation of that behavior. When you use <code>IEnumerable</code>, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.</p>
<p>Whenever I'm "stacking" LINQ expressions, I use <code>IEnumerable</code>, because by only specifying the behavior I give LINQ a chance to defer evaluation and possibly optimize the program. Remember how LINQ doesn't generate the SQL to query the database until you enumerate it? Consider this:</p>
<pre><code>public IEnumerable<Animals> AllSpotted()
{
return from a in Zoo.Animals
where a.coat.HasSpots == true
select a;
}
public IEnumerable<Animals> Feline(IEnumerable<Animals> sample)
{
return from a in sample
where a.race.Family == "Felidae"
select a;
}
public IEnumerable<Animals> Canine(IEnumerable<Animals> sample)
{
return from a in sample
where a.race.Family == "Canidae"
select a;
}
</code></pre>
<p>Now you have a method that selects an initial sample ("AllSpotted"), plus some filters. So now you can do this:</p>
<pre><code>var Leopards = Feline(AllSpotted());
var Hyenas = Canine(AllSpotted());
</code></pre>
<p>So is it faster to use List over <code>IEnumerable</code>? Only if you want to prevent a query from being executed more than once. But is it better overall? Well in the above, Leopards and Hyenas get converted into <em>single SQL queries each</em>, and the database only returns the rows that are relevant. But if we had returned a List from <code>AllSpotted()</code>, then it may run slower because the database could return far more data than is actually needed, and we waste cycles doing the filtering in the client.</p>
<p>In a program, it may be better to defer converting your query to a list until the very end, so if I'm going to enumerate through Leopards and Hyenas more than once, I'd do this:</p>
<pre><code>List<Animals> Leopards = Feline(AllSpotted()).ToList();
List<Animals> Hyenas = Canine(AllSpotted()).ToList();
</code></pre> | {
"question_id": 3628425,
"question_date": "2010-09-02T15:05:05.213Z",
"question_score": 815,
"tags": "c#|linq|list|ienumerable",
"answer_id": 3628705,
"answer_date": "2010-09-02T15:36:42.273Z",
"answer_score": 870
} |
Please answer the following Stack Overflow question:
Title: git add only modified changes and ignore untracked files
<p>I ran "git status" and listed below are some files that were modified/or under the heading "changes not staged for commit".
It also listed some untracked files that I want to ignore (I have a ".gitignore" file in these directories).</p>
<p>I want to put the modified files in staging so I can commit them. When I ran "git add .", it added the modified files AND the files I want to ignore to staging.</p>
<p>How do I add only the modified files and ignore the untracked files if presented with the git status below.</p>
<p>Also, are my ".gitignore" files working properly?</p>
<pre><code>$ git status
# On branch addLocation
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: someProject/path/domain/viewer/LocationDO.java
# modified: someProject/path/service/ld/LdService.java
# modified: someProject/path/service/ld/LdServiceImpl.java
# modified: someProject/path/web/jsf/viewer/LocationFormAction.java
# modified: someProject/war/WEB-INF/classes/message/viewer/viewer.properties
# modified: someProject/war/page/viewer/searchForm.xhtml
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# .metadata/
# someProject/build/
no changes added to commit (use "git add" and/or "git commit -a")
</code></pre> | <p>Ideally your <code>.gitignore</code> should prevent the untracked (and ignored) files from being shown in status, added using <code>git add</code> etc. So I would ask you to correct your <code>.gitignore</code></p>
<p>You can do <code>git add -u</code> so that it will stage the modified and deleted files.</p>
<p>You can also do <code>git commit -a</code> to commit only the modified and deleted files.</p>
<p>Note that if you have Git of version before 2.0 and used <code>git add .</code>, then you would need to use <code>git add -u .</code> (See "<a href="https://stackoverflow.com/a/16162511/6309">Difference of “<code>git add -A</code>” and “<code>git add .</code>”</a>").</p> | {
"question_id": 7124726,
"question_date": "2011-08-19T16:40:59.157Z",
"question_score": 815,
"tags": "git|commit|gitignore|staging",
"answer_id": 7124760,
"answer_date": "2011-08-19T16:44:13.797Z",
"answer_score": 1115
} |
Please answer the following Stack Overflow question:
Title: Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server
<p>This should be dead simple, but I <em>cannot</em> get it to work for the life of me.<br />
I'm just trying to connect remotely to my MySQL server.</p>
<ul>
<li><p>Connecting as:</p>
<pre class="lang-bash prettyprint-override"><code>mysql -u root -h localhost -p
</code></pre>
</li>
<li><p>works fine, but trying:</p>
<pre class="lang-bash prettyprint-override"><code>mysql -u root -h 'any ip address here' -p
</code></pre>
</li>
<li><p>fails with the error:</p>
<blockquote>
<p>ERROR 1130 (00000): Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server</p>
</blockquote>
</li>
</ul>
<p>In the <code>mysql.user</code> table, there is exactly the same entry for user 'root' with host 'localhost' as another with host '%'.</p>
<p>I'm at my wits' end and have no idea how to proceed.
Any ideas are welcome.</p> | <p>Possibly a security precaution. You could try adding a new administrator account:</p>
<pre><code>mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
-> WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
-> WITH GRANT OPTION;
</code></pre>
<p>Although as Pascal and others have noted it's not a great idea to have a user with this kind of access open to any IP. If you need an administrative user, use root, and leave it on localhost. For any other action specify exactly the privileges you need and limit the accessibility of the user as Pascal has suggest below.</p>
<p>Edit:</p>
<p>From the MySQL FAQ:</p>
<blockquote>
<p>If you cannot figure out why you get
Access denied, remove from the user
table all entries that have Host
values containing wildcards (entries
that contain '%' or '_' characters). A
very common error is to insert a new
entry with Host='%' and
User='some_user', thinking that this
allows you to specify localhost to
connect from the same machine. The
reason that this does not work is that
the default privileges include an
entry with Host='localhost' and
User=''. Because that entry has a Host
value 'localhost' that is more
specific than '%', it is used in
preference to the new entry when
connecting from localhost! The correct
procedure is to insert a second entry
with Host='localhost' and
User='some_user', or to delete the
entry with Host='localhost' and
User=''. After deleting the entry,
remember to issue a FLUSH PRIVILEGES
statement to reload the grant tables.
See also Section 5.4.4, “Access
Control, Stage 1: Connection
Verification”.</p>
</blockquote> | {
"question_id": 1559955,
"question_date": "2009-10-13T12:40:47.370Z",
"question_score": 814,
"tags": "mysql|mysql-error-1130",
"answer_id": 1559992,
"answer_date": "2009-10-13T12:47:06.640Z",
"answer_score": 1018
} |
Please answer the following Stack Overflow question:
Title: How to convert byte array to string
<p>I created a byte array with two strings. How do I convert a byte array to string?</p>
<pre><code>var binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write("value1");
binWriter.Write("value2");
binWriter.Seek(0, SeekOrigin.Begin);
byte[] result = reader.ReadBytes((int)binWriter.BaseStream.Length);
</code></pre>
<p>I want to convert <code>result</code> to a string. I could do it using <code>BinaryReader</code>, but I cannot use <code>BinaryReader</code> (it is not supported).</p> | <p>Depending on the encoding you wish to use:</p>
<pre><code>var str = System.Text.Encoding.Default.GetString(result);
</code></pre> | {
"question_id": 11654562,
"question_date": "2012-07-25T16:39:42.900Z",
"question_score": 814,
"tags": "c#|arrays|binaryreader",
"answer_id": 11654597,
"answer_date": "2012-07-25T16:41:52.210Z",
"answer_score": 1317
} |
Please answer the following Stack Overflow question:
Title: Equivalent of shell 'cd' command to change the working directory?
<p><code>cd</code> is the shell command to change the working directory.</p>
<p>How do I change the current working directory in Python?</p> | <p>You can change the working directory with:</p>
<pre class="lang-py prettyprint-override"><code>import os
os.chdir(path)
</code></pre>
<p>There are two best practices to follow when using this method:</p>
<ol>
<li>Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.</li>
<li>Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in <a href="https://stackoverflow.com/questions/431684/how-do-i-cd-in-python/13197763#13197763">his answer</a>.</li>
</ol>
<p>Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use <code>os.chdir()</code> to change the CWD of the calling process.</p> | {
"question_id": 431684,
"question_date": "2009-01-10T20:28:16.723Z",
"question_score": 814,
"tags": "python|cd",
"answer_id": 431715,
"answer_date": "2009-01-10T20:41:50.877Z",
"answer_score": 900
} |
Please answer the following Stack Overflow question:
Title: How do I print the full NumPy array, without truncation?
<p>When I print a numpy array, I get a truncated representation, but I want the full array.</p>
<pre><code>>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
[ 40, 41, 42, ..., 77, 78, 79],
[ 80, 81, 82, ..., 117, 118, 119],
...,
[9880, 9881, 9882, ..., 9917, 9918, 9919],
[9920, 9921, 9922, ..., 9957, 9958, 9959],
[9960, 9961, 9962, ..., 9997, 9998, 9999]])
</code></pre> | <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html" rel="noreferrer"><code>numpy.set_printoptions</code></a>:</p>
<pre><code>import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
</code></pre> | {
"question_id": 1987694,
"question_date": "2010-01-01T01:51:46.140Z",
"question_score": 814,
"tags": "python|arrays|numpy|output-formatting",
"answer_id": 1988024,
"answer_date": "2010-01-01T06:26:05.553Z",
"answer_score": 883
} |
Please answer the following Stack Overflow question:
Title: Pass a JavaScript function as parameter
<p>How do I pass a function as a parameter without the function executing in the "parent" function or using <code>eval()</code>? (Since I've read that it's insecure.)</p>
<p>I have this:</p>
<pre><code>addContact(entityId, refreshContactList());
</code></pre>
<p>It works, but the problem is that <code>refreshContactList</code> fires when the function is called, rather than when it's used in the function.</p>
<p>I could get around it using <code>eval()</code>, but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?</p> | <p>You just need to remove the parenthesis:</p>
<pre class="lang-js prettyprint-override"><code>addContact(entityId, refreshContactList);
</code></pre>
<p>This then passes the function without executing it first.</p>
<p>Here is an example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);</code></pre>
</div>
</div>
</p> | {
"question_id": 13286233,
"question_date": "2012-11-08T09:34:04.623Z",
"question_score": 814,
"tags": "javascript|function|parameters",
"answer_id": 13286241,
"answer_date": "2012-11-08T09:34:56.050Z",
"answer_score": 1126
} |
Please answer the following Stack Overflow question:
Title: Babel 6 regeneratorRuntime is not defined
<p>I'm trying to use async/await from scratch on Babel 6, but I'm getting <code>regeneratorRuntime</code> is not defined.</p>
<p>.babelrc file</p>
<pre><code>{
"presets": [ "es2015", "stage-0" ]
}
</code></pre>
<p>package.json file</p>
<pre><code>"devDependencies": {
"babel-core": "^6.0.20",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
</code></pre>
<p>.js file</p>
<pre><code>"use strict";
async function foo() {
await bar();
}
function bar() { }
exports.default = foo;
</code></pre>
<p>Using it normally without the async/await works just fine. Any ideas what I'm doing wrong?</p> | <p><code>babel-polyfill</code> (<a href="https://babeljs.io/docs/en/babel-polyfill" rel="noreferrer">deprecated</a> as of Babel 7.4) is required. You must also install it in order to get async/await working.</p>
<pre><code>npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
</code></pre>
<p>package.json</p>
<pre><code>"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
</code></pre>
<p>.babelrc</p>
<pre><code>{
"presets": [ "es2015", "stage-0" ]
}
</code></pre>
<p>.js with async/await (sample code)</p>
<pre><code>"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
</code></pre>
<p>In the startup file</p>
<pre><code>require("babel-core/register");
require("babel-polyfill");
</code></pre>
<p>If you are using <strong>webpack</strong> you need to put it as the first value of your <code>entry</code> array in your webpack configuration file (usually <code>webpack.config.js</code>), as per @Cemen comment:</p>
<pre><code>module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
</code></pre>
<p>If you want to run tests with babel then use:</p>
<pre><code>mocha --compilers js:babel-core/register --require babel-polyfill
</code></pre> | {
"question_id": 33527653,
"question_date": "2015-11-04T16:58:28.720Z",
"question_score": 814,
"tags": "javascript|node.js|babeljs",
"answer_id": 33527883,
"answer_date": "2015-11-04T17:10:05.657Z",
"answer_score": 750
} |
Please answer the following Stack Overflow question:
Title: Is there a way to get version from package.json in nodejs code?
<p>Is there a way to get the version set in <code>package.json</code> in a nodejs app? I would want something like this</p>
<pre><code>var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION
</code></pre> | <p>I found that the following code fragment worked best for me. Since it uses <code>require</code> to load the <code>package.json</code>, it works regardless of the current working directory.</p>
<pre class="lang-js prettyprint-override"><code>var pjson = require('./package.json');
console.log(pjson.version);
</code></pre>
<p><strong>A warning, courtesy of <a href="https://stackoverflow.com/users/616987/pathogen">@Pathogen</a>:</strong></p>
<blockquote>
<p>Doing this with Browserify has security implications.<br />
Be careful not to expose your <code>package.json</code> to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.<br />
If you're building server and client in the same project, you expose your server-side version numbers too.
Such specific data can be used by an attacker to better fit the attack on your server.</p>
</blockquote> | {
"question_id": 9153571,
"question_date": "2012-02-05T22:15:37.217Z",
"question_score": 814,
"tags": "node.js|npm|version|versioning|package.json",
"answer_id": 10855054,
"answer_date": "2012-06-01T17:51:37.653Z",
"answer_score": 1212
} |
Please answer the following Stack Overflow question:
Title: How to determine when Fragment becomes visible in ViewPager
<p>Problem: Fragment <code>onResume()</code> in <code>ViewPager</code> is fired before the fragment becomes actually visible.</p>
<p>For example, I have 2 fragments with <code>ViewPager</code> and <code>FragmentPagerAdapter</code>. The second fragment is only available for authorized users and I need to ask the user to log in when the fragment becomes visible (using an alert dialog).</p>
<p>BUT the <code>ViewPager</code> creates the second fragment when the first is visible in order to cache the second fragment and makes it visible when the user starts swiping.</p>
<p>So the <code>onResume()</code> event is fired in the second fragment long before it becomes visible. That's why I'm trying to find an event which fires when the second fragment becomes visible to show a dialog at the appropriate moment.</p>
<p>How can this be done?</p> | <blockquote>
<p>How to determine when Fragment becomes visible in ViewPager</p>
</blockquote>
<p>You can do the following by overriding <code>setUserVisibleHint</code> in your <code>Fragment</code>:</p>
<pre><code>public class MyFragment extends Fragment {
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
}
else {
}
}
}
</code></pre> | {
"question_id": 10024739,
"question_date": "2012-04-05T07:58:15.290Z",
"question_score": 814,
"tags": "android|android-fragments|android-viewpager",
"answer_id": 11075663,
"answer_date": "2012-06-17T23:42:09.847Z",
"answer_score": 607
} |
Please answer the following Stack Overflow question:
Title: What does the "+" (plus sign) CSS selector mean?
<p>For example:</p>
<pre><code>p + p {
/* Some declarations */
}
</code></pre>
<p>I don't know what the <code>+</code> means. What's the difference between this and just defining a style for <code>p</code> without <code>+ p</code>?</p> | <p>See <a href="http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors" rel="noreferrer">adjacent selectors</a> on W3.org.</p>
<p>In this case, the selector means that the style applies only to paragraphs directly following another paragraph.</p>
<p>A plain <code>p</code> selector would apply the style to every paragraph in the page.</p>
<hr>
<p>This will only work on IE7 or above. In IE6, the style will not be applied to any elements. This also goes for the <code>></code> combinator, by the way.</p>
<p>See also Microsoft's overview for <a href="http://msdn.microsoft.com/en-us/library/cc351024%28VS.85%29.aspx#elementselectors" rel="noreferrer">CSS compatibility in Internet Explorer</a>.</p> | {
"question_id": 1139763,
"question_date": "2009-07-16T19:26:50.430Z",
"question_score": 814,
"tags": "css|css-selectors",
"answer_id": 1139776,
"answer_date": "2009-07-16T19:29:01.177Z",
"answer_score": 806
} |
Please answer the following Stack Overflow question:
Title: LINQ Aggregate algorithm explained
<p>This might sound lame, but I have not been able to find a really good explanation of <code>Aggregate</code>.</p>
<p>Good means short, descriptive, comprehensive with a small and clear example.</p> | <p>The easiest-to-understand definition of <code>Aggregate</code> is that it performs an operation on each element of the list taking into account the operations that have gone before. That is to say it performs the action on the first and second element and carries the result forward. Then it operates on the previous result and the third element and carries forward. etc.</p>
<p><strong>Example 1. Summing numbers</strong></p>
<pre><code>var nums = new[]{1,2,3,4};
var sum = nums.Aggregate( (a,b) => a + b);
Console.WriteLine(sum); // output: 10 (1+2+3+4)
</code></pre>
<p>This adds <code>1</code> and <code>2</code> to make <code>3</code>. Then adds <code>3</code> (result of previous) and <code>3</code> (next element in sequence) to make <code>6</code>. Then adds <code>6</code> and <code>4</code> to make <code>10</code>.</p>
<p><strong>Example 2. create a csv from an array of strings</strong></p>
<pre><code>var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate( (a,b) => a + ',' + b);
Console.WriteLine(csv); // Output a,b,c,d
</code></pre>
<p>This works in much the same way. Concatenate <code>a</code> a comma and <code>b</code> to make <code>a,b</code>. Then concatenates <code>a,b</code> with a comma and <code>c</code> to make <code>a,b,c</code>. and so on.</p>
<p><strong>Example 3. Multiplying numbers using a seed</strong></p>
<p>For completeness, there is an <a href="http://msdn.microsoft.com/en-us/library/bb549218.aspx" rel="noreferrer">overload</a> of <code>Aggregate</code> which takes a seed value. </p>
<pre><code>var multipliers = new []{10,20,30,40};
var multiplied = multipliers.Aggregate(5, (a,b) => a * b);
Console.WriteLine(multiplied); //Output 1200000 ((((5*10)*20)*30)*40)
</code></pre>
<p>Much like the above examples, this starts with a value of <code>5</code> and multiplies it by the first element of the sequence <code>10</code> giving a result of <code>50</code>. This result is carried forward and multiplied by the next number in the sequence <code>20</code> to give a result of <code>1000</code>. This continues through the remaining 2 element of the sequence.</p>
<p>Live examples: <a href="http://rextester.com/ZXZ64749" rel="noreferrer">http://rextester.com/ZXZ64749</a><br>
Docs: <a href="http://msdn.microsoft.com/en-us/library/bb548651.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb548651.aspx</a></p>
<hr>
<p><strong>Addendum</strong></p>
<p>Example 2, above, uses string concatenation to create a list of values separated by a comma. This is a simplistic way to explain the use of <code>Aggregate</code> which was the intention of this answer. However, if using this technique to actually create a large amount of comma separated data, it would be more appropriate to use a <code>StringBuilder</code>, and this is entirely compatible with <code>Aggregate</code> using the seeded overload to initiate the <code>StringBuilder</code>.</p>
<pre><code>var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate(new StringBuilder(), (a,b) => {
if(a.Length>0)
a.Append(",");
a.Append(b);
return a;
});
Console.WriteLine(csv);
</code></pre>
<p>Updated example: <a href="http://rextester.com/YZCVXV6464" rel="noreferrer">http://rextester.com/YZCVXV6464</a></p> | {
"question_id": 7105505,
"question_date": "2011-08-18T09:51:21.597Z",
"question_score": 814,
"tags": "c#|.net|linq|aggregate",
"answer_id": 7105616,
"answer_date": "2011-08-18T09:59:30.430Z",
"answer_score": 1135
} |
Please answer the following Stack Overflow question:
Title: How to initialize an array's length in JavaScript?
<p>Most of the tutorials that I've read on arrays in JavaScript (including <a href="http://www.w3schools.com/js/js_obj_array.asp" rel="noreferrer">w3schools</a> and <a href="http://www.devguru.com/technologies/ecmascript/quickref/array.html" rel="noreferrer">devguru</a>) suggest that you can initialize an array with a certain length by passing an integer to the Array constructor using the <code>var test = new Array(4);</code> syntax.</p>
<p>After using this syntax liberally in my js files, I ran one of the files through <a href="http://www.jslint.com/" rel="noreferrer">jsLint</a>, and it freaked out:</p>
<blockquote>
<p>Error: Problem at line 1 character 22: Expected ')' and instead saw '4'.<br>
var test = new Array(4);<br>
Problem at line 1 character 23: Expected ';' and instead saw ')'.<br>
var test = new Array(4);<br>
Problem at line 1 character 23: Expected an identifier and instead saw ')'.</p>
</blockquote>
<p>After reading through <a href="http://www.jslint.com/lint.html" rel="noreferrer">jsLint's explanation of its behavior</a>, it looks like jsLint doesn't really like the <code>new Array()</code> syntax, and instead prefers <code>[]</code> when declaring arrays.</p>
<p>So I have a couple questions:</p>
<p>First, why? Am I running any risk by using the <code>new Array()</code> syntax instead? Are there browser incompatibilities that I should be aware of?</p>
<p>And second, if I switch to the square bracket syntax, is there any way to declare an array and set its length all on one line, or do I have to do something like this:</p>
<pre><code>var test = [];
test.length = 4;
</code></pre> | <ol>
<li><p>Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the <code>length</code> to find out whether an array is empty or not will report that the array is not empty.<br>
<a href="http://jsperf.com/big-array-initialize/2" rel="noreferrer">Some</a> <a href="http://jsperf.com/best-init-array/3" rel="noreferrer">tests</a> show that setting the initial length of large arrays <em>can</em> be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.</p></li>
<li><p>jsLint does not like <code>new Array()</code> because the constructer is ambiguous.</p>
<pre><code>new Array(4);
</code></pre>
<p>creates an empty array <strong>of length</strong> 4. But</p>
<pre><code>new Array('4');
</code></pre>
<p>creates an array <strong>containing the value</strong> <code>'4'</code>.</p></li>
</ol>
<p>Regarding your comment: In JS you don't need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.</p>
<pre><code>var data = [];
var length = 5; // user defined length
for(var i = 0; i < length; i++) {
data.push(createSomeObject());
}
</code></pre> | {
"question_id": 4852017,
"question_date": "2011-01-31T14:29:07.513Z",
"question_score": 813,
"tags": "javascript|arrays|jslint",
"answer_id": 4852052,
"answer_date": "2011-01-31T14:32:30.947Z",
"answer_score": 485
} |
Please answer the following Stack Overflow question:
Title: How can I do a FULL OUTER JOIN in MySQL?
<p>I want to do a <em><a href="https://en.wikipedia.org/wiki/Join_(SQL)#Full_outer_join" rel="noreferrer">full outer join</a></em> in MySQL. Is this possible? Is a <em>full outer join</em> supported by MySQL?</p> | <p>You don't have <em>full joins</em> in MySQL, but you can sure <a href="http://dev.mysql.com/doc/refman/5.0/en/outer-join-simplification.html" rel="nofollow noreferrer">emulate them</a>.</p>
<p>For a code <em>sample</em> transcribed from <a href="https://stackoverflow.com/questions/2384298/mysql-full-outer-join-syntax-error">this Stack Overflow question</a> you have:</p>
<p>With two tables t1, t2:</p>
<pre><code>SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
</code></pre>
<hr />
<p>The query above works for special cases where a <em>full outer join</em> operation would not produce any duplicate rows. The query above depends on the <code>UNION</code> set operator to remove duplicate rows introduced by the query pattern. We can avoid introducing duplicate rows by using an <em>anti-join</em> pattern for the second query, and then use a UNION ALL set operator to combine the two sets. In the more general case, where a full outer join would return duplicate rows, we can do this:</p>
<pre><code>SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
WHERE t1.id IS NULL
</code></pre> | {
"question_id": 4796872,
"question_date": "2011-01-25T17:34:18.777Z",
"question_score": 813,
"tags": "sql|mysql|join|outer-join|full-outer-join",
"answer_id": 4796911,
"answer_date": "2011-01-25T17:38:14.673Z",
"answer_score": 833
} |
Please answer the following Stack Overflow question:
Title: Argument list too long error for rm, cp, mv commands
<p>I have several hundred PDFs under a directory in UNIX. The names of the PDFs are really long (approx. 60 chars).</p>
<p>When I try to delete all PDFs together using the following command:</p>
<pre><code>rm -f *.pdf
</code></pre>
<p>I get the following error:</p>
<pre><code>/bin/rm: cannot execute [Argument list too long]
</code></pre>
<p>What is the solution to this error?
Does this error occur for <code>mv</code> and <code>cp</code> commands as well? If yes, how to solve for these commands?</p> | <p>The reason this occurs is because bash actually expands the asterisk to every matching file, producing a very long command line.</p>
<p>Try this:</p>
<pre><code>find . -name "*.pdf" -print0 | xargs -0 rm
</code></pre>
<p><strong>Warning:</strong> this is a recursive search and will find (and delete) files in subdirectories as well. Tack on <code>-f</code> to the rm command only if you are sure you don't want confirmation.</p>
<p>You can do the following to make the command non-recursive:</p>
<pre><code>find . -maxdepth 1 -name "*.pdf" -print0 | xargs -0 rm
</code></pre>
<p>Another option is to use find's <code>-delete</code> flag:</p>
<pre><code>find . -name "*.pdf" -delete
</code></pre> | {
"question_id": 11289551,
"question_date": "2012-07-02T07:43:34.240Z",
"question_score": 813,
"tags": "linux|unix|command-line-arguments",
"answer_id": 11289567,
"answer_date": "2012-07-02T07:44:39.153Z",
"answer_score": 1134
} |
Please answer the following Stack Overflow question:
Title: Split a string by another string in C#
<p>I've been using the <code>Split()</code> method to split strings, but this only appears to work if you are splitting a string by a character. Is there a way to split a <code>string</code>, with another string being the split by parameter?</p>
<p>I've tried converting the splitter into a character array, with no luck.</p>
<p>In other words, I'd like to split the <code>string</code>:</p>
<blockquote>
<p>THExxQUICKxxBROWNxxFOX</p>
</blockquote>
<p>by <code>xx</code>, and return an array with values:</p>
<blockquote>
<p>THE, QUICK, BROWN, FOX</p>
</blockquote> | <p>In order to split by a string you'll have to use the <a href="http://msdn.microsoft.com/en-us/library/tabh47cf.aspx" rel="noreferrer">string array overload</a>.</p>
<pre><code>string data = "THExxQUICKxxBROWNxxFOX";
return data.Split(new string[] { "xx" }, StringSplitOptions.None);
</code></pre> | {
"question_id": 2245442,
"question_date": "2010-02-11T15:24:15.950Z",
"question_score": 813,
"tags": "c#|.net|string|split",
"answer_id": 2245460,
"answer_date": "2010-02-11T15:26:22.277Z",
"answer_score": 1453
} |
Please answer the following Stack Overflow question:
Title: What exactly do "u" and "r" string prefixes do, and what are raw string literals?
<p>While asking <a href="https://stackoverflow.com/questions/2081622/python-raw-strings-and-unicode-how-to-use-web-for-input-as-regexp-patterns">this question</a>, I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks.</p>
<p>I know what an encoding is, and I know what <code>u''</code> alone does since I get what is Unicode.</p>
<ul>
<li><p>But what does <code>r''</code> do exactly? What kind of string does it result in?</p></li>
<li><p>And above all, what the heck does <code>ur''</code> do?</p></li>
<li><p>Finally, is there any reliable way to go back from a Unicode string to a simple raw string?</p></li>
<li><p>Ah, and by the way, if your system and your text editor charset are set to UTF-8, does <code>u''</code> actually do anything?</p></li>
</ul> | <p>There's not really any "raw <em>string</em>"; there are raw <em>string literals</em>, which are exactly the string literals marked by an <code>'r'</code> before the opening quote.</p>
<p>A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, <code>\</code>, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence.</p>
<p>This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them -- that's all. It also gained some popularity to express native Windows file paths (with backslashes instead of regular slashes like on other platforms), but that's very rarely needed (since normal slashes mostly work fine on Windows too) and imperfect (due to the "except" clause above).</p>
<p><code>r'...'</code> is a byte string (in Python 2.*), <code>ur'...'</code> is a Unicode string (again, in Python 2.*), and any of the other three kinds of quoting also produces exactly the same types of strings (so for example <code>r'...'</code>, <code>r'''...'''</code>, <code>r"..."</code>, <code>r"""..."""</code> are all byte strings, and so on).</p>
<p>Not sure what you mean by "going <em>back</em>" - there is no intrinsically back and forward directions, because there's no raw string <strong>type</strong>, it's just an alternative syntax to express perfectly normal string objects, byte or unicode as they may be.</p>
<p>And yes, in Python 2.*, <code>u'...'</code> <strong>is</strong> of course always distinct from just <code>'...'</code> -- the former is a unicode string, the latter is a byte string. What encoding the literal might be expressed in is a completely orthogonal issue.</p>
<p>E.g., consider (Python 2.6):</p>
<pre><code>>>> sys.getsizeof('ciao')
28
>>> sys.getsizeof(u'ciao')
34
</code></pre>
<p>The Unicode object of course takes more memory space (very small difference for a very short string, obviously ;-).</p> | {
"question_id": 2081640,
"question_date": "2010-01-17T16:22:57.770Z",
"question_score": 813,
"tags": "python|unicode|python-2.x|rawstring",
"answer_id": 2081708,
"answer_date": "2010-01-17T16:38:39.220Z",
"answer_score": 824
} |
Please answer the following Stack Overflow question:
Title: Undo git stash pop that results in merge conflict
<p>I began making changes to my codebase, not realizing I was on an old topic branch. To transfer them, I wanted to stash them and then apply them to a new branch off of master. I used <code>git stash pop</code> to transfer work-in-progress changes to this new branch, forgetting that I hadn't pulled new changes into master before creating the new branch. This resulted in a bunch of merge conflicts and loss of a clean stash of my changes (since I used pop).</p>
<p>Once I recreate the new branch correctly, how I can I recover my stashed changes to apply them properly? </p> | <p>As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:</p>
<ol>
<li>To unstage the merge conflicts: <code>git reset HEAD .</code> (note the trailing dot)</li>
<li>To save the conflicted merge (just in case): <code>git stash</code></li>
<li>To return to master: <code>git checkout master</code></li>
<li>To pull latest changes: <code>git fetch upstream; git merge upstream/master</code></li>
<li>To correct my new branch: <code>git checkout new-branch; git rebase master</code></li>
<li>To apply the correct stashed changes (now 2nd on the stack): <code>git stash apply stash@{1}</code></li>
</ol> | {
"question_id": 22207256,
"question_date": "2014-03-05T19:25:18.267Z",
"question_score": 813,
"tags": "git|git-stash",
"answer_id": 22207257,
"answer_date": "2014-03-05T19:25:18.267Z",
"answer_score": 939
} |
Please answer the following Stack Overflow question:
Title: Create an empty list with certain size in Python
<p>How do I create an empty list that can hold 10 elements?</p>
<p>After that, I want to assign values in that list. For example:</p>
<pre class="lang-py prettyprint-override"><code>xs = list()
for i in range(0, 9):
xs[i] = i
</code></pre>
<p>However, that gives <code>IndexError: list assignment index out of range</code>. Why?</p>
<hr />
<p><strong>Editor's note:</strong></p>
<p><sub>In Python, lists <strong>do not have a set capacity</strong>, but it is not possible to assign to elements that aren't already present. Answers here show code that creates a list with 10 "dummy" elements to replace later. However, most beginners encountering this problem <em>really just want to build a list by adding elements to it</em>. That should be done using the <code>.append</code> method, although there will often be problem-specific ways to create the list more directly. Please see <a href="https://stackoverflow.com/questions/5653533">Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list?</a> for details.</sub></p> | <p>You cannot assign to a list like <code>xs[i] = value</code>, unless the list already is initialized with at least <code>i+1</code> elements. Instead, use <code>xs.append(value)</code> to add elements to the end of the list. (Though you could use the assignment notation if you were using a dictionary instead of a list.)</p>
<p>Creating an empty list:</p>
<pre><code>>>> xs = [None] * 10
>>> xs
[None, None, None, None, None, None, None, None, None, None]
</code></pre>
<p>Assigning a value to an existing element of the above list:</p>
<pre><code>>>> xs[1] = 5
>>> xs
[None, 5, None, None, None, None, None, None, None, None]
</code></pre>
<p>Keep in mind that something like <code>xs[15] = 5</code> would still fail, as our list has only 10 elements.</p>
<p>range(x) creates a list from [0, 1, 2, ... x-1]</p>
<pre><code># 2.X only. Use list(range(10)) in 3.X.
>>> xs = range(10)
>>> xs
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<p>Using a function to create a list:</p>
<pre><code>>>> def display():
... xs = []
... for i in range(9): # This is just to tell you how to create a list.
... xs.append(i)
... return xs
...
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<p>List comprehension (Using the squares because for range you don't need to do all this, you can just return <code>range(0,9)</code> ):</p>
<pre><code>>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]
</code></pre> | {
"question_id": 10712002,
"question_date": "2012-05-23T00:38:24.613Z",
"question_score": 812,
"tags": "python|list",
"answer_id": 10712044,
"answer_date": "2012-05-23T00:44:12.223Z",
"answer_score": 1221
} |
Please answer the following Stack Overflow question:
Title: Remove trailing delimiting character from a delimited string
<p>What is fastest way to remove the last character from a string?</p>
<p>I have a string like</p>
<pre><code>a,b,c,d,e,
</code></pre>
<p>I would like to remove the last ',' and get the remaining string back:</p>
<pre><code>OUTPUT: a,b,c,d,e
</code></pre>
<p>What is the fastest way to do this?</p> | <p>Contrary to the question asked, <code>rtrim()</code> will remove <em>any number</em> of characters, listed in the second argument, from the end of the string. In case you expect just a single comma, the following code would do:</p>
<pre><code>$newarraynama = rtrim($arraynama, ",");
</code></pre>
<p>But in my case I had 2 characters, a comma and a space, so I had to change to</p>
<pre><code>$newarraynama = rtrim($arraynama, " ,");
</code></pre>
<p>and now it would remove all commas and spaces from the end of the string, returning <code>a, b, c, d, e</code> either from <code>a, b, c, d, e,</code>, <code>a, b, c, d, e,,,</code>, <code>a, b, c, d, e, </code> or <code>a, b, c, d, e , ,, , ,</code></p>
<p>But in case there could be multiple commas but you need to remove <em>only the last one</em>, then <code>rtrim()</code> shouldn't be used at all - see other answers for the solution that directly answers the question.</p>
<p>However, <code>rtrim()</code> could be a good choice if you don't know whether the extra character could be present or not. Unlike <code>substr</code>-based solutions it will return <code>a, b, c, d, e</code> from <code>a, b, c, d, e</code></p> | {
"question_id": 5592994,
"question_date": "2011-04-08T09:15:10.207Z",
"question_score": 812,
"tags": "php|csv|delimiter|truncate|trailing",
"answer_id": 5593009,
"answer_date": "2011-04-08T09:16:11.090Z",
"answer_score": 1306
} |
Please answer the following Stack Overflow question:
Title: How to concatenate two MP4 files using FFmpeg?
<p>I'm trying to concatenate two mp4 files using ffmpeg. I need this to be an automatic process hence why I chose ffmpeg. I'm converting the two files into <code>.ts</code> files and then concatenating them and then trying to encode that concatenated <code>.ts</code> file. The files are <code>h264</code> and <code>aac</code> encoded and I'm hoping to keep the quality the same or as close to original as possible.</p>
<pre><code>ffmpeg -i part1.mp4 -vcodec copy -vbsf h264_mp4toannexb -acodec copy part1.ts
ffmpeg -i part2.mp4 -vcodec copy -vbsf h264_mp4toannexb -acodec copy part2.ts
cat part1.ts part2.ts > parts.ts
ffmpeg -y -i parts.ts -acodec copy -ar 44100 -ab 96k -coder ac -vbsf h264_mp4toannexb parts.mp4
</code></pre>
<p>Unfortunately I'm getting the following error message coming back from ffmpeg during encoding:</p>
<pre><code>[h264 @ 0x1012600]sps_id out of range
[h264 @ 0x1012600]non-existing SPS 0 referenced in buffering period
[h264 @ 0x1012600]sps_id out of range
[h264 @ 0x1012600]non-existing SPS 0 referenced in buffering period
[NULL @ 0x101d600]error, non monotone timestamps 13779431 >= 13779431kbits/s
av_interleaved_write_frame(): Error while opening file
</code></pre>
<p>This happens about half way through encoding which makes me think that you can't concat two .ts files together and have it work.</p> | <p>I ended up using mpg as the intermediate format and it worked (NOTE this is a dangerous example, -qscale 0 will re-encode the video...)</p>
<pre><code>ffmpeg -i 1.mp4 -qscale 0 1.mpg
ffmpeg -i 2.mp4 -qscale 0 2.mpg
cat 1.mpg 2.mpg | ffmpeg -f mpeg -i - -qscale 0 -vcodec mpeg4 output.mp4
</code></pre> | {
"question_id": 7333232,
"question_date": "2011-09-07T11:40:01.017Z",
"question_score": 812,
"tags": "ffmpeg|h.264|mp4",
"answer_id": 7333453,
"answer_date": "2011-09-07T11:53:46.070Z",
"answer_score": 41
} |
Please answer the following Stack Overflow question:
Title: How do you write multiline strings in Go?
<p>Does Go have anything similar to Python's multiline strings: </p>
<pre class="lang-python prettyprint-override"><code>"""line 1
line 2
line 3"""
</code></pre>
<p>If not, what is the preferred way of writing strings spanning multiple lines?</p> | <p>According to the <a href="http://golang.org/doc/go_spec.html#String_literals" rel="noreferrer">language specification</a>, you can use a raw string literal, where the string is delimited by backticks instead of double quotes.</p>
<pre><code>`line 1
line 2
line 3`
</code></pre> | {
"question_id": 7933460,
"question_date": "2011-10-28T18:44:35.050Z",
"question_score": 812,
"tags": "string|go|multiline",
"answer_id": 7933487,
"answer_date": "2011-10-28T18:46:44.223Z",
"answer_score": 1254
} |
Please answer the following Stack Overflow question:
Title: How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
<p>I have a simple key/value list in JSON being sent back to ASP.NET via POST. Example:</p>
<pre><code>{ "key1": "value1", "key2": "value2"}
</code></pre>
<p><strong>I AM NOT TRYING TO DESERIALIZE INTO STRONGLY-TYPED .NET OBJECTS</strong></p>
<p>I simply need a plain old <strong>Dictionary(Of String, String)</strong>, or some equivalent (hash table, Dictionary(Of String, Object), old-school StringDictionary--hell, a 2-D array of strings would work for me.</p>
<p>I can use anything available in ASP.NET 3.5, as well as the popular Json.NET (which I'm already using for serialization <strong>to</strong> the client).</p>
<p>Apparently neither of these JSON libraries have this forehead-slapping obvious capability out of the box--they are totally focused on reflection-based deserialization via strong contracts.</p>
<p>Any ideas?</p>
<p>Limitations:</p>
<ol>
<li>I don't want to implement my own JSON parser</li>
<li>Can't use ASP.NET 4.0 yet</li>
<li>Would prefer to stay away from the older, deprecated ASP.NET class for JSON</li>
</ol> | <p><a href="https://www.newtonsoft.com/json" rel="noreferrer">Json.NET</a> does this...</p>
<pre><code>string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
</code></pre>
<p>More examples: <a href="https://www.newtonsoft.com/json/help/html/SerializingCollections.htm" rel="noreferrer">Serializing Collections with Json.NET</a></p> | {
"question_id": 1207731,
"question_date": "2009-07-30T16:28:00.423Z",
"question_score": 811,
"tags": "json|asp.net-ajax|asp.net-3.5|json.net",
"answer_id": 1212115,
"answer_date": "2009-07-31T11:51:02.577Z",
"answer_score": 1058
} |
Please answer the following Stack Overflow question:
Title: How to delete all files and folders in a directory?
<p>Using C#, how can I delete all files and folders from a directory, but still keep the root directory?</p> | <pre><code>System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
</code></pre>
<hr>
<p>If your directory may have many files, <code>EnumerateFiles()</code> is more efficient than <code>GetFiles()</code>, because when you use <code>EnumerateFiles()</code> you can start enumerating it before the whole collection is returned, as opposed to <code>GetFiles()</code> where you need to load the entire collection in memory before begin to enumerate it. See this quote <a href="https://msdn.microsoft.com/en-us/library/ms143327(v=vs.110).aspx" rel="noreferrer">here</a>:</p>
<blockquote>
<p>Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.</p>
</blockquote>
<p>The same applies to <code>EnumerateDirectories()</code> and <code>GetDirectories()</code>. So the code would be:</p>
<pre><code>foreach (FileInfo file in di.EnumerateFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
dir.Delete(true);
}
</code></pre>
<p>For the purpose of this question, there is really no reason to use <code>GetFiles()</code> and <code>GetDirectories()</code>.</p> | {
"question_id": 1288718,
"question_date": "2009-08-17T15:48:19.233Z",
"question_score": 811,
"tags": "c#|.net",
"answer_id": 1288747,
"answer_date": "2009-08-17T15:52:45.700Z",
"answer_score": 1028
} |
Please answer the following Stack Overflow question:
Title: Why can't I change directories using "cd" in a script?
<p>I'm trying to write a small script to change the current directory to my project directory:</p>
<pre><code>#!/bin/bash
cd /home/tree/projects/java
</code></pre>
<p>I saved this file as proj, added execute permission with <code>chmod</code>, and copied it to <code>/usr/bin</code>. When I call it by:
<code>proj</code>, it does nothing. What am I doing wrong?</p> | <p>Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The <code>cd</code> succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.</p>
<p>One way to get around this is to use an alias instead:</p>
<pre><code>alias proj="cd /home/tree/projects/java"
</code></pre> | {
"question_id": 255414,
"question_date": "2008-11-01T02:07:08.800Z",
"question_score": 811,
"tags": "bash",
"answer_id": 255415,
"answer_date": "2008-11-01T02:09:06.970Z",
"answer_score": 682
} |
Please answer the following Stack Overflow question:
Title: How to check whether an object is a date?
<p>I have an annoying bug in on a webpage:</p>
<blockquote>
<p>date.GetMonth() is not a function</p>
</blockquote>
<p>So, I suppose that I am doing something wrong. The variable <code>date</code> is not an object of type <code>Date</code>. <strong>How can I check for a datatype in Javascript?</strong> I tried to add a <code>if (date)</code>, but it doesn't work.</p>
<pre><code>function getFormatedDate(date) {
if (date) {
var month = date.GetMonth();
}
}
</code></pre>
<p>So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?</p>
<p>Thanks!</p>
<p><strong>UPDATE:</strong> I don't want to check the format of the date, but I want to be sure that the parameter passed to the method <code>getFormatedDate()</code> is of type <code>Date</code>.</p> | <p>As an alternative to duck typing via</p>
<pre><code>typeof date.getMonth === 'function'
</code></pre>
<p>you can use the <code>instanceof</code> operator, i.e. But it will return true for invalid dates too, e.g. <code>new Date('random_string')</code> is also instance of Date</p>
<pre><code>date instanceof Date
</code></pre>
<p>This will fail if objects are passed across frame boundaries.</p>
<p>A work-around for this is to check the object's class via</p>
<pre><code>Object.prototype.toString.call(date) === '[object Date]'
</code></pre> | {
"question_id": 643782,
"question_date": "2009-03-13T17:31:06.690Z",
"question_score": 811,
"tags": "javascript|date",
"answer_id": 643827,
"answer_date": "2009-03-13T17:43:37.300Z",
"answer_score": 1410
} |
Please answer the following Stack Overflow question:
Title: Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?
<p>My Python package has a <code>setup.py</code> which builds fine locally on Ubuntu Trusty and on a fresh Vagrant Ubuntu Trusty VM when I provision it like this:</p>
<pre><code>sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
sudo -H pip install setuptools wheel virtualenv --upgrade
</code></pre>
<p>But when I do the same on a Travis CI Trusty Beta VM:</p>
<pre><code>- sudo apt-get install python python-dev --force-yes --assume-yes --fix-broken
- curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7
- sudo -H pip install setuptools wheel virtualenv --upgrade
</code></pre>
<p>I get:</p>
<pre><code>python2.7 setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
</code></pre>
<p>This <a href="https://stackoverflow.com/questions/26664102/why-can-i-not-create-a-wheel-in-python">Why can I not create a wheel in python?</a> is related but note I am installing wheel and upgrading setuptools.</p> | <p>Had to install the <code>wheel</code> package. Everything was up to date but still giving the error.</p>
<pre><code>pip install wheel
</code></pre>
<p>then</p>
<pre><code>python setup.py bdist_wheel
</code></pre>
<p>worked without issues.</p> | {
"question_id": 34819221,
"question_date": "2016-01-15T20:19:56.813Z",
"question_score": 811,
"tags": "python|travis-ci|setup.py|pypi",
"answer_id": 44862371,
"answer_date": "2017-07-01T15:03:34.530Z",
"answer_score": 1295
} |
Please answer the following Stack Overflow question:
Title: Node.js Best Practice Exception Handling
<p>I just started trying out node.js a few days ago. I've realized that the Node is terminated whenever I have an unhandled exception in my program. This is different than the normal server container that I have been exposed to where only the Worker Thread dies when unhandled exceptions occur and the container would still be able to receive the request. This raises a few questions:</p>
<ul>
<li>Is <code>process.on('uncaughtException')</code> the only effective way to guard against it? </li>
<li>Will <code>process.on('uncaughtException')</code> catch the unhandled exception during execution of asynchronous processes as well?</li>
<li>Is there a module that is already built (such as sending email or writing to a file) that I could leverage in the case of uncaught exceptions?</li>
</ul>
<p>I would appreciate any pointer/article that would show me the common best practices for handling uncaught exceptions in node.js</p> | <p>Update: Joyent now has <a href="https://www.joyent.com/node-js/production/design/errors" rel="noreferrer">their own guide</a>. The following information is more of a summary:</p>
<h2>Safely "throwing" errors</h2>
<p>Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:</p>
<ul>
<li><p>For synchronous code, if an error happens, return the error:</p>
<pre><code>// Define divider as a syncrhonous function
var divideSync = function(x,y) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by returning it
return new Error("Can't divide by zero")
}
else {
// no error occured, continue on
return x/y
}
}
// Divide 4/2
var result = divideSync(4,2)
// did an error occur?
if ( result instanceof Error ) {
// handle the error safely
console.log('4/2=err', result)
}
else {
// no error occured, continue on
console.log('4/2='+result)
}
// Divide 4/0
result = divideSync(4,0)
// did an error occur?
if ( result instanceof Error ) {
// handle the error safely
console.log('4/0=err', result)
}
else {
// no error occured, continue on
console.log('4/0='+result)
}
</code></pre></li>
<li><p>For callback-based (ie. asynchronous) code, the first argument of the callback is <code>err</code>, if an error happens <code>err</code> is the error, if an error doesn't happen then <code>err</code> is <code>null</code>. Any other arguments follow the <code>err</code> argument:</p>
<pre><code>var divide = function(x,y,next) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by calling the completion callback
// with the first argument being the error
next(new Error("Can't divide by zero"))
}
else {
// no error occured, continue on
next(null, x/y)
}
}
divide(4,2,function(err,result){
// did an error occur?
if ( err ) {
// handle the error safely
console.log('4/2=err', err)
}
else {
// no error occured, continue on
console.log('4/2='+result)
}
})
divide(4,0,function(err,result){
// did an error occur?
if ( err ) {
// handle the error safely
console.log('4/0=err', err)
}
else {
// no error occured, continue on
console.log('4/0='+result)
}
})
</code></pre></li>
<li><p>For <a href="http://nodejs.org/api/events.html" rel="noreferrer">eventful</a> code, where the error may happen anywhere, instead of throwing the error, fire the <a href="http://nodejs.org/api/events.html#events_class_events_eventemitter" rel="noreferrer"><code>error</code> event instead</a>:</p>
<pre><code>// Definite our Divider Event Emitter
var events = require('events')
var Divider = function(){
events.EventEmitter.call(this)
}
require('util').inherits(Divider, events.EventEmitter)
// Add the divide function
Divider.prototype.divide = function(x,y){
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by emitting it
var err = new Error("Can't divide by zero")
this.emit('error', err)
}
else {
// no error occured, continue on
this.emit('divided', x, y, x/y)
}
// Chain
return this;
}
// Create our divider and listen for errors
var divider = new Divider()
divider.on('error', function(err){
// handle the error safely
console.log(err)
})
divider.on('divided', function(x,y,result){
console.log(x+'/'+y+'='+result)
})
// Divide
divider.divide(4,2).divide(4,0)
</code></pre></li>
</ul>
<h2>Safely "catching" errors</h2>
<p>Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:</p>
<ul>
<li><p>When we know where the error is occurring, we can wrap that section in a <a href="http://nodejs.org/api/domain.html" rel="noreferrer">node.js domain</a></p>
<pre><code>var d = require('domain').create()
d.on('error', function(err){
// handle the error safely
console.log(err)
})
// catch the uncaught errors in this asynchronous or synchronous code block
d.run(function(){
// the asynchronous or synchronous code that we want to catch thrown errors on
var err = new Error('example')
throw err
})
</code></pre></li>
<li><p>If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:</p>
<pre><code>// catch the uncaught errors in this synchronous code block
// try catch statements only work on synchronous code
try {
// the synchronous code that we want to catch thrown errors on
var err = new Error('example')
throw err
} catch (err) {
// handle the error safely
console.log(err)
}
</code></pre>
<p>However, be careful not to use <code>try...catch</code> in asynchronous code, as an asynchronously thrown error will not be caught:</p>
<pre><code>try {
setTimeout(function(){
var err = new Error('example')
throw err
}, 1000)
}
catch (err) {
// Example error won't be caught here... crashing our app
// hence the need for domains
}
</code></pre>
<p>If you do want to work with <code>try..catch</code> in conjunction with asynchronous code, when running Node 7.4 or higher you can use <code>async/await</code> natively to write your asynchronous functions.</p>
<p>Another thing to be careful about with <code>try...catch</code> is the risk of wrapping your completion callback inside the <code>try</code> statement like so:</p>
<pre><code>var divide = function(x,y,next) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by calling the completion callback
// with the first argument being the error
next(new Error("Can't divide by zero"))
}
else {
// no error occured, continue on
next(null, x/y)
}
}
var continueElsewhere = function(err, result){
throw new Error('elsewhere has failed')
}
try {
divide(4, 2, continueElsewhere)
// ^ the execution of divide, and the execution of
// continueElsewhere will be inside the try statement
}
catch (err) {
console.log(err.stack)
// ^ will output the "unexpected" result of: elsewhere has failed
}
</code></pre>
<p>This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.</p></li>
<li><p>Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the <code>uncaughtException</code> listener (however doing so can put the application in an <a href="http://nodejs.org/api/process.html#process_event_uncaughtexception" rel="noreferrer">unknown state</a>):</p>
<pre><code>// catch the uncaught errors that weren't wrapped in a domain or try catch statement
// do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
process.on('uncaughtException', function(err) {
// handle the error safely
console.log(err)
})
// the asynchronous or synchronous code that emits the otherwise uncaught error
var err = new Error('example')
throw err
</code></pre></li>
</ul> | {
"question_id": 7310521,
"question_date": "2011-09-05T16:15:20.037Z",
"question_score": 811,
"tags": "node.js|exception-handling|serverside-javascript",
"answer_id": 7313005,
"answer_date": "2011-09-05T21:45:12.303Z",
"answer_score": 786
} |
Please answer the following Stack Overflow question:
Title: How to use multiprocessing pool.map with multiple arguments
<p>In the Python <a href="https://docs.python.org/3/library/multiprocessing.html" rel="noreferrer"><code>multiprocessing</code></a> library, is there a variant of <code>pool.map</code> which supports multiple arguments?</p>
<pre><code>import multiprocessing
text = "test"
def harvester(text, case):
X = case[0]
text + str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text, case), case, 1)
pool.close()
pool.join()
</code></pre> | <p>The answer to this is version- and situation-dependent. The most general answer for recent versions of Python (since 3.3) was first described below by <a href="https://stackoverflow.com/a/5443941/577088">J.F. Sebastian</a>.<sup>1</sup> It uses the <a href="http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap" rel="noreferrer"><code>Pool.starmap</code></a> method, which accepts a sequence of argument tuples. It then automatically unpacks the arguments from each tuple and passes them to the given function:</p>
<pre><code>import multiprocessing
from itertools import product
def merge_names(a, b):
return '{} & {}'.format(a, b)
if __name__ == '__main__':
names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
with multiprocessing.Pool(processes=3) as pool:
results = pool.starmap(merge_names, product(names, repeat=2))
print(results)
# Output: ['Brown & Brown', 'Brown & Wilson', 'Brown & Bartlett', ...
</code></pre>
<p>For earlier versions of Python, you'll need to write a helper function to unpack the arguments explicitly. If you want to use <code>with</code>, you'll also need to write a wrapper to turn <code>Pool</code> into a context manager. (Thanks to <a href="https://stackoverflow.com/questions/5442910/python-multiprocessing-pool-map-for-multiple-arguments/5442981?noredirect=1#comment80290057_5442981">muon</a> for pointing this out.)</p>
<pre><code>import multiprocessing
from itertools import product
from contextlib import contextmanager
def merge_names(a, b):
return '{} & {}'.format(a, b)
def merge_names_unpack(args):
return merge_names(*args)
@contextmanager
def poolcontext(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
if __name__ == '__main__':
names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
with poolcontext(processes=3) as pool:
results = pool.map(merge_names_unpack, product(names, repeat=2))
print(results)
# Output: ['Brown & Brown', 'Brown & Wilson', 'Brown & Bartlett', ...
</code></pre>
<p>In simpler cases, with a fixed second argument, you can also use <code>partial</code>, but only in Python 2.7+.</p>
<pre><code>import multiprocessing
from functools import partial
from contextlib import contextmanager
@contextmanager
def poolcontext(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
def merge_names(a, b):
return '{} & {}'.format(a, b)
if __name__ == '__main__':
names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
with poolcontext(processes=3) as pool:
results = pool.map(partial(merge_names, b='Sons'), names)
print(results)
# Output: ['Brown & Sons', 'Wilson & Sons', 'Bartlett & Sons', ...
</code></pre>
<p><sup>1. Much of this was inspired by his answer, which should probably have been accepted instead. But since this one is stuck at the top, it seemed best to improve it for future readers.</sup></p> | {
"question_id": 5442910,
"question_date": "2011-03-26T14:23:10.920Z",
"question_score": 810,
"tags": "python|multiprocessing|python-multiprocessing",
"answer_id": 5442981,
"answer_date": "2011-03-26T14:36:42.557Z",
"answer_score": 490
} |
Please answer the following Stack Overflow question:
Title: Get first key in a (possibly) associative array?
<p>What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:</p>
<pre><code>foreach ($an_array as $key => $val) break;
</code></pre>
<p>Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?</p> | <h2>2019 Update</h2>
<p>Starting from <strong>PHP 7.3</strong>, there is a new built in function called <code>array_key_first()</code> which will retrieve the first key from the given array without resetting the internal pointer. Check out the <a href="http://php.net/manual/en/function.array-key-first.php" rel="noreferrer">documentation</a> for more info.</p>
<hr>
<p>You can use <a href="http://php.net/reset" rel="noreferrer"><code>reset</code></a> and <a href="http://php.net/key" rel="noreferrer"><code>key</code></a>:</p>
<pre><code>reset($array);
$first_key = key($array);
</code></pre>
<p>It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.</p>
<p>Just remember to call <code>reset</code>, or you may get any of the keys in the array. You can also use <a href="http://php.net/end" rel="noreferrer"><code>end</code></a> instead of <code>reset</code> to get the last key.</p>
<p>If you wanted the key to get the first value, <code>reset</code> actually returns it:</p>
<pre><code>$first_value = reset($array);
</code></pre>
<p>There is one special case to watch out for though (so check the length of the array first):</p>
<pre><code>$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)
</code></pre> | {
"question_id": 1028668,
"question_date": "2009-06-22T18:13:59.147Z",
"question_score": 810,
"tags": "php|arrays",
"answer_id": 1028677,
"answer_date": "2009-06-22T18:16:43.183Z",
"answer_score": 1411
} |
Please answer the following Stack Overflow question:
Title: How to fix "Attempted relative import in non-package" even with __init__.py
<p>I'm trying to follow <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328</a>, with the following directory structure:</p>
<pre><code>pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py
</code></pre>
<p>In <code>core_test.py</code> I have the following import statement</p>
<pre><code>from ..components.core import GameLoopEvents
</code></pre>
<p>However, when I run, I get the following error:</p>
<pre><code>tests$ python core_test.py
Traceback (most recent call last):
File "core_test.py", line 3, in <module>
from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package
</code></pre>
<p>Searching around I found "<a href="https://stackoverflow.com/questions/9427037/relative-path-not-working-even-with-init-py">relative path not working even with __init__.py</a>" and "<a href="https://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder/6098238#6098238">Import a module from a relative path</a>" but they didn't help.</p>
<p>Is there anything I'm missing here?</p> | <p>Yes. You're not using it as a package.</p>
<pre><code>python -m pkg.tests.core_test
</code></pre> | {
"question_id": 11536764,
"question_date": "2012-07-18T07:59:14.477Z",
"question_score": 810,
"tags": "python|package|python-import|importerror|init",
"answer_id": 11536794,
"answer_date": "2012-07-18T08:01:04.023Z",
"answer_score": 471
} |
Please answer the following Stack Overflow question:
Title: What is lexical scope?
<p>What is a brief introduction to lexical scoping?</p> | <p>I understand them through examples. :)</p>
<p>First, <em>lexical scope</em> (also called <em>static scope</em>), in C-like syntax:</p>
<pre><code>void fun()
{
int x = 5;
void fun2()
{
printf("%d", x);
}
}
</code></pre>
<p>Every inner level can access its outer levels.</p>
<p>There is another way, called <em>dynamic scope</em> used by the first implementation of <a href="https://en.wikipedia.org/wiki/Lisp_%28programming_language%29" rel="noreferrer">Lisp</a>, again in a C-like syntax:</p>
<pre><code>void fun()
{
printf("%d", x);
}
void dummy1()
{
int x = 5;
fun();
}
void dummy2()
{
int x = 10;
fun();
}
</code></pre>
<p>Here <code>fun</code> can either access <code>x</code> in <code>dummy1</code> or <code>dummy2</code>, or any <code>x</code> in any function that call <code>fun</code> with <code>x</code> declared in it.</p>
<pre><code>dummy1();
</code></pre>
<p>will print 5,</p>
<pre><code>dummy2();
</code></pre>
<p>will print 10.</p>
<p>The first one is called static because it can be deduced at compile-time, and the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.</p>
<p>I find static scoping easier for the eye. Most languages went this way eventually, even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.</p>
<p>As an example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example. If we write something like this:</p>
<pre><code>if(/* some condition */)
dummy1();
else
dummy2();
</code></pre>
<p>The call chain depends on a run time condition. If it is true, then the call chain looks like:</p>
<pre><code>dummy1 --> fun()
</code></pre>
<p>If the condition is false:</p>
<pre><code>dummy2 --> fun()
</code></pre>
<p>The outer scope of <code>fun</code> in both cases is the caller <em>plus the caller of the caller and so on</em>.</p>
<p>Just to mention that the C language does not allow nested functions nor dynamic scoping.</p> | {
"question_id": 1047454,
"question_date": "2009-06-26T05:10:15.523Z",
"question_score": 810,
"tags": "javascript|scoping|lexical-scope",
"answer_id": 1047491,
"answer_date": "2009-06-26T05:26:05.270Z",
"answer_score": 781
} |
Please answer the following Stack Overflow question:
Title: How to tell Jackson to ignore a field during serialization if its value is null?
<p>How can Jackson be configured to ignore a field value during serialization if that field's value is null. </p>
<p>For example:</p>
<pre><code>public class SomeClass {
// what jackson annotation causes jackson to skip over this value if it is null but will
// serialize it otherwise
private String someValue;
}
</code></pre> | <p>To suppress serializing properties with null values using Jackson >2.0, you can <a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonInclude.Include.html" rel="noreferrer">configure the <code>ObjectMapper</code> directly</a>, or make use of the <a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonInclude.html" rel="noreferrer"><code>@JsonInclude</code></a> annotation:</p>
<pre><code>mapper.setSerializationInclusion(Include.NON_NULL);
</code></pre>
<p>or:</p>
<pre><code>@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
</code></pre>
<p>Alternatively, you could use <code>@JsonInclude</code> in a getter so that the attribute would be shown if the value is not null.</p>
<p>A more complete example is available in <a href="https://stackoverflow.com/questions/11449211/how-to-prevent-null-values-inside-a-map-and-null-fields-inside-a-bean-from-getti/11464975#11464975">my answer</a> to <a href="https://stackoverflow.com/questions/11449211/">How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson</a>.</p> | {
"question_id": 11757487,
"question_date": "2012-08-01T10:40:31.037Z",
"question_score": 809,
"tags": "java|jackson",
"answer_id": 11761975,
"answer_date": "2012-08-01T14:57:34.390Z",
"answer_score": 1249
} |
Please answer the following Stack Overflow question:
Title: How do you install an APK file in the Android emulator?
<p>I finally managed to obfuscate my Android application, now I want to test it by installing the <a href="http://en.wikipedia.org/wiki/APK_%28file_format%29" rel="noreferrer">APK</a> file and running it on the emulator. </p>
<p>How can I install an APK file on the Android Emulator?</p> | <p><strong>You can simply drag and drop the .apk file of your application to the emulator and it will automatically start installing.</strong></p>
<p>Another option:</p>
<hr />
<p><strong>Windows:</strong></p>
<ol>
<li>Execute the emulator <a href="http://www.youtube.com/watch?v=HVysAukOpCA" rel="noreferrer">(SDK Manager.exe->Tools->Manage AVDs...->New then Start)</a></li>
<li>Start the console (Windows XP), Run -> type <strong>cmd</strong>, and move to the <strong>platform-tools</strong> folder of <strong>SDK</strong> directory.</li>
<li>Paste the <em>APK</em> file in the 'android-sdk\tools' or 'platform-tools' folder.</li>
<li>Then type the following command.</li>
</ol>
<blockquote>
<p>adb install [.apk path]</p>
</blockquote>
<p>Example:</p>
<blockquote>
<p>adb install C:\Users\Name\MyProject\build\Jorgesys.apk</p>
</blockquote>
<p><strong>Linux:</strong></p>
<ol>
<li>Copy the apk file to <code>platform-tools</code> in the <code>android-sdk linux</code> folder.</li>
<li>Open <strong>Terminal</strong> and <strong>navigate to platform-tools</strong> folder in <strong>android-sdk</strong>.</li>
<li>Then Execute this command -</li>
</ol>
<blockquote>
<p>./adb install FileName.apk</p>
</blockquote>
<ol start="4">
<li>If the operation is successful (the result is displayed on the screen), then you will find your file in the launcher of your emulator.</li>
</ol>
<p><strong>Mac:</strong></p>
<pre><code>PATH=$PATH:~/Library/Android/sdk/platform-tools
</code></pre>
<blockquote>
<p>Example : PATH=$PATH:/users/jorgesys/eclipse/android-sdk-mac_64/tools</p>
</blockquote>
<p>Then run adb.</p>
<p>Mac:</p>
<p>1.Run the emulator,</p>
<p>2.then copy your .apk file and paste into <code>/Users/your_system_username/Library/Android/sdk/platform-tools</code>,<br />
if you are not able to find sdk path in your mac system, do the following steps: Open <code>finder->select</code> Go option on top menu -> select Go to Folder option -> it will popup a window with a textfield: <code>/Users/your_system_username/Library/Android/sdk/</code> -> now open platform-tools folder and paste your copied .apk file,</p>
<ol start="3">
<li><p>Now open the terminal and type the following:
<code>cd Library/Android/sdk/platform-tools</code></p>
</li>
<li><p>execute the following in your terminal: <code>./adb install yourapkfilename.apk</code> if you get the following error message: <code>error: no devices found - waiting for device</code>, follow step 5.</p>
</li>
<li><p>Run your emulator from Android Studio, once emulator active then repeat step 4, you will see the success message on your terminal.</p>
</li>
</ol> | {
"question_id": 3480201,
"question_date": "2010-08-13T19:43:31.777Z",
"question_score": 809,
"tags": "android|android-emulator|installation|apk",
"answer_id": 3480235,
"answer_date": "2010-08-13T19:50:07.973Z",
"answer_score": 1119
} |
Please answer the following Stack Overflow question:
Title: What's the best way to limit text length of EditText in Android
<p>What's the best way to limit the text length of an <code>EditText</code> in Android?</p>
<p>Is there a way to do this via xml?</p> | <p><a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android:maxLength" rel="noreferrer">Documentation</a></p>
<p><a href="http://androidblogger.blogspot.com/2009/01/numeric-edittext-and-edittext-with-max.html" rel="noreferrer">Example</a></p>
<pre><code>android:maxLength="10"
</code></pre> | {
"question_id": 3285412,
"question_date": "2010-07-19T21:55:42.207Z",
"question_score": 809,
"tags": "android|android-edittext|maxlength",
"answer_id": 3285421,
"answer_date": "2010-07-19T21:57:12.593Z",
"answer_score": 1563
} |
Please answer the following Stack Overflow question:
Title: What are the rules for calling the base class constructor?
<p>What are the C++ rules for calling the base class constructor from a derived class?</p>
<p>For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).</p> | <p>Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".</p>
<pre><code>class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
</code></pre>
<p>More info on the constructor's initialization list <a href="http://www.cprogramming.com/tutorial/initialization-lists-c++.html" rel="noreferrer">here</a> and <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6" rel="noreferrer">here</a>.</p> | {
"question_id": 120876,
"question_date": "2008-09-23T13:09:20.570Z",
"question_score": 808,
"tags": "c++|inheritance|constructor",
"answer_id": 120916,
"answer_date": "2008-09-23T13:18:34.853Z",
"answer_score": 1099
} |
Please answer the following Stack Overflow question:
Title: Get selected element's outer HTML
<p>I'm trying to get the HTML of a selected object with jQuery. I am aware of the <code>.html()</code> function; the issue is that I need the HTML including the selected object (a table row in this case, where <code>.html()</code> only returns the cells inside the row).</p>
<p>I've searched around and found a few very ‘hackish’ type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of <code>outerHtml</code> functionality?</p> | <p><em>2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.</em></p>
<p>This site seems to have a solution for you :
<a href="http://yelotofu.com/2008/08/jquery-outerhtml/" rel="noreferrer">jQuery: outerHTML | Yelotofu</a></p>
<pre><code>jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
</code></pre> | {
"question_id": 2419749,
"question_date": "2010-03-10T19:09:02.810Z",
"question_score": 808,
"tags": "jquery",
"answer_id": 2419877,
"answer_date": "2010-03-10T19:26:20.997Z",
"answer_score": 192
} |
Please answer the following Stack Overflow question:
Title: Difference between scaling horizontally and vertically for databases
<p>I have come across many NoSQL databases and SQL databases. There are varying parameters to measure the strength and weaknesses of these databases and scalability is one of them. What is the difference between horizontally and vertically scaling these databases?</p> | <p><strong>Horizontal scaling means that you scale by adding more machines</strong> into your pool of resources whereas <strong>Vertical scaling means that you scale by adding more power (CPU, RAM) to an existing machine</strong>.</p>
<p>An easy way to remember this is to think of a machine on a server rack, we add more machines across the <strong>horizontal</strong> direction and add more resources to a machine in the <strong>vertical</strong> direction.</p>
<p> <a href="https://i.stack.imgur.com/On3tO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/On3tO.png" alt="Horizontal Scaling/Vertical Scaling Visualisation" /></a></p>
<p>In the database world, horizontal-scaling is often based on the partitioning of the data i.e. each node contains only part of the data, in vertical-scaling the data resides on a single node and scaling is done through multi-core i.e. spreading the load between the CPU and RAM resources of that machine.</p>
<p>With horizontal-scaling it is often easier to scale dynamically by adding more machines into the existing pool - Vertical-scaling is often limited to the capacity of a single machine, scaling beyond that capacity often involves downtime and comes with an upper limit.</p>
<p>Good examples of horizontal scaling are Cassandra, MongoDB, <a href="https://cloud.google.com/spanner" rel="noreferrer">Google Cloud Spanner</a> .. and a good example of vertical scaling is MySQL - Amazon RDS (The cloud version of MySQL). It provides an easy way to scale vertically by switching from small to bigger machines. This process often involves downtime.</p>
<p>In-Memory Data Grids such as <a href="http://www.gigaspaces.com/datagrid" rel="noreferrer">GigaSpaces XAP</a>, <a href="http://www.oracle.com/technetwork/middleware/coherence/overview/index.html" rel="noreferrer">Coherence</a> etc.. are often optimized for both horizontal and vertical scaling simply because they're not bound to disk. Horizontal-scaling through partitioning and vertical-scaling through multi-core support.</p>
<p>You can read more on this subject in my earlier posts:
<a href="http://ht.ly/cAhPe" rel="noreferrer">Scale-out vs Scale-up</a> and <a href="http://ht.ly/cAhY6" rel="noreferrer">The Common Principles Behind the NOSQL Alternatives</a></p> | {
"question_id": 11707879,
"question_date": "2012-07-29T08:40:08.583Z",
"question_score": 808,
"tags": "database|database-design|nosql|scalability",
"answer_id": 11715598,
"answer_date": "2012-07-30T04:57:16.420Z",
"answer_score": 1425
} |
Please answer the following Stack Overflow question:
Title: How to get the current date/time in Java
<p>What's the best way to get the current date/time in Java?</p> | <p>It depends on what form of date / time you want:</p>
<ul>
<li><p>If you want the date / time as a single numeric value, then <code>System.currentTimeMillis()</code> gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java <code>long</code>). This value is a delta from a UTC time-point, and is independent of the local time-zone<sup>1</sup>.</p>
</li>
<li><p>If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:</p>
<ul>
<li><p><code>new Date()</code> gives you a <code>Date</code> object initialized with the current date / time. The problem is that the <code>Date</code> API methods are mostly flawed ... and deprecated.</p>
</li>
<li><p><code>Calendar.getInstance()</code> gives you a <code>Calendar</code> object initialized with the current date / time, using the default <code>Locale</code> and <code>TimeZone</code>. Other overloads allow you to use a specific <code>Locale</code> and/or <code>TimeZone</code>. Calendar works ... but the APIs are still cumbersome.</p>
</li>
<li><p><code>new org.joda.time.DateTime()</code> gives you a <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-time</a> object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. <a href="https://stackoverflow.com/questions/6280829.">https://stackoverflow.com/questions/6280829.</a>)</p>
</li>
<li><p>in Java 8, calling <code>java.time.LocalDateTime.now()</code> and <code>java.time.ZonedDateTime.now()</code> will give you representations<sup>2</sup> for the current date / time.</p>
</li>
</ul>
</li>
</ul>
<p>Prior to Java 8, most people who know about these things recommended <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-time</a> as having (by far) the best Java APIs for doing things involving time point and duration calculations.</p>
<p>With Java 8 and later, the standard <code>java.time</code> package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.<sup>3</sup>.</p>
<hr />
<p><sup>1 - <code>System.currentTimeMillis()</code> gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.<br>
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: <em>"It cannot represent an instant on the time-line without additional information such as an offset or time-zone."</em><br>
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.</sup></p> | {
"question_id": 5175728,
"question_date": "2011-03-03T01:48:09.583Z",
"question_score": 807,
"tags": "java|datetime",
"answer_id": 5175900,
"answer_date": "2011-03-03T02:13:55.547Z",
"answer_score": 743
} |
Please answer the following Stack Overflow question:
Title: Java URL encoding of query string parameters
<p>Say I have a URL </p>
<pre><code>http://example.com/query?q=
</code></pre>
<p>and I have a query entered by the user such as:</p>
<blockquote>
<p>random word £500 bank $</p>
</blockquote>
<p>I want the result to be a properly encoded URL:</p>
<pre><code>http://example.com/query?q=random%20word%20%A3500%20bank%20%24
</code></pre>
<p>What's the best way to achieve this? I tried <code>URLEncoder</code> and creating URI/URL objects but none of them come out quite right.</p> | <p><a href="https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/net/URLEncoder.html" rel="noreferrer"><code>URLEncoder</code></a> is the way to go. You only need to keep in mind to encode <em>only</em> the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character <code>&</code> nor the parameter name-value separator character <code>=</code>.</p>
<pre><code>String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
</code></pre>
<p>When you're still not on Java 10 or newer, then use <code>StandardCharsets.UTF_8.toString()</code> as charset argument, or when you're still not on Java 7 or newer, then use <code>"UTF-8"</code>.</p>
<hr />
<p>Note that spaces in query parameters are represented by <code>+</code>, not <code>%20</code>, which is legitimately valid. The <code>%20</code> is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character <code>?</code>), not in query string (the part after <code>?</code>).</p>
<p>Also note that there are three <code>encode()</code> methods. One without <code>Charset</code> as second argument and another with <code>String</code> as second argument which throws a checked exception. The one without <code>Charset</code> argument is deprecated. Never use it and always specify the <code>Charset</code> argument. The <a href="https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/net/URLEncoder.html" rel="noreferrer">javadoc</a> even explicitly recommends to use the UTF-8 encoding, as mandated by <a href="https://www.rfc-editor.org/rfc/rfc3986" rel="noreferrer">RFC3986</a> and <a href="http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars" rel="noreferrer">W3C</a>.</p>
<blockquote>
<p>All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. <strong>The recommended encoding scheme to use is UTF-8</strong>. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.</p>
</blockquote>
<h3>See also:</h3>
<ul>
<li><a href="https://www.talisman.org/%7Eerlkonig/misc/lunatech%5Ewhat-every-webdev-must-know-about-url-encoding/" rel="noreferrer">What every web developer must know about URL encoding</a></li>
</ul> | {
"question_id": 10786042,
"question_date": "2012-05-28T14:10:45.493Z",
"question_score": 807,
"tags": "java|http|url|encoding|urlencode",
"answer_id": 10786112,
"answer_date": "2012-05-28T14:15:36.947Z",
"answer_score": 1297
} |
Please answer the following Stack Overflow question:
Title: How can I detect pressing Enter on the keyboard using jQuery?
<p>I would like to detect whether the user has pressed <kbd>Enter</kbd> using jQuery.</p>
<p>How is this possible? Does it require a plugin?</p>
<p>It looks like I need to use the <a href="http://docs.jquery.com/Events/keypress" rel="noreferrer"><code>keypress()</code></a> method.</p>
<p>Are there browser issues with that command - like are there any browser compatibility issues I should know about?</p> | <p>The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with <kbd>enter</kbd> being 13 in all browsers. So with that in mind, you can do this:</p>
<pre><code>$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
</code></pre> | {
"question_id": 979662,
"question_date": "2009-06-11T06:39:43.170Z",
"question_score": 807,
"tags": "javascript|jquery|keyboard-events|enter|jquery-events",
"answer_id": 979686,
"answer_date": "2009-06-11T06:49:19.080Z",
"answer_score": 1462
} |
Please answer the following Stack Overflow question:
Title: Get current time in seconds since the Epoch on Linux, Bash
<p>I need something simple like <code>date</code>, but in seconds since 1970 instead of the current date, hours, minutes, and seconds.</p>
<p><code>date</code> doesn't seem to offer that option. Is there an easy way?</p> | <p>This should work:</p>
<pre><code>date +%s
</code></pre> | {
"question_id": 1092631,
"question_date": "2009-07-07T14:22:31.433Z",
"question_score": 807,
"tags": "linux|bash|datetime",
"answer_id": 1092643,
"answer_date": "2009-07-07T14:25:00.947Z",
"answer_score": 1479
} |
Please answer the following Stack Overflow question:
Title: How do I view 'git diff' output with my preferred diff tool/ viewer?
<p>When I type <code>git diff</code>, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?</p> | <p>Since Git1.6.3, you can use the <strong>git difftool script</strong>: see <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242">my answer below</a>.</p>
<hr>
<p>May be this <a href="https://web.archive.org/web/20170508180316/http://git.net:80/ml/version-control.msysgit/2008-06/msg00200.html" rel="noreferrer">article</a> will help you. Here are the best parts:</p>
<p>There are two different ways to specify an external diff tool. </p>
<p>The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:</p>
<pre><code>path old-file old-hex old-mode new-file new-hex new-mode
</code></pre>
<p>As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.</p>
<p>The second method, which I prefer, is to <strong>configure the external diff tool via "git
config"</strong>. Here is what I did:</p>
<p>1) Create a wrapper script "git-diff-wrapper.sh" which contains something like</p>
<pre><code>-->8-(snip)--
#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"<path_to_diff_executable>" "$2" "$5" | cat
--8<-(snap)--
</code></pre>
<p>As you can see, only the second ("old-file") and fifth ("new-file") arguments will be
passed to the diff tool.</p>
<p>2) Type</p>
<pre><code>$ git config --global diff.external <path_to_wrapper_script>
</code></pre>
<p>at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains</p>
<pre><code>-->8-(snip)--
[diff]
external = <path_to_wrapper_script>
--8<-(snap)--
</code></pre>
<p>Be sure to use the correct syntax to specify the paths to the wrapper script and diff
tool, i.e. use forward slashed instead of backslashes. In my case, I have</p>
<pre><code>[diff]
external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\"
</code></pre>
<p>in .gitconfig and</p>
<pre><code>"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat
</code></pre>
<p>in the wrapper script. Mind the trailing "cat"!</p>
<p>(I suppose the '<code>| cat</code>' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)</p>
<p>(<a href="https://stackoverflow.com/users/20520/diomidis-spinellis">Diomidis Spinellis</a> adds <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#comment96247087_255212">in the comments</a>: </p>
<blockquote>
<p>The <code>cat</code> command is required, because <a href="http://man7.org/linux/man-pages/man1/diff.1.html" rel="noreferrer"><code>diff(1)</code></a>, by default exits with an error code if the files differ.<br>
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.<br>
By piping the output of <code>git</code> to <code>cat</code> the non-zero error code is masked.<br>
More efficiently, the program could just run <code>exit</code> with and argument of 0.)</p>
</blockquote>
<hr>
<p>That (the article quoted above) is the theory for external tool <strong>defined through config file</strong> (not through environment variable).<br>
In practice (still for config file definition of external tool), you can refer to:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667">How do I setup DiffMerge with msysgit / gitk?</a> which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk</li>
<li><a href="https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#773973">How can I set up an editor to work with Git on Windows?</a> for the definition of Notepad++ as an external editor.</li>
</ul> | {
"question_id": 255202,
"question_date": "2008-10-31T22:55:12.493Z",
"question_score": 807,
"tags": "git|diff|difftool|git-difftool|diffmerge",
"answer_id": 255212,
"answer_date": "2008-10-31T23:03:43.460Z",
"answer_score": 406
} |
Please answer the following Stack Overflow question:
Title: How to cherry-pick a range of commits and merge them into another branch?
<p>I have the following repository layout:</p>
<ul>
<li>master branch (production)</li>
<li>integration</li>
<li>working</li>
</ul>
<p>What I want to achieve is to cherry-pick a range of commits from the working branch and merge it into the integration branch. I'm pretty new to git and I can't figure out how to exactly do this (the cherry-picking of commit ranges in one operation, not the merging) without messing the repository up. Any pointers or thoughts on this? Thanks!</p> | <p>When it comes to a range of commits, cherry-picking <del>is</del> <em>was</em> not practical.</p>
<p>As <a href="https://stackoverflow.com/a/3664543/6309">mentioned below</a> by <a href="https://stackoverflow.com/users/442025/keith-kim">Keith Kim</a>, Git 1.7.2+ introduced the ability to cherry-pick a range of commits (but you still need to be aware of the <a href="https://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112">consequence of cherry-picking for future merge</a>)</p>
<blockquote>
<p>git cherry-pick" learned to pick a range of commits<br />
(e.g. "<code>cherry-pick A..B</code>" and "<code>cherry-pick --stdin</code>"), so did "<code>git revert</code>"; these do not support the nicer sequencing control "<code>rebase [-i]</code>" has, though.</p>
</blockquote>
<p><a href="https://stackoverflow.com/users/42961/damian">damian</a> <a href="https://stackoverflow.com/a/3933416/6309">comments</a> and warns us:</p>
<blockquote>
<p>In the "<code>cherry-pick A..B</code>" form, <strong><code>A</code> should be older than <code>B</code></strong>.<br />
<strong>If they're the wrong order the command will silently fail</strong>.</p>
</blockquote>
<p>If you want to pick the <strong>range <code>B</code> through <code>D</code> (including <code>B</code>)</strong> that would be <strong><code>B^..D</code></strong> (instead of <code>B..D</code>).<br />
See "<a href="https://stackoverflow.com/a/9853814/6309">Git create branch from range of previous commits?</a>" as an illustration.</p>
<p>As <a href="https://stackoverflow.com/users/2541573/jubobs">Jubobs</a> mentions <a href="https://stackoverflow.com/questions/1994463/how-to-cherry-pick-a-range-of-commits-and-merge-into-another-branch/1994491#comment51629396_1994491">in the comments</a>:</p>
<blockquote>
<p>This assumes that <code>B</code> is not a root commit; you'll get an "<code>unknown revision</code>" error otherwise.</p>
</blockquote>
<p>Note: as of Git 2.9.x/2.10 (Q3 2016), you can cherry-pick a range of commit directly on an orphan branch (empty head): see "<a href="https://stackoverflow.com/a/38285663/6309">How to make existing branch an orphan in git</a>".</p>
<hr />
<p>Original answer (January 2010)</p>
<p>A <code>rebase --onto</code> would be better, where you replay the given range of commit on top of your integration branch, as <a href="https://stackoverflow.com/questions/509859/what-is-the-best-way-to-git-patch-a-subrange-of-a-branch">Charles Bailey described here</a>.<br />
(also, look for "Here is how you would transplant a topic branch based on one branch to another" in the <a href="http://git-scm.com/docs/git-rebase" rel="noreferrer">git rebase man page</a>, to see a practical example of <code>git rebase --onto</code>)</p>
<p>If your current branch is integration:</p>
<pre class="lang-sh prettyprint-override"><code># Checkout a new temporary branch at the current location
git checkout -b tmp
# Move the integration branch to the head of the new patchset
git branch -f integration last_SHA-1_of_working_branch_range
# Rebase the patchset onto tmp, the old location of integration
git rebase --onto tmp first_SHA-1_of_working_branch_range~1 integration
</code></pre>
<p>That will replay everything between:</p>
<ul>
<li>after the parent of <code>first_SHA-1_of_working_branch_range</code> (hence the <code>~1</code>): the first commit you want to replay</li>
<li>up to "<code>integration</code>" (which points to the last commit you want to replay, from the <code>working</code> branch)</li>
</ul>
<p>to "<code>tmp</code>" (which points to where <code>integration</code> was pointing before)</p>
<p>If there is any conflict when one of those commits is replayed:</p>
<ul>
<li>either solve it and run "<code>git rebase --continue</code>".</li>
<li>or skip this patch, and instead run "<code>git rebase --skip</code>"</li>
<li>or cancel the all thing with a "<code>git rebase --abort</code>" (and put back the <code>integration</code> branch on the <code>tmp</code> branch)</li>
</ul>
<p>After that <code>rebase --onto</code>, <code>integration</code> will be back at the last commit of the integration branch (that is "<code>tmp</code>" branch + all the replayed commits)</p>
<p>With cherry-picking or <code>rebase --onto</code>, do not forget it has consequences on subsequent merges, as <a href="https://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112">described here</a>.</p>
<hr />
<p>A pure "<code>cherry-pick</code>" solution is <a href="https://groups.google.com/d/msg/git-version-control/F0KYheOR2dY/pLj70x0A8L0J" rel="noreferrer">discussed here</a>, and would involve something like:</p>
<blockquote>
<p>If you want to use a patch approach then "git format-patch|git am" and "git cherry" are your options.<br />
Currently, <code>git cherry-pick</code> accepts only a single commit, but if you want to pick the range <code>B</code> through <code>D</code> that would be <code>B^..D</code> in git lingo, so</p>
</blockquote>
<pre class="lang-sh prettyprint-override"><code>git rev-list --reverse --topo-order B^..D | while read rev
do
git cherry-pick $rev || break
done
</code></pre>
<p>But anyway, when you need to "replay" a range of commits, the word "replay" should push you to use the "<code>rebase</code>" feature of Git.</p> | {
"question_id": 1994463,
"question_date": "2010-01-03T09:50:23.807Z",
"question_score": 807,
"tags": "git|git-merge|git-cherry-pick",
"answer_id": 1994491,
"answer_date": "2010-01-03T10:08:04.123Z",
"answer_score": 972
} |
Please answer the following Stack Overflow question:
Title: Disable ONLY_FULL_GROUP_BY
<p>I accidentally enabled ONLY_FULL_GROUP_BY mode like this:</p>
<pre><code>SET sql_mode = 'ONLY_FULL_GROUP_BY';
</code></pre>
<p>How do I disable it?</p> | <p><strong>Solution 1:</strong>
Remove <strong>ONLY_FULL_GROUP_BY</strong> from mysql console</p>
<pre><code>mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
</code></pre>
<p>you can read more <a href="http://johnemb.blogspot.com.ng/2014/09/adding-or-removing-individual-sql-modes.html" rel="noreferrer">here</a> </p>
<p><strong>Solution 2:</strong> Remove <strong>ONLY_FULL_GROUP_BY</strong> from phpmyadmin</p>
<ul>
<li>Open phpmyadmin & select localhost </li>
<li>Click on menu Variables & scroll down for sql mode</li>
<li>Click on edit button to change the values & remove <strong>ONLY_FULL_GROUP_BY</strong> & click on save.
<a href="https://i.stack.imgur.com/5CQdo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5CQdo.png" alt="enter image description here"></a></li>
</ul> | {
"question_id": 23921117,
"question_date": "2014-05-28T20:21:28.723Z",
"question_score": 806,
"tags": "mysql",
"answer_id": 36033983,
"answer_date": "2016-03-16T11:11:40.887Z",
"answer_score": 1527
} |
Please answer the following Stack Overflow question:
Title: Pandas Merging 101
<ul>
<li>How can I perform a (<code>INNER</code>| (<code>LEFT</code>|<code>RIGHT</code>|<code>FULL</code>) <code>OUTER</code>) <code>JOIN</code> with pandas?</li>
<li>How do I add NaNs for missing rows after a merge?</li>
<li>How do I get rid of NaNs after merging?</li>
<li>Can I merge on the index?</li>
<li>How do I merge multiple DataFrames?</li>
<li>Cross join with pandas</li>
<li><code>merge</code>? <code>join</code>? <code>concat</code>? <code>update</code>? Who? What? Why?!</li>
</ul>
<p>... and more. I've seen these recurring questions asking about various facets of the pandas merge functionality. Most of the information regarding merge and its various use cases today is fragmented across dozens of badly worded, unsearchable posts. The aim here is to collate some of the more important points for posterity.</p>
<p>This Q&A is meant to be the next installment in a series of helpful user guides on common pandas idioms (see <a href="https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe">this post on pivoting</a>, and <a href="https://stackoverflow.com/questions/49620538/what-are-the-levels-keys-and-names-arguments-for-in-pandas-concat-functio">this post on concatenation</a>, which I will be touching on, later).</p>
<p>Please note that this post is <em>not</em> meant to be a replacement for <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html" rel="noreferrer">the documentation</a>, so please read that as well! Some of the examples are taken from there.</p>
<hr />
<h3>Table of Contents</h3>
<p><sub>For ease of access.</sub></p>
<ul>
<li><p><a href="https://stackoverflow.com/a/53645883/4909087">Merging basics - basic types of joins</a> (read this first)</p>
</li>
<li><p><a href="https://stackoverflow.com/a/65167356/4909087">Index-based joins</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/65167327/4909087">Generalizing to multiple DataFrames</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/53699013/4909087">Cross join</a></p>
</li>
</ul> | <p>This post aims to give readers a primer on SQL-flavored merging with Pandas, how to use it, and when not to use it.</p>
<p>In particular, here's what this post will go through:</p>
<ul>
<li><p>The basics - types of joins (LEFT, RIGHT, OUTER, INNER)</p>
<ul>
<li>merging with different column names</li>
<li>merging with multiple columns</li>
<li>avoiding duplicate merge key column in output</li>
</ul>
</li>
</ul>
<p>What this post (and other posts by me on this thread) will not go through:</p>
<ul>
<li>Performance-related discussions and timings (for now). Mostly notable mentions of better alternatives, wherever appropriate.</li>
<li>Handling suffixes, removing extra columns, renaming outputs, and other specific use cases. There are other (read: better) posts that deal with that, so figure it out!</li>
</ul>
<blockquote>
<p><strong>Note</strong>
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.</p>
<p>Furthermore, all the DataFrames here can be copied and replicated so
you can play with them. Also, see <a href="https://stackoverflow.com/questions/31610889/how-to-copy-paste-dataframe-from-stackoverflow-into-python">this
post</a>
on how to read DataFrames from your clipboard.</p>
<p>Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from <a href="https://stackoverflow.com/a/55858991/4909087">here</a>.</p>
</blockquote>
<hr />
<hr />
<h1>Enough talk - just show me how to use <code>merge</code>!</h1>
<h3>Setup & Basics</h3>
<pre><code>np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
left
key value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right
key value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
</code></pre>
<p>For the sake of simplicity, the key column has the same name (for now).</p>
<p>An <strong>INNER JOIN</strong> is represented by</p>
<img src="https://i.stack.imgur.com/YvuOa.png" width="500"/>
<blockquote>
<p><strong>Note</strong>
This, along with the forthcoming figures all follow this convention:</p>
<ul>
<li><strong>blue</strong> indicates rows that are present in the merge result</li>
<li><strong>red</strong> indicates rows that are excluded from the result (i.e., removed)</li>
<li><strong>green</strong> indicates missing values that are replaced with <code>NaN</code>s in the result</li>
</ul>
</blockquote>
<p>To perform an INNER JOIN, call <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="noreferrer"><code>merge</code></a> on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.</p>
<pre><code>left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
</code></pre>
<p>This returns only rows from <code>left</code> and <code>right</code> which share a common key (in this example, "B" and "D).</p>
<p>A <strong>LEFT OUTER JOIN</strong>, or LEFT JOIN is represented by</p>
<img src="https://i.stack.imgur.com/BECid.png" width="500" />
<p>This can be performed by specifying <code>how='left'</code>.</p>
<pre><code>left.merge(right, on='key', how='left')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
</code></pre>
<p>Carefully note the placement of NaNs here. If you specify <code>how='left'</code>, then only keys from <code>left</code> are used, and missing data from <code>right</code> is replaced by NaN.</p>
<p>And similarly, for a <strong>RIGHT OUTER JOIN</strong>, or RIGHT JOIN which is...</p>
<img src="https://i.stack.imgur.com/8w1US.png" width="500" />
<p>...specify <code>how='right'</code>:</p>
<pre><code>left.merge(right, on='key', how='right')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
2 E NaN 0.950088
3 F NaN -0.151357
</code></pre>
<p>Here, keys from <code>right</code> are used, and missing data from <code>left</code> is replaced by NaN.</p>
<p>Finally, for the <strong>FULL OUTER JOIN</strong>, given by</p>
<img src="https://i.stack.imgur.com/euLoe.png" width="500" />
<p>specify <code>how='outer'</code>.</p>
<pre><code>left.merge(right, on='key', how='outer')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
4 E NaN 0.950088
5 F NaN -0.151357
</code></pre>
<p>This uses the keys from both frames, and NaNs are inserted for missing rows in both.</p>
<p>The documentation summarizes these various merges nicely:</p>
<p><a href="https://i.stack.imgur.com/5qDIy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5qDIy.png" alt="Enter image description here" /></a></p>
<hr />
<h3><strong>Other JOINs - LEFT-Excluding, RIGHT-Excluding, and FULL-Excluding/ANTI JOINs</strong></h3>
<p>If you need <strong>LEFT-Excluding JOINs</strong> and <strong>RIGHT-Excluding JOINs</strong> in two steps.</p>
<p>For LEFT-Excluding JOIN, represented as</p>
<img src="https://i.stack.imgur.com/bXWIV.png" width="500"/>
<p>Start by performing a LEFT OUTER JOIN and then filtering to rows coming from <code>left</code> only (excluding everything from the right),</p>
<pre><code>(left.merge(right, on='key', how='left', indicator=True)
.query('_merge == "left_only"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
</code></pre>
<p>Where,</p>
<pre><code>left.merge(right, on='key', how='left', <b>indicator=True</b>)
key value_x value_y _merge
0 A 1.764052 NaN left_only
1 B 0.400157 1.867558 both
2 C 0.978738 NaN left_only
3 D 2.240893 -0.977278 both</code></pre>
<p>And similarly, for a RIGHT-Excluding JOIN,</p>
<img src="https://i.stack.imgur.com/Z0br2.png" width="500"/>
<pre><code>(left.merge(right, on='key', how='right', <b>indicator=True</b>)
.query('_merge == "right_only"')
.drop('_merge', 1))
key value_x value_y
2 E NaN 0.950088
3 F NaN -0.151357</code></pre>
<p>Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an <strong>ANTI-JOIN</strong>),</p>
<img src="https://i.stack.imgur.com/PWMYd.png" width="500"/>
<p>You can do this in similar fashion—</p>
<pre><code>(left.merge(right, on='key', how='outer', indicator=True)
.query('_merge != "both"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
4 E NaN 0.950088
5 F NaN -0.151357
</code></pre>
<hr />
<h3><strong>Different names for key columns</strong></h3>
<p>If the key columns are named differently—for example, <code>left</code> has <code>keyLeft</code>, and <code>right</code> has <code>keyRight</code> instead of <code>key</code>—then you will have to specify <code>left_on</code> and <code>right_on</code> as arguments instead of <code>on</code>:</p>
<pre><code>left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)
left2
keyLeft value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right2
keyRight value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
</code></pre>
<pre><code>left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
keyLeft value_x keyRight value_y
0 B 0.400157 B 1.867558
1 D 2.240893 D -0.977278
</code></pre>
<hr />
<h3><strong>Avoiding duplicate key column in output</strong></h3>
<p>When merging on <code>keyLeft</code> from <code>left</code> and <code>keyRight</code> from <code>right</code>, if you only want either of the <code>keyLeft</code> or <code>keyRight</code> (but not both) in the output, you can start by setting the index as a preliminary step.</p>
<pre><code>left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
value_x keyRight value_y
0 0.400157 B 1.867558
1 2.240893 D -0.977278
</code></pre>
<p>Contrast this with the output of the command just before (that is, the output of <code>left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')</code>), you'll notice <code>keyLeft</code> is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.</p>
<hr />
<h3><strong>Merging only a single column from one of the <code>DataFrames</code></strong></h3>
<p>For example, consider</p>
<pre><code>right3 = right.assign(newcol=np.arange(len(right)))
right3
key value newcol
0 B 1.867558 0
1 D -0.977278 1
2 E 0.950088 2
3 F -0.151357 3
</code></pre>
<p>If you are required to merge only "newcol" (without any of the other columns), you can usually just subset columns before merging:</p>
<pre><code>left.merge(right3[['key', 'newcol']], on='key')
key value newcol
0 B 0.400157 0
1 D 2.240893 1
</code></pre>
<p>If you're doing a LEFT OUTER JOIN, a more performant solution would involve <code>map</code>:</p>
<pre><code># left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
</code></pre>
<p>As mentioned, this is similar to, but faster than</p>
<pre><code>left.merge(right3[['key', 'newcol']], on='key', how='left')
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
</code></pre>
<hr />
<h3><strong>Merging on multiple columns</strong></h3>
<p>To join on more than one column, specify a list for <code>on</code> (or <code>left_on</code> and <code>right_on</code>, as appropriate).</p>
<pre><code>left.merge(right, on=['key1', 'key2'] ...)
</code></pre>
<p>Or, in the event the names are different,</p>
<pre><code>left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])
</code></pre>
<hr />
<h3><strong>Other useful <code>merge*</code> operations and functions</strong></h3>
<ul>
<li><p>Merging a DataFrame with Series on index: See <a href="https://stackoverflow.com/a/40762674/4909087">this answer</a>.</p>
</li>
<li><p>Besides <code>merge</code>, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="noreferrer"><code>DataFrame.update</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="noreferrer"><code>DataFrame.combine_first</code></a> are also used in certain cases to update one DataFrame with another.</p>
</li>
<li><p><a href="http://pandas.pydata.org/pandas-docs/version/0.19.0/generated/pandas.merge_ordered.html" rel="noreferrer"><code>pd.merge_ordered</code></a> is a useful function for ordered JOINs.</p>
</li>
<li><p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_asof.html" rel="noreferrer"><code>pd.merge_asof</code></a> (read: merge_asOf) is useful for <em>approximate</em> joins.</p>
</li>
</ul>
<p><strong>This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the <a href="https://pandas.pydata.org/pandas-docs/stable/merging.html" rel="noreferrer">documentation on <code>merge</code>, <code>join</code>, and <code>concat</code></a> as well as the links to the function specifications.</strong></p>
<hr />
<hr />
<h1>Continue Reading</h1>
<p>Jump to other topics in Pandas Merging 101 to continue learning:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/53645883/4909087">Merging basics - basic types of joins</a> <sup>*</sup></p>
</li>
<li><p><a href="https://stackoverflow.com/a/65167356/4909087">Index-based joins</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/65167327/4909087">Generalizing to multiple DataFrames</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/53699013/4909087">Cross join</a></p>
</li>
</ul>
<p><sub>*You are here.</sub></p> | {
"question_id": 53645882,
"question_date": "2018-12-06T06:41:15.650Z",
"question_score": 806,
"tags": "python|pandas|join|merge|concatenation",
"answer_id": 53645883,
"answer_date": "2018-12-06T06:41:15.650Z",
"answer_score": 1123
} |
Please answer the following Stack Overflow question:
Title: How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?
<p>How do I ignore the following error message on Git pull?</p>
<blockquote>
<p>Your local changes to the following files would be overwritten by merge</p>
</blockquote>
<p>What if I <strong>want</strong> to overwrite them?</p>
<p>I've tried things like <code>git pull -f</code>, but nothing works.</p>
<p>To be clear, I only want to overwrite specific changes, not everything.</p> | <p>Alright with the help of the other two answers I've come up with a direct solution:</p>
<pre><code>git checkout HEAD^ file/to/overwrite
git pull
</code></pre> | {
"question_id": 14318234,
"question_date": "2013-01-14T12:14:43.180Z",
"question_score": 805,
"tags": "git|git-pull|git-stash",
"answer_id": 14319943,
"answer_date": "2013-01-14T14:04:31.867Z",
"answer_score": 407
} |
Please answer the following Stack Overflow question:
Title: How to convert string representation of list to a list
<p>I was wondering what the simplest way is to convert a string representation of a list like the following to a <code>list</code>:</p>
<pre><code>x = '[ "A","B","C" , " D"]'
</code></pre>
<p>Even in cases where the user puts spaces in between the commas, and spaces inside of the quotes, I need to handle that as well and convert it to:</p>
<pre><code>x = ["A", "B", "C", "D"]
</code></pre>
<p>I know I can strip spaces with <code>strip()</code> and <code>split()</code> and check for non-letter characters. But the code was getting very kludgy. Is there a quick function that I'm not aware of?</p> | <pre><code>>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']
</code></pre>
<p><a href="https://docs.python.org/library/ast.html#ast.literal_eval" rel="noreferrer"><code>ast.literal_eval</code></a>:</p>
<blockquote>
<p>With <code>ast.literal_eval</code> you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and <code>None</code>.</p>
</blockquote> | {
"question_id": 1894269,
"question_date": "2009-12-12T18:19:03.863Z",
"question_score": 805,
"tags": "python|string",
"answer_id": 1894296,
"answer_date": "2009-12-12T18:30:49.720Z",
"answer_score": 1083
} |
Please answer the following Stack Overflow question:
Title: How to test multiple variables for equality against a single value?
<p>I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:</p>
<pre><code>x = 0
y = 1
z = 3
mylist = []
if x or y or z == 0:
mylist.append("c")
if x or y or z == 1:
mylist.append("d")
if x or y or z == 2:
mylist.append("e")
if x or y or z == 3:
mylist.append("f")
</code></pre>
<p>which would return a list of:</p>
<pre><code>["c", "d", "f"]
</code></pre> | <p>You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:</p>
<pre><code>if x == 1 or y == 1 or z == 1:
</code></pre>
<p><code>x</code> and <code>y</code> are otherwise evaluated on their own (<code>False</code> if <code>0</code>, <code>True</code> otherwise).</p>
<p>You can shorten that using a containment test against <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">a tuple</a>:</p>
<pre><code>if 1 in (x, y, z):
</code></pre>
<p>or better still:</p>
<pre><code>if 1 in {x, y, z}:
</code></pre>
<p>using <a href="https://docs.python.org/3/tutorial/datastructures.html#sets" rel="noreferrer">a <code>set</code></a> to take advantage of the constant-cost membership test (i.e. <code>in</code> takes a fixed amount of time whatever the left-hand operand is).</p>
<h3>Explanation</h3>
<p>When you use <code>or</code>, python sees each side of the operator as <em>separate</em> expressions. The expression <code>x or y == 1</code> is treated as first a boolean test for <code>x</code>, then if that is False, the expression <code>y == 1</code> is tested.</p>
<p>This is due to <a href="http://docs.python.org/3/reference/expressions.html#operator-precedence" rel="noreferrer">operator precedence</a>. The <code>or</code> operator has a lower precedence than the <code>==</code> test, so the latter is evaluated <em>first</em>.</p>
<p>However, even if this were <em>not</em> the case, and the expression <code>x or y or z == 1</code> was actually interpreted as <code>(x or y or z) == 1</code> instead, this would still not do what you expect it to do.</p>
<p><code>x or y or z</code> would evaluate to the first argument that is 'truthy', e.g. not <code>False</code>, numeric 0 or empty (see <a href="http://docs.python.org/3/reference/expressions.html#boolean-operations" rel="noreferrer">boolean expressions</a> for details on what Python considers false in a boolean context).</p>
<p>So for the values <code>x = 2; y = 1; z = 0</code>, <code>x or y or z</code> would resolve to <code>2</code>, because that is the first true-like value in the arguments. Then <code>2 == 1</code> would be <code>False</code>, even though <code>y == 1</code> would be <code>True</code>.</p>
<p>The same would apply to the inverse; testing multiple values against a single variable; <code>x == 1 or 2 or 3</code> would fail for the same reasons. Use <code>x == 1 or x == 2 or x == 3</code> or <code>x in {1, 2, 3}</code>.</p> | {
"question_id": 15112125,
"question_date": "2013-02-27T12:26:23.243Z",
"question_score": 805,
"tags": "python|if-statement|comparison|match|boolean-logic",
"answer_id": 15112149,
"answer_date": "2013-02-27T12:27:40.217Z",
"answer_score": 1074
} |
Please answer the following Stack Overflow question:
Title: How to remove close button on the jQuery UI dialog?
<p>How do I remove the close button (the <strong>X</strong> in the top-right corner) on a dialog box created by jQuery UI?</p> | <p>I have found this worked in the end (note the third line overriding the open function which find the button and hides it):</p>
<pre><code>$("#div2").dialog({
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog || ui).hide();
}
});
</code></pre>
<p>To hide the close button on all dialogs you can use the following CSS too:</p>
<pre><code>.ui-dialog-titlebar-close {
visibility: hidden;
}
</code></pre> | {
"question_id": 896777,
"question_date": "2009-05-22T07:55:41.027Z",
"question_score": 805,
"tags": "jquery|html|css|jquery-ui|jquery-ui-dialog",
"answer_id": 897393,
"answer_date": "2009-05-22T11:20:08.167Z",
"answer_score": 721
} |
Please answer the following Stack Overflow question:
Title: What should main() return in C and C++?
<p>What is the correct (most efficient) way to define the <code>main()</code> function in C and C++ — <code>int main()</code> or <code>void main()</code> — and why? And how about the arguments?
If <code>int main()</code> then <code>return 1</code> or <code>return 0</code>?</p>
<hr>
<p><em>There are numerous duplicates of this question, including:</em></p>
<ul>
<li><a href="https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function/">What are the valid signatures for C's <code>main()</code> function?</a></li>
<li><a href="https://stackoverflow.com/questions/17715008/the-return-type-of-main-function/">The return type of <code>main()</code> function</a></li>
<li><a href="https://stackoverflow.com/questions/636829/difference-between-void-main-and-int-main">Difference between <code>void main()</code> and <code>int main()</code>?</a></li>
<li><a href="https://stackoverflow.com/questions/1621574/mains-signature-in-c"><code>main()</code>'s signature in C++</a></li>
<li><a href="https://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main">What is the proper declaration of <code>main()</code>?</a> — For C++, with a very good answer indeed.</li>
<li><a href="https://stackoverflow.com/questions/8692120/styles-of-main-functions-in-c">Styles of <code>main()</code> functions in C</a></li>
<li><a href="https://stackoverflow.com/questions/10915713/return-type-of-main-method-in-c">Return type of <code>main()</code> method in C</a></li>
<li><a href="https://stackoverflow.com/questions/9356510/int-main-vs-void-main-in-c"><code>int main()</code> vs <code>void main()</code> in C</a></li>
</ul>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/5191965/c-int-mainint-argc-char-argv">C++ — <code>int main(int argc, char **argv)</code></a></li>
<li><a href="https://stackoverflow.com/questions/5217395/c-int-mainint-argc-char-argv">C++ — <code>int main(int argc, char *argv[])</code></a></li>
<li><a href="https://stackoverflow.com/questions/10321435/is-char-envp-as-a-third-argument-to-main-portable">Is <code>char *envp[]</code> as a third argument to <code>main()</code> portable?</a></li>
<li><a href="https://stackoverflow.com/questions/18402853/must-the-int-main-function-return-a-value-in-all-compilers">Must the <code>int main()</code> function return a value in all compilers?</a></li>
<li><a href="https://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to-define">Why is the type of the <code>main()</code> function in C and C++ left to the user to define?</a></li>
<li><a href="https://stackoverflow.com/questions/22239/why-does-int-main-compile">Why does <code>int main(){}</code> compile?</a></li>
<li><a href="https://stackoverflow.com/questions/26470912/legal-definitions-of-main-in-c14">Legal definitions of <code>main()</code> in C++14?</a></li>
</ul> | <p>The return value for <code>main</code> indicates how the program exited. Normal exit is represented by a 0 return value from <code>main</code>. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, <code>void main()</code> is prohibited by the C++ standard and should not be used. The valid C++ <code>main</code> signatures are:</p>
<pre><code>int main()
</code></pre>
<p>and</p>
<pre><code>int main(int argc, char* argv[])
</code></pre>
<p>which is equivalent to</p>
<pre><code>int main(int argc, char** argv)
</code></pre>
<p>It is also worth noting that in C++, <code>int main()</code> can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether <code>return 0;</code> should be omitted or not is open to debate. The range of valid C program main signatures is much greater. </p>
<p>Efficiency is not an issue with the <code>main</code> function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering <code>main()</code> is allowed, but should be avoided.</p> | {
"question_id": 204476,
"question_date": "2008-10-15T12:13:48.327Z",
"question_score": 805,
"tags": "c++|c|return-value|program-entry-point|return-type",
"answer_id": 204483,
"answer_date": "2008-10-15T12:16:08.277Z",
"answer_score": 645
} |
Please answer the following Stack Overflow question:
Title: How do you select a particular option in a SELECT element in jQuery?
<p>If you know the Index, Value or Text. also if you don't have an ID for a direct reference.</p>
<p><a href="https://stackoverflow.com/questions/149573/check-if-option-is-selected-with-jquery-if-not-select-a-default#149820">This</a>, <a href="https://stackoverflow.com/questions/196684/jquery-get-select-option-text#196687">this</a> and <a href="https://stackoverflow.com/questions/47824/using-core-jquery-how-do-you-remove-all-the-options-of-a-select-box-then-add-on#47829">this</a> are all helpful answers.</p>
<p>Example markup</p>
<pre><code><div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
</code></pre> | <p>A selector to get the middle option-element by value is</p>
<pre><code>$('.selDiv option[value="SEL1"]')
</code></pre>
<p>For an index:</p>
<pre><code>$('.selDiv option:eq(1)')
</code></pre>
<p>For a known text:</p>
<pre><code>$('.selDiv option:contains("Selection 1")')
</code></pre>
<p><strong>EDIT</strong>: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:</p>
<pre><code>$('.selDiv option:eq(1)').prop('selected', true)
</code></pre>
<p>In older versions:</p>
<pre><code>$('.selDiv option:eq(1)').attr('selected', 'selected')
</code></pre>
<p><strong>EDIT2</strong>: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no <a href="http://api.jquery.com/category/selectors/" rel="noreferrer">selector</a> to match the full text, but a <a href="http://api.jquery.com/filter/" rel="noreferrer">filter</a> works:</p>
<pre><code> $('.selDiv option')
.filter(function(i, e) { return $(e).text() == "Selection 1"})
</code></pre>
<p><strong>EDIT3</strong>: Use caution with <code>$(e).text()</code> as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no <code></option></code> tag):</p>
<pre><code><select ...>
<option value="1">Selection 1
<option value="2">Selection 2
:
</select>
</code></pre>
<p>If you simply use <code>e.text</code> any extra whitespace like the trailing newline will be removed, making the comparison more robust.</p> | {
"question_id": 314636,
"question_date": "2008-11-24T16:18:19.923Z",
"question_score": 804,
"tags": "jquery",
"answer_id": 6068322,
"answer_date": "2011-05-20T06:38:10.747Z",
"answer_score": 1341
} |
Please answer the following Stack Overflow question:
Title: How to fix "ReferenceError: primordials is not defined" in Node.js
<p>I have installed Node.js modules by 'npm install', and then I tried to do <code>gulp sass-watch</code> in a command prompt. After that, I got the below response.</p>
<pre class="lang-none prettyprint-override"><code>[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
^
ReferenceError: primordials is not defined
</code></pre>
<p>I have tried this before <code>gulp sass-watch</code>:</p>
<pre class="lang-none prettyprint-override"><code>npm -g install gulp-cli
</code></pre> | <p>I hit the same error. I suspect you're using Node.js 12 and Gulp.js 3. That combination does not work: <em><a href="https://github.com/gulpjs/gulp/issues/2324" rel="noreferrer">Gulp.js 3 is broken on Node.js 12 #2324</a></em></p>
<p>A previous workaround from Jan. does not work either: <em><a href="https://github.com/gulpjs/gulp/issues/2246" rel="noreferrer">After update to Node.js 11.0.0 running Gulp.js exits with 'ReferenceError: internalBinding is not defined' #2246</a></em></p>
<p>Solution: Either upgrade to Gulp.js 4 or downgrade to an earlier version of Node.js.</p> | {
"question_id": 55921442,
"question_date": "2019-04-30T12:57:10.583Z",
"question_score": 804,
"tags": "node.js|sass|gulp|gulp-sass",
"answer_id": 55926692,
"answer_date": "2019-04-30T18:19:38.673Z",
"answer_score": 868
} |
Please answer the following Stack Overflow question:
Title: Can I use a :before or :after pseudo-element on an input field?
<p>I am trying to use the <code>:after</code> CSS pseudo-element on an <code>input</code> field, but it does not work. If I use it with a <code>span</code>, it works OK. </p>
<pre><code><style type="text/css">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>
</code></pre>
<p>This works (puts the smiley after "buu!" and before "some more")</p>
<pre><code><span class="mystyle">buuu!</span>a some more
</code></pre>
<p>This does not work - it only colors someValue in red, but there is no smiley.</p>
<pre><code><input class="mystyle" type="text" value="someValue">
</code></pre>
<p>What am I doing wrong? should I use another pseudo-selector?</p>
<p>Note: I cannot add a <code>span</code> around my <code>input</code>, because it is being generated by a third-party control.</p> | <p><code>:after</code> and <code>:before</code> are not supported in Internet Explorer 7 and under, on any elements.</p>
<p>It's also not meant to be used on replaced elements such as <strong>form elements</strong> (inputs) and <strong>image elements</strong>.</p>
<p>In other words it's <strong>impossible</strong> with pure CSS.</p>
<p>However if using <a href="http://jquery.com" rel="noreferrer">jquery</a> you can use</p>
<pre><code>$(".mystyle").after("add your smiley here");
</code></pre>
<p><a href="http://api.jquery.com/after/" rel="noreferrer">API docs on .after</a></p>
<p>To append your content with javascript. This will work across all browsers.</p> | {
"question_id": 2587669,
"question_date": "2010-04-06T19:28:08.357Z",
"question_score": 804,
"tags": "html|css|pseudo-element|css-content",
"answer_id": 2591460,
"answer_date": "2010-04-07T10:01:42.930Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: setTimeout or setInterval?
<p>As far as I can tell, these two pieces of javascript behave the same way:</p>
<p><strong>Option A:</strong></p>
<pre><code>function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
</code></pre>
<p><strong>Option B:</strong></p>
<pre><code>function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
</code></pre>
<p>Is there any difference between using <a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout" rel="noreferrer">setTimeout</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/setInterval" rel="noreferrer">setInterval</a>?</p> | <p>They essentially try to do the same thing, but the <code>setInterval</code> approach will be more accurate than the <code>setTimeout</code> approach, since <code>setTimeout</code> waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).</p>
<p>Although one might think that <code>setInterval</code> will execute <strong>exactly</strong> every 1000ms, it is important to note that <code>setInterval</code> will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.</p>
<p>In <a href="http://jsfiddle.net/GustvandeWal/295jqqqb/" rel="noreferrer">this Fiddle</a>, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.</p>
<p>The delay is almost always negligible, but if you're programming something really precise, you should go for a <em>self-adjusting timer</em> (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created) </p> | {
"question_id": 729921,
"question_date": "2009-04-08T13:11:01.100Z",
"question_score": 804,
"tags": "javascript|setinterval",
"answer_id": 729943,
"answer_date": "2009-04-08T13:14:46.583Z",
"answer_score": 701
} |
Please answer the following Stack Overflow question:
Title: How to put a border around an Android TextView?
<p>Is it possible to draw a border around an Android <code>TextView</code>?</p> | <p>You can set a shape drawable (a rectangle) as background for the view.</p>
<pre><code><TextView android:text="Some text" android:background="@drawable/back"/>
</code></pre>
<p>And rectangle drawable back.xml (put into res/drawable folder):</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
</code></pre>
<p>You can use <code>@android:color/transparent</code> for the solid color to have a transparent background.
You can also use padding to separate the text from the border.
for more information see: <a href="http://developer.android.com/guide/topics/resources/drawable-resource.html" rel="noreferrer">http://developer.android.com/guide/topics/resources/drawable-resource.html</a></p> | {
"question_id": 3496269,
"question_date": "2010-08-16T18:50:27.807Z",
"question_score": 803,
"tags": "android|android-layout|textview|border|android-shapedrawable",
"answer_id": 3496310,
"answer_date": "2010-08-16T18:56:28.277Z",
"answer_score": 1388
} |
Please answer the following Stack Overflow question:
Title: Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23
<p>I've always programmed Android with Eclipse and decided to start migrating to <a href="https://en.wikipedia.org/wiki/Android_Studio" rel="noreferrer">Android Studio</a>. I decided to use the same SDK I already had for Eclipse, then:</p>
<ul>
<li>Started a new project</li>
<li>Set minimum SDK 4.0 (API Level 14)</li>
<li>Choose Blank Activity option</li>
<li>Used Default names for Activity Name and Layout Name</li>
<li>Hit Finish</li>
</ul>
<p>After a few seconds Gradle finishes the build, and it throws me two errors with the following messages in file Teste4\app\build\intermediates/exploded-aar\com.android.support\appcompat-v7\23.0.0\res\values-v23\values-v23.xml:</p>
<blockquote>
<p>Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'. <br/>
<br/>
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'. <br/></p>
</blockquote>
<p>Under <em>File -> Project Structure -> Modules: app (left column) -> Properties tab</em>, I have the following versions set up:</p>
<ul>
<li>"Compile Sdk Version": Android 5.1 (API Level 22)</li>
<li>"Build Tools Version": 23.0.2</li>
</ul>
<p>What should I do in order to fix this?</p>
<p>I already tried what was suggested in Stack Overflow question <em><a href="https://stackoverflow.com/questions/26431676">appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'</a></em>, but it didn't work.</p> | <p>Your compile SDK version must match the support library's major version.</p>
<p>Since you are using version 23 of the support library, you need to compile against version 23 of the Android SDK.</p>
<p>Alternatively you can continue compiling against version 22 of the Android SDK by switching to the latest support library v22.</p> | {
"question_id": 32075498,
"question_date": "2015-08-18T14:39:53.383Z",
"question_score": 803,
"tags": "android|android-studio|gradle",
"answer_id": 32075678,
"answer_date": "2015-08-18T14:47:15.727Z",
"answer_score": 1154
} |
Please answer the following Stack Overflow question:
Title: Adding a method to an existing object instance
<p>I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python. </p>
<p>I understand that it's not always good to do so. But how might one do this?</p> | <p>In Python, there is a difference between functions and bound methods.</p>
<pre><code>>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
</code></pre>
<p>Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p>
<p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p>
<pre><code>>>> def fooFighters( self ):
... print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters
</code></pre>
<p>Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):</p>
<pre><code>>>> a.fooFighters()
fooFighters
</code></pre>
<p>The problem comes when you want to attach a method to a single instance:</p>
<pre><code>>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)
</code></pre>
<p>The function is not automatically bound when it's attached directly to an instance:</p>
<pre><code>>>> a.barFighters
<function barFighters at 0x00A98EF0>
</code></pre>
<p>To bind it, we can use the <a href="https://docs.python.org/3/library/types.html#types.MethodType" rel="noreferrer">MethodType function in the types module</a>:</p>
<pre><code>>>> import types
>>> a.barFighters = types.MethodType( barFighters, a )
>>> a.barFighters
<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters
</code></pre>
<p>This time other instances of the class have not been affected:</p>
<pre><code>>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'
</code></pre>
<p>More information can be found by reading about <a href="https://docs.python.org/3/howto/descriptor.html" rel="noreferrer">descriptors</a> and <a href="https://web.archive.org/web/20090124004817/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html" rel="noreferrer">metaclass</a> <a href="http://www.gnosis.cx/publish/programming/metaclass_2.html" rel="noreferrer">programming</a>.</p> | {
"question_id": 972,
"question_date": "2008-08-04T02:17:51.780Z",
"question_score": 803,
"tags": "python|oop|methods|monkeypatching",
"answer_id": 2982,
"answer_date": "2008-08-06T00:33:35.063Z",
"answer_score": 1111
} |
Please answer the following Stack Overflow question:
Title: How can I compare numbers in Bash?
<p>I'm unable to get numeric comparisons working:</p>
<pre class="lang-sh prettyprint-override"><code>echo "enter two numbers";
read a b;
echo "a=$a";
echo "b=$b";
if [ $a \> $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
</code></pre>
<p>The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.</p>
<p>How can I convert the numbers into a type to do a true comparison?</p> | <p>In Bash, you should do your check in an <a href="http://mywiki.wooledge.org/ArithmeticExpression" rel="noreferrer">arithmetic context</a>:</p>
<pre><code>if (( a > b )); then
...
fi
</code></pre>
<p>For POSIX shells that don't support <code>(())</code>, you can use <code>-lt</code> and <code>-gt</code>.</p>
<pre><code>if [ "$a" -gt "$b" ]; then
...
fi
</code></pre>
<p>You can get a full list of comparison operators with <code>help test</code> or <code>man test</code>.</p> | {
"question_id": 18668556,
"question_date": "2013-09-07T00:44:38.097Z",
"question_score": 802,
"tags": "bash|shell|numeric",
"answer_id": 18668580,
"answer_date": "2013-09-07T00:48:12.037Z",
"answer_score": 1223
} |
Please answer the following Stack Overflow question:
Title: What is a segmentation fault?
<p>What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?</p> | <p>Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C++.</p>
<p>There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer:</p>
<pre><code>int *p = NULL;
*p = 1;
</code></pre>
<p>Another segfault happens when you try to write to a portion of memory that was marked as read-only:</p>
<pre><code>char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault
</code></pre>
<p>Dangling pointer points to a thing that does not exist anymore, like here:</p>
<pre><code>char *p = NULL;
{
char c;
p = &c;
}
// Now p is dangling
</code></pre>
<p>The pointer <code>p</code> dangles because it points to the character variable <code>c</code> that ceased to exist after the block ended. And when you try to dereference dangling pointer (like <code>*p='A'</code>), you would probably get a segfault.</p> | {
"question_id": 2346806,
"question_date": "2010-02-27T09:23:14.947Z",
"question_score": 802,
"tags": "c++|c|segmentation-fault",
"answer_id": 2346849,
"answer_date": "2010-02-27T09:36:21.843Z",
"answer_score": 882
} |
Please answer the following Stack Overflow question:
Title: C# List<string> to string with delimiter
<p>Is there a function in C# to quickly convert some collection to string and separate values with delimiter?</p>
<p>For example:</p>
<p><code>List<string> names</code> --> <code>string names_together = "John, Anna, Monica"</code></p> | <p>You can use <a href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx" rel="noreferrer"><code>String.Join</code></a>. If you have a <code>List<string></code> then you can call <a href="http://msdn.microsoft.com/en-us/library/x303t819.aspx" rel="noreferrer"><code>ToArray</code></a> first: </p>
<pre><code>List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());
</code></pre>
<p>In .NET 4 you don't need the <code>ToArray</code> anymore, since there is an overload of <code>String.Join</code> that takes an <code>IEnumerable<string></code>. </p>
<p><strong>Results:</strong></p>
<hr>
<blockquote>
<p>John, Anna, Monica</p>
</blockquote> | {
"question_id": 3575029,
"question_date": "2010-08-26T12:29:06.827Z",
"question_score": 802,
"tags": "c#|string|list|delimiter",
"answer_id": 3575036,
"answer_date": "2010-08-26T12:30:38.620Z",
"answer_score": 1552
} |
Please answer the following Stack Overflow question:
Title: Static variables in JavaScript
<p>How can I create static variables in Javascript?</p> | <p>If you come from a class-based, statically typed object-oriented language <em>(like Java, C++ or C#)</em> I assume that you are trying to create a variable or method associated to a "type" but not to an instance.</p>
<p>An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic OO JavaScript:</p>
<pre><code>function MyClass () { // constructor function
var privateVariable = "foo"; // Private variable
this.publicVariable = "bar"; // Public variable
this.privilegedMethod = function () { // Public Method
alert(privateVariable);
};
}
// Instance method will be available to all instances but only load once in memory
MyClass.prototype.publicMethod = function () {
alert(this.publicVariable);
};
// Static variable shared by all instances
MyClass.staticProperty = "baz";
var myInstance = new MyClass();
</code></pre>
<p><code>staticProperty</code> is defined in the MyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">first-class objects</a>, so being an object, you can assign properties to a function.</p>
<p><strong>UPDATE:</strong> ES6 introduced the ability to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes" rel="noreferrer">declare classes</a> through the <code>class</code> keyword. It is syntax sugar over the existing prototype-based inheritance.</p>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static" rel="noreferrer"><code>static</code> keyword</a> allows you to easily define static properties or methods in a class.</p>
<p>Let's see the above example implemented with ES6 classes:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class MyClass {
// class constructor, equivalent to
// the function body of a constructor
constructor() {
const privateVariable = 'private value'; // Private variable at the constructor scope
this.publicVariable = 'public value'; // Public property
this.privilegedMethod = function() {
// Public Method with access to the constructor scope variables
console.log(privateVariable);
};
}
// Prototype methods:
publicMethod() {
console.log(this.publicVariable);
}
// Static properties shared by all instances
static staticProperty = 'static value';
static staticMethod() {
console.log(this.staticProperty);
}
}
// We can add properties to the class prototype
MyClass.prototype.additionalMethod = function() {
console.log(this.publicVariable);
};
var myInstance = new MyClass();
myInstance.publicMethod(); // "public value"
myInstance.additionalMethod(); // "public value"
myInstance.privilegedMethod(); // "private value"
MyClass.staticMethod(); // "static value"</code></pre>
</div>
</div>
</p> | {
"question_id": 1535631,
"question_date": "2009-10-08T04:31:25.337Z",
"question_score": 802,
"tags": "javascript|variables|static|closures",
"answer_id": 1535687,
"answer_date": "2009-10-08T04:49:16.703Z",
"answer_score": 947
} |
Please answer the following Stack Overflow question:
Title: All com.android.support libraries must use the exact same version specification
<p>After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.</p>
<blockquote>
<p>All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/trji5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/trji5.png" alt="enter image description here"></a></p>
<p>my gradle:</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:support-v4:25.1.1'
compile 'com.android.support:design:25.1.1'
compile 'com.android.support:recyclerview-v7:25.1.1'
compile 'com.android.support:cardview-v7:25.1.1'
compile 'com.google.android.gms:play-services-maps:10.2.0'
compile 'com.google.android.gms:play-services:10.2.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.blankj:utilcode:1.3.6'
compile 'com.orhanobut:logger:1.15'
compile 'com.facebook.stetho:stetho:1.4.2'
provided 'com.google.auto.value:auto-value:1.2'
annotationProcessor 'com.google.auto.value:auto-value:1.2'
annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'
compile 'com.mikepenz:iconics-core:2.8.2@aar'
compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
compile 'com.github.GrenderG:Toasty:1.1.1'
compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
compile 'com.github.MAXDeliveryNG:slideview:1.0.0'
compile 'com.facebook.fresco:fresco:1.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.maps.android:android-maps-utils:0.4.4'
compile 'com.github.jd-alexander:library:1.1.0'
}
</code></pre> | <p>You can solve this with one of the following solutions:</p>
<h2>Update:</h2>
<p>As of Android studio 3.0, it becomes much easier as it now shows a more helpful hint, so we only need to follow this hint.<br>
for example:
<img src="https://i.stack.imgur.com/BObtK.png" alt="1]"></p>
<blockquote>
<p>All com.android.support libraries must use the exact same version
specification (mixing versions can lead to runtime crashes). Found
versions 27.0.2, 26.1.0. Examples include
com.android.support:animated-vector-drawable:27.0.2 and
com.android.support:customtabs:26.1.0</p>
<p>there are some combinations of libraries, or tools and libraries, that
are incompatible, or can lead to bugs. One such incompatibility is
compiling with a version of the Android support libraries that is not
the latest version (or in particular, a version lower than your
targetSdkVersion.)</p>
</blockquote>
<p><strong>Solution:</strong><br>
Add explicitly the library with the old version but with a new version number.<br>
in my case <code>com.android.support:customtabs:26.1.0</code> so I need to add: </p>
<pre><code>implementation "com.android.support:customtabs:27.0.2"
</code></pre>
<p>ie: Take the library from the second item, and implement it with the version number from the first.</p>
<p>Note: don't forget to press sync now so gradle can rebuild the dependency graph and see if there are any more conflicts.</p>
<p><strong>Explanation:</strong><br>
you may be confused by the error message as don't use <code>customtabs</code> so how I have a conflict!!<br>
well.. you didn't use it directly but one of your libraries uses an old version of <code>customtabs</code> internally, so you need to ask for it directly. </p>
<p>if you curious to know which of your libraries is responsible for the old version and maybe ask the author to update his lib, Run a Gradle dependency report, see the old answer to know how.</p>
<p>Note this </p>
<hr>
<h2>Old answer:</h2>
<p>inspired by <a href="https://stackoverflow.com/a/42582204/1843331">CommonsWare answer</a>:</p>
<p>Run a Gradle dependency report to see what your full tree of
dependencies is.</p>
<p>From there, you will see which one of your libraries are asking for a different version of the Android Support libraries.
For whatever it is asking for, you can ask for it directly with the
25.2.0 version or use Gradle's other conflict resolution approaches to get the same versions.</p>
<hr>
<h2>Update:</h2>
<p>As of gradle plugin version: 3.0 <code>compile</code> has been replaced by <code>implementation</code> or <code>api</code> see <a href="https://stackoverflow.com/a/44493379/3998402">this answer</a> for the difference.</p>
<p>hence use instead:</p>
<pre><code>./gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
</code></pre>
<p>or for windows cmd: </p>
<pre><code>gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
</code></pre>
<p>and search for the conflicted version.</p>
<p>For me, the error disappeared after removing <code>com.google.android.gms:play-services:10.2.0</code></p>
<p>And only include <code>com.google.android.gms:play-services-location:10.2.0</code> and <code>com.google.android.gms:play-services-maps:10.2.0</code> as they are the only two play services that I use.</p>
<p>I think the <code>gms:play-services</code> depend on some old components of the support library, so we need to add them explicitly ourselves.</p>
<hr>
<p>for AS 3.0 an older.</p>
<p>Run:</p>
<pre><code>./gradlew -q dependencies <module-name>:dependencies --configuration implementation
</code></pre>
<p>Example:</p>
<pre><code>./gradlew -q dependencies app:dependencies --configuration implementation
</code></pre>
<hr>
<p>if someone knows a better way in the new gradle plugin please let me know.</p> | {
"question_id": 42374151,
"question_date": "2017-02-21T17:35:02.123Z",
"question_score": 802,
"tags": "android|build.gradle",
"answer_id": 42374426,
"answer_date": "2017-02-21T17:49:38.770Z",
"answer_score": 912
} |
Please answer the following Stack Overflow question:
Title: How do I update/upgrade pip itself from inside my virtual environment?
<p>I'm able to update pip-managed packages, but how do I update pip itself? According to <code>pip --version</code>, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version. </p>
<p>What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tried <code>pip update</code> and <code>pip update pip</code> with no success.</p> | <p><code>pip</code> is just a <a href="https://pypi.python.org/pypi/pip">PyPI package</a> like any other; you could use it to upgrade itself the same way you would upgrade any package:</p>
<pre><code>pip install --upgrade pip
</code></pre>
<p>On Windows the <a href="https://pip.pypa.io/en/stable/installing/#upgrading-pip">recommended command</a> is:</p>
<pre><code>python -m pip install --upgrade pip
</code></pre> | {
"question_id": 15221473,
"question_date": "2013-03-05T10:29:18.290Z",
"question_score": 801,
"tags": "python|upgrade|virtualenv|pip|package-managers",
"answer_id": 15223296,
"answer_date": "2013-03-05T12:03:10.687Z",
"answer_score": 1371
} |
Please answer the following Stack Overflow question:
Title: How to get the type of T from a member of a generic class or method
<p>Let's say I have a generic member in a class or method, like so:</p>
<pre><code>public class Foo<T>
{
public List<T> Bar { get; set; }
public void Baz()
{
// get type of T
}
}
</code></pre>
<p>When I instantiate the class, the <code>T</code> becomes <code>MyTypeObject1</code>, so the class has a generic list property: <code>List<MyTypeObject1></code>. The same applies to a generic method in a non-generic class:</p>
<pre><code>public class Foo
{
public void Bar<T>()
{
var baz = new List<T>();
// get type of T
}
}
</code></pre>
<p>I would like to know what type of objects the list of my class contains. So what type of <code>T</code> does the list property called <code>Bar</code> or the local variable <code>baz</code> contain?</p>
<p>I cannot do <code>Bar[0].GetType()</code>, because the list might contain zero elements. How can I do it?</p> | <p>If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:</p>
<pre><code>Type typeParameterType = typeof(T);
</code></pre>
<p>If you are in the lucky situation of having <code>object</code> as a type parameter, see <a href="https://stackoverflow.com/a/557349/3649914">Marc's answer</a>.</p> | {
"question_id": 557340,
"question_date": "2009-02-17T15:24:36.940Z",
"question_score": 801,
"tags": "c#|.net|generics",
"answer_id": 557355,
"answer_date": "2009-02-17T15:27:08.433Z",
"answer_score": 842
} |
Please answer the following Stack Overflow question:
Title: How to convert an Array to a Set in Java
<p>I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:</p>
<pre><code>java.util.Arrays.asList(Object[] a);
</code></pre>
<p>Any ideas?</p> | <p>Like this:</p>
<pre><code>Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
</code></pre>
<p>In Java 9+, if unmodifiable set is ok:</p>
<pre><code>Set<T> mySet = Set.of(someArray);
</code></pre>
<p>In Java 10+, the generic type parameter can be inferred from the arrays component type:</p>
<pre><code>var mySet = Set.of(someArray);
</code></pre>
<p><strong>Be careful</strong></p>
<blockquote>
<p>Set.of throws IllegalArgumentException - if there are any duplicate
elements in someArray.
See more details: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)" rel="noreferrer">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E...)</a></p>
</blockquote> | {
"question_id": 3064423,
"question_date": "2010-06-17T18:23:56.460Z",
"question_score": 801,
"tags": "java|collections|arrays|set",
"answer_id": 3064447,
"answer_date": "2010-06-17T18:27:37.670Z",
"answer_score": 1352
} |
Please answer the following Stack Overflow question:
Title: How to change line-ending settings
<p>Is there a file or menu that will let me change the settings on how to deal with line endings?</p>
<p>I read there are 3 options:</p>
<ol>
<li><p><strong>Checkout Windows-style, commit Unix-style</strong></p>
<p>Git will convert LF to CRLF when checking out text files. When
committing text files, CRLF will be converted to LF. For
cross-platform projects, this is the recommended setting on Windows
("core.autocrlf" is set to "true")</p></li>
<li><p><strong>Checkout as-is, commit Unix-style</strong></p>
<p>Git will not perform any conversion when checking out text files.
When committing text files, CRLF will be converted to LF. For
cross-platform projects this is the recommended setting on Unix
("core.autocrlf" is set to "input").</p></li>
<li><p><strong>Checkout as-is, commit as-is</strong></p>
<p>Git will not perform any conversions when checking out or committing
text files. Choosing this option is not recommended for cross-platform
projects ("core.autocrlf" is set to "false")</p></li>
</ol> | <p>The normal way to control this is with <code>git config</code></p>
<p>For example</p>
<pre class="lang-sh prettyprint-override"><code>git config --global core.autocrlf true
</code></pre>
<p>For details, scroll down in <a href="http://git-scm.com/book/en/Customizing-Git-Git-Configuration#_formatting_and_whitespace" rel="noreferrer">this link to Pro Git</a> to the section named "core.autocrlf"</p>
<hr>
<p>If you want to know what <em>file</em> this is saved in, you can run the command:</p>
<pre class="lang-sh prettyprint-override"><code>git config --global --edit
</code></pre>
<p>and the git global config file should open in a text editor, and you can see where that file was loaded from.</p> | {
"question_id": 10418975,
"question_date": "2012-05-02T17:45:07.460Z",
"question_score": 801,
"tags": "git|msysgit",
"answer_id": 10419350,
"answer_date": "2012-05-02T18:12:26.190Z",
"answer_score": 707
} |
Please answer the following Stack Overflow question:
Title: Duplicating a MySQL table, indices, and data
<p>How do I copy or clone or duplicate the data, structure,
and indices of a MySQL table to a new one?</p>
<p>This is what I've found so far.</p>
<p>This will copy the data and the structure,
but not the indices:</p>
<pre><code>create table {new_table} select * from {old_table};
</code></pre>
<p>This will copy the structure and indices,
but not the data:</p>
<pre><code>create table {new_table} like {old_table};
</code></pre> | <p>To copy with indexes and triggers do these 2 queries:</p>
<pre><code>CREATE TABLE new_table LIKE old_table;
INSERT INTO new_table SELECT * FROM old_table;
</code></pre>
<p>To copy just structure and data use this one:</p>
<pre><code>CREATE TABLE new_table AS SELECT * FROM old_table;
</code></pre>
<p>I've asked this before:</p>
<p><a href="https://stackoverflow.com/questions/2415855/run-mysql-create-table-by-select-another-and-copied-the-indexes-automatically">Copy a MySQL table including indexes</a></p> | {
"question_id": 3280006,
"question_date": "2010-07-19T09:53:57.910Z",
"question_score": 801,
"tags": "mysql",
"answer_id": 3280042,
"answer_date": "2010-07-19T09:59:43.183Z",
"answer_score": 1767
} |
Please answer the following Stack Overflow question:
Title: Convert DOS line endings to Linux line endings in Vim
<p>If I open files I created in Windows, the lines all end with <code>^M</code>.
How do I delete these characters all at once?</p> | <p><a href="https://sourceforge.net/projects/dos2unix" rel="noreferrer">dos2unix</a> is a commandline utility that will do this, or <code>:%s/^M//g</code> will if you use <kbd>Ctrl</kbd>-<kbd>v</kbd> <kbd>Ctrl</kbd>-<kbd>m</kbd> to input the ^M, or you can <code>:set ff=unix</code> and Vim will do it for you.</p>
<p>There is documentation on the <a href="http://www.vim.org/htmldoc/options.html#%27fileformat%27" rel="noreferrer">fileformat</a> setting, and the Vim wiki has a comprehensive <a href="http://vim.wikia.com/wiki/Change_end-of-line_format_for_dos-mac-unix" rel="noreferrer">page on line ending conversions</a>.</p>
<p>Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do <code>:set ff=dos</code>, so Vim will know it's a DOS file and use DOS conventions for line endings.</p> | {
"question_id": 82726,
"question_date": "2008-09-17T12:44:26.010Z",
"question_score": 800,
"tags": "linux|vim|file|editor|dos2unix",
"answer_id": 82743,
"answer_date": "2008-09-17T12:45:38.567Z",
"answer_score": 1179
} |
Please answer the following Stack Overflow question:
Title: Is it possible to move/rename files in Git and maintain their history?
<p>I would like to rename/move a project subtree in Git moving it from</p>
<pre><code>/project/xyz
</code></pre>
<p>to </p>
<pre><code>/components/xyz
</code></pre>
<p>If I use a plain <code>git mv project components</code>, then all the commit history for the <code>xyz project</code> gets lost. Is there a way to move this such that the history is maintained?</p> | <p>Git detects renames rather than persisting the operation with the commit, so whether you use <code>git mv</code> or <code>mv</code> doesn't matter.</p>
<p>The <code>log</code> command takes a <a href="http://git-scm.com/docs/git-log#Documentation/git-log.txt---follow" rel="noreferrer"><code>--follow</code></a> argument that continues history before a rename operation, i.e., it searches for similar content using heuristics.</p>
<p>To lookup the full history, use the following command:</p>
<pre><code>git log --follow ./path/to/file
</code></pre> | {
"question_id": 2314652,
"question_date": "2010-02-22T22:11:07.067Z",
"question_score": 800,
"tags": "git|rename|mv",
"answer_id": 2314757,
"answer_date": "2010-02-22T22:26:14.917Z",
"answer_score": 723
} |
Please answer the following Stack Overflow question:
Title: How do I implement basic "Long Polling"?
<p>I can find lots of information on how Long Polling works (For example, <a href="http://jfarcand.wordpress.com/2007/05/15/new-adventures-in-comet-polling-long-polling-or-http-streaming-with-ajax-which-one-to-choose/" rel="noreferrer">this</a>, and <a href="http://en.wikipedia.org/wiki/Comet_(programming)#Ajax_with_long_polling" rel="noreferrer">this</a>), but no <em>simple</em> examples of how to implement this in code.</p>
<p>All I can find is <a href="http://code.google.com/p/cometd/" rel="noreferrer">cometd</a>, which relies on the Dojo JS framework, and a fairly complex server system..</p>
<p>Basically, how would I use Apache to serve the requests, and how would I write a simple script (say, in PHP) which would "long-poll" the server for new messages?</p>
<p>The example doesn't have to be scaleable, secure or complete, it just needs to work!</p> | <p>It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).</p>
<p>Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)</p>
<p><code>msgsrv.php</code></p>
<pre class="lang-php prettyprint-override"><code><?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
</code></pre>
<p>Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's <a href="http://twistedmatrix.com/trac/" rel="noreferrer">twisted</a>, which does not rely on one thread per request. <a href="http://cometdproject.dojotoolkit.org/" rel="noreferrer">cometD</a> is an popular one (which is available in several languages), and <a href="http://www.tornadoweb.org/" rel="noreferrer">Tornado</a> is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)</p>
<p>Then, in Javascript, you request the above file (<code>msg_srv.php</code>), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)</p>
<p>What follows is an example of such a page.. When the page is loaded, it sends the initial request for the <code>msgsrv.php</code> file.. If it succeeds, we append the message to the <code>#messages</code> div, then after 1 second we call the waitForMsg function again, which triggers the wait.</p>
<p>The 1 second <code>setTimeout()</code> is a really basic rate-limiter, it works fine without this, but if <code>msgsrv.php</code> <em>always</em> returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.</p>
<p>If the page errors, it appends the error to the <code>#messages</code> div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)</p>
<p>The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required</p>
<p>Anyway, the <code>long_poller.htm</code> code, using the jQuery framework:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
<title>BargePoller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{ background:#000;color:#fff;font-size:.9em; }
.msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
.old{ background-color:#246499;}
.new{ background-color:#3B9957;}
.error{ background-color:#992E36;}
</style>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "msgsrv.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
waitForMsg, /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="messages">
<div class="msg old">
BargePoll message requester!
</div>
</div>
</body>
</html>
</code></pre> | {
"question_id": 333664,
"question_date": "2008-12-02T11:14:47.553Z",
"question_score": 800,
"tags": "php|http|comet",
"answer_id": 333884,
"answer_date": "2008-12-02T13:15:17.123Z",
"answer_score": 521
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.