input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Difference between CR LF, LF and CR line break types? <p>I'd like to know the difference (with examples if possible) between CR LF (Windows), LF (Unix) and CR (Macintosh) line break types. </p>
<p>It's really just about which bytes are stored in a file. <code>CR</code> is a bytecode for carriage return (from the days of typewriters) and <code>LF</code> similarly, for line feed. It just refers to the bytes that are placed as end-of-line markers.</p> <p>Way more information, as always, on <a href="http://en.wikipedia.org/wiki/Newline" rel="noreferrer">wikipedia</a>.</p>
{ "question_id": 1552749, "question_date": "2009-10-12T04:47:26.617Z", "question_score": 1020, "tags": "line-breaks", "answer_id": 1552770, "answer_date": "2009-10-12T04:52:29.337Z", "answer_score": 454 }
Please answer the following Stack Overflow question: Title: Find which version of package is installed with pip <p>Using pip, is it possible to figure out which version of a package is currently installed?</p> <p>I know about <code>pip install XYZ --upgrade</code> but I am wondering if there is anything like <code>pip info XYZ</code>. If not what would be the best way to tell what version I am currently using.</p>
<p>As of <a href="https://github.com/pypa/pip/blob/1.3/CHANGES.txt#L54" rel="noreferrer">pip 1.3</a>, there is a <code>pip show</code> command.</p> <pre><code>$ pip show Jinja2 --- Name: Jinja2 Version: 2.7.3 Location: /path/to/virtualenv/lib/python2.7/site-packages Requires: markupsafe </code></pre> <p>In older versions, <code>pip freeze</code> and <code>grep</code> should do the job nicely.</p> <pre><code>$ pip freeze | grep Jinja2 Jinja2==2.7.3 </code></pre>
{ "question_id": 10214827, "question_date": "2012-04-18T17:37:20.470Z", "question_score": 1020, "tags": "python|pip", "answer_id": 10215100, "answer_date": "2012-04-18T17:53:51.653Z", "answer_score": 1450 }
Please answer the following Stack Overflow question: Title: How do I type hint a method with the type of the enclosing class? <p>I have the following code in Python 3:</p> <pre><code>class Position: def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other: Position) -&gt; Position: return Position(self.x + other.x, self.y + other.y) </code></pre> <p>But my editor (PyCharm) says that the reference <code>Position</code> can not be resolved (in the <code>__add__</code> method). How should I specify that I expect the return type to be of type <code>Position</code>?</p> <p>Edit: I think this is actually a PyCharm issue. It actually uses the information in its warnings, and code completion.</p> <p><img src="https://i.imgur.com/yjjCWw3.png" alt="" /></p> <p>But correct me if I'm wrong, and need to use some other syntax.</p>
<p><strong>TL;DR</strong>: As of today (2019), in Python 3.7+ you can turn this feature on using a &quot;future&quot; statement, <code>from __future__ import annotations</code>.</p> <p>(The behaviour enabled by <code>from __future__ import annotations</code> <em>might</em> become the default in future versions of Python, and <a href="https://www.python.org/dev/peps/pep-0563/" rel="noreferrer">was going</a> to be made the default in Python 3.10. However, the change in 3.10 <a href="https://mail.python.org/archives/list/[email protected]/thread/CLVXXPQ2T2LQ5MP2Y53VVQFCXYWQJHKZ/" rel="noreferrer">was reverted</a> at the last minute, and now may not happen at all.)</p> <p>In Python 3.6 or below, you should use a string.</p> <hr /> <p>I guess you got this exception:</p> <pre><code>NameError: name 'Position' is not defined </code></pre> <p>This is because <code>Position</code> must be defined before you can use it in an annotation, unless you are using Python with <a href="https://www.python.org/dev/peps/pep-0563/" rel="noreferrer">PEP 563</a> changes enabled.</p> <h2>Python 3.7+: <code>from __future__ import annotations</code></h2> <p>Python 3.7 introduces <a href="https://www.python.org/dev/peps/pep-0563/" rel="noreferrer">PEP 563: postponed evaluation of annotations</a>. A module that uses the future statement <code>from __future__ import annotations</code> will store annotations as strings automatically:</p> <pre><code>from __future__ import annotations class Position: def __add__(self, other: Position) -&gt; Position: ... </code></pre> <p>This had been scheduled to become the default in Python 3.10, but this change has now been postponed. Since Python still is a dynamically typed language so no type-checking is done at runtime, typing annotations should have no performance impact, right? Wrong! Before Python 3.7, the typing module used to be <a href="https://www.python.org/dev/peps/pep-0560/#performance" rel="noreferrer">one of the slowest python modules in core</a> so <strong>for code that involves importing the <code>typing</code> module, you will see an <a href="https://docs.python.org/3.7/whatsnew/3.7.html#pep-560-core-support-for-typing-module-and-generic-types" rel="noreferrer">up to 7 times increase in performance</a> when you upgrade to 3.7.</strong></p> <h2>Python &lt;3.7: use a string</h2> <p><a href="https://www.python.org/dev/peps/pep-0484/#forward-references" rel="noreferrer">According to PEP 484</a>, you should use a string instead of the class itself:</p> <pre><code>class Position: ... def __add__(self, other: 'Position') -&gt; 'Position': ... </code></pre> <p>If you use the Django framework, this may be familiar, as Django models also use strings for forward references (foreign key definitions where the foreign model is <code>self</code> or is not declared yet). This should work with Pycharm and other tools.</p> <h2>Sources</h2> <p>The relevant parts of PEP 484 and PEP 563, to spare you the trip:</p> <blockquote> <h1><a href="https://www.python.org/dev/peps/pep-0484/#forward-references" rel="noreferrer">Forward references</a></h1> <p>When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.</p> <p>A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. For example, the following code (the start of a simple binary tree implementation) does not work:</p> <pre><code>class Tree: def __init__(self, left: Tree, right: Tree): self.left = left self.right = right </code></pre> <p>To address this, we write:</p> <pre><code>class Tree: def __init__(self, left: 'Tree', right: 'Tree'): self.left = left self.right = right </code></pre> <p>The string literal should contain a valid Python expression (i.e., compile(lit, '', 'eval') should be a valid code object) and it should evaluate without errors once the module has been fully loaded. The local and global namespace in which it is evaluated should be the same namespaces in which default arguments to the same function would be evaluated.</p> </blockquote> <p>and PEP 563:</p> <blockquote> <h1><a href="https://www.python.org/dev/peps/pep-0563/#implementation" rel="noreferrer">Implementation</a></h1> <p>In Python 3.10, function and variable annotations will no longer be evaluated at definition time. Instead, a string form will be preserved in the respective <code>__annotations__</code> dictionary. Static type checkers will see no difference in behavior, whereas tools using annotations at runtime will have to perform postponed evaluation.</p> <p>...</p> <h2><a href="https://www.python.org/dev/peps/pep-0563/#enabling-the-future-behavior-in-python-3-7" rel="noreferrer">Enabling the future behavior in Python 3.7</a></h2> <p>The functionality described above can be enabled starting from Python 3.7 using the following special import:</p> <pre><code>from __future__ import annotations </code></pre> </blockquote> <h2>Things that you may be tempted to do instead</h2> <h3>A. Define a dummy <code>Position</code></h3> <p>Before the class definition, place a dummy definition:</p> <pre><code>class Position(object): pass class Position(object): ... </code></pre> <p>This will get rid of the <code>NameError</code> and may even look OK:</p> <pre><code>&gt;&gt;&gt; Position.__add__.__annotations__ {'other': __main__.Position, 'return': __main__.Position} </code></pre> <p>But is it?</p> <pre><code>&gt;&gt;&gt; for k, v in Position.__add__.__annotations__.items(): ... print(k, 'is Position:', v is Position) return is Position: False other is Position: False </code></pre> <h3>B. Monkey-patch in order to add the annotations:</h3> <p>You may want to try some Python metaprogramming magic and write a decorator to monkey-patch the class definition in order to add annotations:</p> <pre><code>class Position: ... def __add__(self, other): return self.__class__(self.x + other.x, self.y + other.y) </code></pre> <p>The decorator should be responsible for the equivalent of this:</p> <pre><code>Position.__add__.__annotations__['return'] = Position Position.__add__.__annotations__['other'] = Position </code></pre> <p>At least it seems right:</p> <pre><code>&gt;&gt;&gt; for k, v in Position.__add__.__annotations__.items(): ... print(k, 'is Position:', v is Position) return is Position: True other is Position: True </code></pre> <p>Probably too much trouble.</p>
{ "question_id": 33533148, "question_date": "2015-11-04T22:17:54.093Z", "question_score": 1020, "tags": "python|python-3.x|pycharm|type-hinting|python-typing", "answer_id": 33533514, "answer_date": "2015-11-04T22:44:33.850Z", "answer_score": 1409 }
Please answer the following Stack Overflow question: Title: Ruby: How to install a specific version of a ruby gem? <p>Using the command-line <code>gem</code> tool, how can I install a specific version of a gem?</p>
<p>Use the <code>-v</code> flag:</p> <pre><code>$ gem install fog -v 1.8 </code></pre>
{ "question_id": 17026441, "question_date": "2013-06-10T14:37:15.097Z", "question_score": 1019, "tags": "ruby|rubygems", "answer_id": 17026442, "answer_date": "2013-06-10T14:37:15.097Z", "answer_score": 1316 }
Please answer the following Stack Overflow question: Title: What are the rules about using an underscore in a C++ identifier? <p>It's common in C++ to name member variables with some kind of prefix to denote the fact that they're member variables, rather than local variables or parameters. If you've come from an MFC background, you'll probably use <code>m_foo</code>. I've also seen <code>myFoo</code> occasionally.</p> <p>C# (or possibly just .NET) seems to recommend using just an underscore, as in <code>_foo</code>. Is this allowed by the C++ standard?</p>
<p>The rules (which did not change in C++11):</p> <ul> <li>Reserved in any scope, including for use as <a href="https://stackoverflow.com/questions/4297933/c-implementation#4297974">implementation</a> macros: <ul> <li>identifiers beginning with an underscore followed immediately by an uppercase letter</li> <li>identifiers containing adjacent underscores (or "double underscore")</li> </ul></li> <li>Reserved in the global namespace: <ul> <li>identifiers beginning with an underscore</li> </ul></li> <li>Also, everything in the <code>std</code> namespace is reserved. (You are allowed to add template specializations, though.) </li> </ul> <p>From the 2003 C++ Standard:</p> <blockquote> <h3>17.4.3.1.2 Global names [lib.global.names]</h3> <p>Certain sets of names and function signatures are always reserved to the implementation:</p> <ul> <li>Each name that contains a double underscore (<code>__</code>) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.</li> <li>Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.<sup>165</sup></li> </ul> <p><sup>165)</sup> Such names are also reserved in namespace <code>::std</code> (17.4.3.1). </p> </blockquote> <p>Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:</p> <blockquote> <h3>7.1.3 Reserved identifiers</h3> <p>Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.</p> <ul> <li>All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.</li> <li>All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.</li> <li>Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).</li> <li>All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.<sup>154</sup></li> <li>Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.</li> </ul> <p>No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.</p> <p>If the program removes (with <code>#undef</code>) any macro definition of an identifier in the first group listed above, the behavior is undefined.</p> <p><sup>154)</sup> The list of reserved identifiers with external linkage includes <code>errno</code>, <code>math_errhandling</code>, <code>setjmp</code>, and <code>va_end</code>.</p> </blockquote> <p>Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:</p> <ul> <li>Names beginning with a capital <code>E</code> followed a digit or uppercase letter: <ul> <li>may be used for additional error code names.</li> </ul></li> <li>Names that begin with either <code>is</code> or <code>to</code> followed by a lowercase letter <ul> <li>may be used for additional character testing and conversion functions.</li> </ul></li> <li>Names that begin with <code>LC_</code> followed by an uppercase letter <ul> <li>may be used for additional macros specifying locale attributes.</li> </ul></li> <li>Names of all existing mathematics functions suffixed with <code>f</code> or <code>l</code> are reserved <ul> <li>for corresponding functions that operate on float and long double arguments, respectively.</li> </ul></li> <li>Names that begin with <code>SIG</code> followed by an uppercase letter are reserved <ul> <li>for additional signal names.</li> </ul></li> <li>Names that begin with <code>SIG_</code> followed by an uppercase letter are reserved <ul> <li>for additional signal actions.</li> </ul></li> <li>Names beginning with <code>str</code>, <code>mem</code>, or <code>wcs</code> followed by a lowercase letter are reserved <ul> <li>for additional string and array functions.</li> </ul></li> <li>Names beginning with <code>PRI</code> or <code>SCN</code> followed by any lowercase letter or <code>X</code> are reserved <ul> <li>for additional format specifier macros</li> </ul></li> <li>Names that end with <code>_t</code> are reserved <ul> <li>for additional type names.</li> </ul></li> </ul> <p>While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.</p> <hr> <p>Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.</p> <p>After doing research on this article I no longer end my identifiers with <code>_t</code> as this is reserved by the POSIX standard.</p> <p>The rule about any identifier ending with <code>_t</code> surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the <a href="http://www.gnu.org/software/libtool/manual/libc/Reserved-Names.html" rel="noreferrer">GNU libtool manual</a>, listing reserved names.</p> <p>CesarB provided the following link to the <a href="http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html" rel="noreferrer">POSIX 2004</a> reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The <a href="http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html" rel="noreferrer">POSIX 2008</a> reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.</p>
{ "question_id": 228783, "question_date": "2008-10-23T07:02:06.347Z", "question_score": 1019, "tags": "c++|naming-conventions|standards|c++-faq", "answer_id": 228797, "answer_date": "2008-10-23T07:08:41.280Z", "answer_score": 932 }
Please answer the following Stack Overflow question: Title: Escape curly brace '{' in String.Format <p>How do I display a literal curly brace character when using the String.Format method?</p> <p>Example:</p> <pre><code>sb.AppendLine(String.Format("public {0} {1} { get; private set; }", prop.Type, prop.Name)); </code></pre> <p>I would like the output to look like this:</p> <pre><code>public Int32 MyProperty { get; private set; } </code></pre>
<p>Use double braces <code>{{</code> or <code>}}</code> so your code becomes:</p> <pre><code>sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", prop.Type, prop.Name)); // For prop.Type of "Foo" and prop.Name of "Bar", the result would be: // public Foo Bar { get; private set; } </code></pre>
{ "question_id": 3773857, "question_date": "2010-09-22T21:44:19.330Z", "question_score": 1019, "tags": "c#|.net|string", "answer_id": 3773868, "answer_date": "2010-09-22T21:45:47.240Z", "answer_score": 1548 }
Please answer the following Stack Overflow question: Title: not:first-child selector <p>I have a <code>div</code> tag containing several <code>ul</code> tags.</p> <p>I'm able to set CSS properties for the first <code>ul</code> tag only:</p> <pre class="lang-css prettyprint-override"><code>div ul:first-child { background-color: #900; } </code></pre> <p>However, my following attempts to set CSS properties for each other <code>ul</code> tag except the first one don't work:</p> <pre class="lang-css prettyprint-override"><code>div ul:not:first-child { background-color: #900; } div ul:not(:first-child) { background-color: #900; } div ul:first-child:after { background-color: #900; } </code></pre> <p>How can I write in CSS: "each element, except the first"?</p>
<p>One of the versions you posted <a href="http://jsfiddle.net/5TKjB/">actually works</a> for all modern browsers (where <a href="http://www.w3.org/TR/css3-selectors/">CSS selectors level 3</a> are <a href="http://caniuse.com/#feat=css-sel3">supported</a>):</p> <pre><code>div ul:not(:first-child) { background-color: #900; } </code></pre> <p>If you need to support legacy browsers, or if you are hindered by the <code>:not</code> selector's <a href="http://www.w3.org/TR/css3-selectors/#negation">limitation</a> (it only accepts a <a href="http://www.w3.org/TR/css3-selectors/#simple-selectors-dfn">simple selector</a> as an argument) then you can use another technique:</p> <p>Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:</p> <pre><code>div ul { background-color: #900; /* applies to every ul */ } div ul:first-child { background-color: transparent; /* limits the scope of the previous rule */ } </code></pre> <p>When limiting the scope use the <a href="http://www.w3.org/TR/CSS2/colors.html#background-properties">default value</a> for each CSS attribute that you are setting.</p>
{ "question_id": 12289853, "question_date": "2012-09-05T21:09:16.673Z", "question_score": 1018, "tags": "css|css-selectors", "answer_id": 12289888, "answer_date": "2012-09-05T21:11:23.177Z", "answer_score": 1785 }
Please answer the following Stack Overflow question: Title: How to parse JSON using Node.js? <p>How should I parse JSON using Node.js? Is there some module which will validate and parse JSON securely?</p>
<p>You can simply use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="noreferrer"><code>JSON.parse</code></a>. </p> <p>The definition of the <code>JSON</code> object <a href="http://es5.github.com/#x15.12" rel="noreferrer">is part of the ECMAScript 5 specification</a>. node.js is built on Google Chrome's <a href="https://developers.google.com/v8/" rel="noreferrer">V8</a> engine, which adheres to ECMA standard. Therefore, node.js also has a global object <a href="https://developer.mozilla.org/En/Using_JSON_in_Firefox" rel="noreferrer"><strong><code>JSON</code></strong><sup><em>[docs]</em></sup></a>. </p> <p>Note - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="noreferrer"><code>JSON.parse</code></a> can tie up the current thread because it is a synchronous method. So if you are planning to parse big JSON objects use a streaming json parser.</p>
{ "question_id": 5726729, "question_date": "2011-04-20T07:10:52.583Z", "question_score": 1018, "tags": "javascript|json|node.js", "answer_id": 5726756, "answer_date": "2011-04-20T07:13:45.350Z", "answer_score": 1133 }
Please answer the following Stack Overflow question: Title: Shell command to tar directory excluding certain files/folders <p>Is there a simple shell command/script that supports excluding certain files/folders from being archived?</p> <p>I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.</p> <p><strong>Not quite solutions:</strong></p> <p>The <code>tar --exclude=PATTERN</code> command matches the given pattern and excludes those files, but I need specific files &amp; folders to be ignored (full file path), otherwise valid files might be excluded.</p> <p>I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.</p> <p>I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with <code>--exclude-from=file</code> to copy all the files to a tmp directory, and then use tar to archive that directory.</p> <p>Can anybody think of a better/more efficient solution?</p> <p>EDIT: <strong>Charles Ma</strong>'s solution works well. The big gotcha is that the <code>--exclude='./folder'</code> <strong>MUST</strong> be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):</p> <pre><code>cd /folder_to_backup tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz . </code></pre>
<p>You can have multiple exclude options for tar so</p> <pre><code>$ tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz . </code></pre> <p>etc will work. Make <strong>sure</strong> to put <code>--exclude</code> <strong>before</strong> the source and destination items. </p>
{ "question_id": 984204, "question_date": "2009-06-11T22:57:31.850Z", "question_score": 1015, "tags": "linux|shell|archive|tar", "answer_id": 984259, "answer_date": "2009-06-11T23:11:19.027Z", "answer_score": 1316 }
Please answer the following Stack Overflow question: Title: How can I stop .gitignore from appearing in the list of untracked files? <p>I just did a <code>git init</code> on the root of my new project.</p> <p>Then I created a <code>.gitignore</code> file.</p> <p>Now, when I type <code>git status</code>, <strong>.gitignore</strong> file appears in the list of untracked files. Why is that?</p>
<p>The <code>.gitignore</code> file should be in your repository, so it should indeed be added and committed in, as <code>git status</code> suggests. It has to be a part of the repository tree, so that changes to it can be merged and so on.</p> <p>So, add it to your repository, it should not be gitignored.</p> <p>If you really want you can add <code>.gitignore</code> to the <code>.gitignore</code> file if you don't want it to be committed. However, in that case it's probably better to add the ignores to <code>.git/info/exclude</code>, a special checkout-local file that works just like .gitignore but does not show up in "git status" since it's in the <code>.git</code> folder.</p> <p>See also <a href="https://help.github.com/articles/ignoring-files" rel="noreferrer">https://help.github.com/articles/ignoring-files</a></p>
{ "question_id": 767147, "question_date": "2009-04-20T06:42:27.050Z", "question_score": 1015, "tags": "git|version-control|dvcs|gitignore", "answer_id": 767213, "answer_date": "2009-04-20T07:11:45.857Z", "answer_score": 1016 }
Please answer the following Stack Overflow question: Title: How would I extract a single file (or changes to a file) from a git stash? <p>Is it possible to extract a single file or diff of a file from a git stash without popping the stash changeset off?</p>
<p>On the <a href="http://git-scm.com/docs/git-stash" rel="noreferrer" title="git-stash - Stash the changes in a dirty working directory away">git stash</a> manpage you can read (in the &quot;Discussion&quot; section, just after &quot;Options&quot; description) that:</p> <blockquote> <p>A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created.</p> </blockquote> <p>So you can treat stash (e.g. <code>stash@{0}</code> is first / topmost stash) as a merge commit, and use:</p> <pre><code>$ git diff stash@{0}^1 stash@{0} -- &lt;filename&gt; </code></pre> <p>Explanation: <code>stash@{0}^1</code> means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away. We use this form of &quot;git diff&quot; (with two commits) because <code>stash@{0}</code> / <code>refs/stash</code> is a merge commit, and we have to tell git which parent we want to diff against. More cryptic:</p> <pre><code>$ git diff stash@{0}^! -- &lt;filename&gt; </code></pre> <p>should also work (see <a href="http://git-scm.com/docs/git-rev-parse#_specifying_ranges" rel="noreferrer">git rev-parse</a> manpage for explanation of <code>rev^!</code> syntax, in &quot;Specifying ranges&quot; section).</p> <p>Likewise, you can use <a href="http://git-scm.com/docs/git-checkout" rel="noreferrer">git checkout</a> to check a single file out of the stash:</p> <pre><code>$ git checkout stash@{0} -- &lt;filename&gt; </code></pre> <p>or to save it under another filename:</p> <pre><code>$ git show stash@{0}:&lt;full filename&gt; &gt; &lt;newfile&gt; </code></pre> <p>or</p> <pre><code>$ git show stash@{0}:./&lt;relative filename&gt; &gt; &lt;newfile&gt; </code></pre> <p>(<em>note</em> that here &lt;full filename&gt; is full pathname of a file relative to top directory of a project (think: relative to <code>stash@{0}</code>)).</p> <hr /> <p>You might need to protect <code>stash@{0}</code> from shell expansion, i.e. use <code>&quot;stash@{0}&quot;</code> or <code>'stash@{0}'</code>.</p>
{ "question_id": 1105253, "question_date": "2009-07-09T17:12:11.013Z", "question_score": 1015, "tags": "git|git-stash", "answer_id": 1105666, "answer_date": "2009-07-09T18:21:11.110Z", "answer_score": 1450 }
Please answer the following Stack Overflow question: Title: Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm' <p>I have Windows 7 32-bit. I installed the latest <a href="http://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a> 32 bit.<br> When I try to run the command <code>npm install jquery</code>, I receive the error:</p> <blockquote> <p>Error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm </p> </blockquote> <p>How does one resolve it?</p>
<p>Manually creating a folder named 'npm' in the displayed path fixed the problem.</p> <p>More information can be found on <a href="https://github.com/npm/npm/wiki/Troubleshooting#error-enoent-stat-cusersuserappdataroamingnpm-on-windows-7" rel="noreferrer">Troubleshooting page</a></p>
{ "question_id": 25093276, "question_date": "2014-08-02T08:45:08.317Z", "question_score": 1015, "tags": "windows|node.js|installation", "answer_id": 25095327, "answer_date": "2014-08-02T13:04:56.567Z", "answer_score": 1805 }
Please answer the following Stack Overflow question: Title: What's "tools:context" in Android layout files? <p>Starting with a recent new version of ADT, I've noticed this new attribute on the layout XML files, for example:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity" /&gt; </code></pre> <p><strong>What is "tools:context" used for?</strong></p> <p>How does it even know the exact path to the activity that is written there? Does it look at the package of the app, inside the manifest?</p> <p>Is it limited to classes that extend Context or only activities? Is it usable for ListView items etc.?</p>
<p>This is the activity the tools UI editor uses to render your layout preview. It is documented <a href="https://developer.android.com/studio/write/tool-attributes#toolscontext" rel="noreferrer">here</a>: </p> <blockquote> <p>This attribute declares which activity this layout is associated with by default. This enables features in the editor or layout preview that require knowledge of the activity, such as what the layout theme should be in the preview and where to insert onClick handlers when you make those from a quickfix</p> </blockquote>
{ "question_id": 11078487, "question_date": "2012-06-18T07:25:48.703Z", "question_score": 1014, "tags": "android|xml|android-layout|android-context|android-tools-namespace", "answer_id": 11078889, "answer_date": "2012-06-18T07:56:54.150Z", "answer_score": 495 }
Please answer the following Stack Overflow question: Title: How to .gitignore all files/folder in a folder, but not the folder itself? <p>I want to check in a blank folder to my Git repository. Effectively, I need to ignore all of the files and folders within the folder, but not the folder itself. How can I do this? What should I put in my <code>.gitignore</code> file?</p> <p>For those wondering why I would want to do this, I have an &quot;upload&quot; directory in my repository. I want to commit the blank directory, but without all the contents.</p>
<p>You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.</p> <p>For example, add an empty file called <code>.gitkeep</code> to the folder you want to keep, then in your <code>.gitignore</code> file write:</p> <pre><code># exclude everything somefolder/* # exception to the rule !somefolder/.gitkeep </code></pre> <p>Commit your <code>.gitignore</code> and <code>.gitkeep</code> files and this should resolve your issue.</p>
{ "question_id": 4250063, "question_date": "2010-11-22T20:42:08.313Z", "question_score": 1012, "tags": "git|gitignore", "answer_id": 4250082, "answer_date": "2010-11-22T20:43:48.783Z", "answer_score": 948 }
Please answer the following Stack Overflow question: Title: Python's equivalent of && (logical-and) in an if-statement <p>This doesn't work:</p> <pre><code>if cond1 &amp;&amp; cond2: </code></pre>
<p>Use <code>and</code> instead of <code>&amp;&amp;</code>.</p>
{ "question_id": 2485466, "question_date": "2010-03-21T01:23:03.370Z", "question_score": 1011, "tags": "python", "answer_id": 2485471, "answer_date": "2010-03-21T01:25:05.950Z", "answer_score": 1766 }
Please answer the following Stack Overflow question: Title: How to concatenate (join) items in a list to a single string <p>How do I concatenate a list of strings into a single string?</p> <p>For example, given <code>['this', 'is', 'a', 'sentence']</code>, how do I get <code>&quot;this-is-a-sentence&quot;</code>?</p> <hr /> <p><sub>For handling a few strings in <em>separate variables</em>, see <a href="https://stackoverflow.com/questions/4435169">How do I append one string to another in Python?</a>.</sub></p> <p><sub>For the opposite process - creating a list from a string - see <a href="https://stackoverflow.com/q/4978787">How do I split a string into a list of characters?</a> or <a href="https://stackoverflow.com/questions/743806/">How do I split a string into a list of words?</a> as appropriate.</sub></p>
<p>Use <a href="https://docs.python.org/library/stdtypes.html#str.join" rel="noreferrer"><code>str.join</code></a>:</p> <pre><code>&gt;&gt;&gt; words = ['this', 'is', 'a', 'sentence'] &gt;&gt;&gt; '-'.join(words) 'this-is-a-sentence' &gt;&gt;&gt; ' '.join(words) 'this is a sentence' </code></pre>
{ "question_id": 12453580, "question_date": "2012-09-17T05:32:25.410Z", "question_score": 1011, "tags": "python|string|list|concatenation", "answer_id": 12453584, "answer_date": "2012-09-17T05:33:41.273Z", "answer_score": 1765 }
Please answer the following Stack Overflow question: Title: How do I resolve git saying "Commit your changes or stash them before you can merge"? <p>I made some updates on my local machine, pushed them to a remote repository, and now I'm trying to pull the changes to the server and I get the message;</p> <pre><code>error: Your local changes to the following files would be overwritten by merge: wp-content/w3tc-config/master.php Please, commit your changes or stash them before you can merge. </code></pre> <p>So I ran,</p> <pre><code>git checkout -- wp-content/w3tc-config/master.php </code></pre> <p>and tried again and I get the same message. I'm assuming that <code>w3tc</code> changed something in the config file on the server. I don't care whether the local copy or remote copy goes on the server (I suppose the remote one is best), I just want to be able to merge the rest of my changes (plugin updates).</p> <p>Any ideas?</p>
<p>You can't merge with local modifications. Git protects you from losing potentially important changes.</p> <p>You have three options: </p> <ul> <li><h2>Commit the change using</h2> <pre><code>git commit -m "My message" </code></pre></li> <li><h2>Stash it.</h2> <p>Stashing acts as a stack, where you can push changes, and you pop them in reverse order.</p> <p>To stash, type</p> <pre><code>git stash </code></pre> <p>Do the merge, and then pull the stash:</p> <pre><code>git stash pop </code></pre></li> <li><h2>Discard the local changes</h2> <p>using <code>git reset --hard</code><br> or <code>git checkout -t -f remote/branch</code></p> <h2>Or: Discard local changes for a specific file</h2> <p>using <code>git checkout filename</code></p></li> </ul>
{ "question_id": 15745045, "question_date": "2013-04-01T14:11:34.087Z", "question_score": 1011, "tags": "git|git-commit", "answer_id": 15745424, "answer_date": "2013-04-01T14:34:59.827Z", "answer_score": 1721 }
Please answer the following Stack Overflow question: Title: How to check if a String is numeric in Java <p>How would you check if a String was a number before parsing it?</p>
<p>With <a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a> 3.5 and above: <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#isCreatable-java.lang.String-" rel="noreferrer"><code>NumberUtils.isCreatable</code></a> or <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumeric-java.lang.CharSequence-" rel="noreferrer"><code>StringUtils.isNumeric</code></a>.</p> <p>With <a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a> 3.4 and below: <a href="https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/math/NumberUtils.html#isNumber(java.lang.String)" rel="noreferrer"><code>NumberUtils.isNumber</code></a> or <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumeric-java.lang.CharSequence-" rel="noreferrer"><code>StringUtils.isNumeric</code></a>.</p> <p>You can also use <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumericSpace-java.lang.CharSequence-" rel="noreferrer"><code>StringUtils.isNumericSpace</code></a> which returns <code>true</code> for empty strings and ignores internal spaces in the string. Another way is to use <a href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-" rel="noreferrer"><code>NumberUtils.isParsable</code></a> which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)</p>
{ "question_id": 1102891, "question_date": "2009-07-09T09:49:47.097Z", "question_score": 1010, "tags": "java|string|numeric", "answer_id": 12569609, "answer_date": "2012-09-24T17:01:45.170Z", "answer_score": 767 }
Please answer the following Stack Overflow question: Title: When should I use git pull --rebase? <p>I know of some people who use <code>git pull --rebase</code> by default and others who insist never to use it. I believe I understand the difference between merging and rebasing, but I'm trying to put this in the context of <code>git pull</code>. Is it just about not wanting to see lots of merge commit messages, or are there other issues?</p>
<p>You should use <code>git pull --rebase</code> when</p> <ul> <li>your changes do not deserve a separate branch</li> </ul> <p>Indeed -- why not then? It's more clear, and doesn't impose a <em>logical grouping</em> on your commits.</p> <hr> <p>Ok, I suppose it needs some clarification. In Git, as you probably know, you're encouraged to branch and merge. Your local branch, into which you pull changes, and remote branch are, actually, different branches, and <code>git pull</code> is about merging them. It's reasonable, since you push not very often and usually accumulate a number of changes before they constitute a completed feature.</p> <p>However, sometimes--by whatever reason--you think that it would actually be better if these two--remote and local--were <strong>one</strong> branch. Like in SVN. It is here where <code>git pull --rebase</code> comes into play. You no longer merge--you actually <em>commit on top of the remote branch</em>. That's what it actually is about.</p> <p>Whether it's dangerous or not is the question of whether you are treating local and remote branch as one inseparable thing. Sometimes it's reasonable (when your changes are small, or if you're at the beginning of a robust development, when important changes are brought in by small commits). Sometimes it's not (when you'd normally create another branch, but you were too lazy to do that). But that's a different question.</p>
{ "question_id": 2472254, "question_date": "2010-03-18T18:04:26.913Z", "question_score": 1010, "tags": "git", "answer_id": 2472606, "answer_date": "2010-03-18T19:01:45.833Z", "answer_score": 687 }
Please answer the following Stack Overflow question: Title: What does set -e mean in a bash script? <p>I'm studying the content of this <strong>preinst</strong> file that the script executes before that package is unpacked from its Debian archive (.deb) file.</p> <p>The script has the following code:</p> <pre><code>#!/bin/bash set -e # Automatically added by dh_installinit if [ "$1" = install ]; then if [ -d /usr/share/MyApplicationName ]; then echo "MyApplicationName is just installed" return 1 fi rm -Rf $HOME/.config/nautilus-actions/nautilus-actions.conf rm -Rf $HOME/.local/share/file-manager/actions/* fi # End automatically added section </code></pre> <p>My first query is about the line:</p> <pre><code>set -e </code></pre> <p>I think that the rest of the script is pretty simple: It checks whether the Debian/Ubuntu package manager is executing an install operation. If it is, it checks whether my application has just been installed on the system. If it has, the script prints the message <strong>"MyApplicationName is just installed"</strong> and ends (<code>return 1</code> mean that ends with an “error”, doesn’t it?).</p> <p>If the user is asking the Debian/Ubuntu package system to install my package, the script also deletes two directories.</p> <p>Is this right or am I missing something?</p>
<p>From <code>help set</code> :</p> <pre><code> -e Exit immediately if a command exits with a non-zero status. </code></pre> <p>But it's considered bad practice by some (bash FAQ and irc freenode #bash FAQ authors). It's recommended to use:</p> <pre><code>trap 'do_something' ERR </code></pre> <p>to run <code>do_something</code> function when errors occur.</p> <p>See <a href="http://mywiki.wooledge.org/BashFAQ/105" rel="noreferrer">http://mywiki.wooledge.org/BashFAQ/105</a></p>
{ "question_id": 19622198, "question_date": "2013-10-27T19:06:32.730Z", "question_score": 1010, "tags": "linux|bash|shell|sh", "answer_id": 19622569, "answer_date": "2013-10-27T19:39:10.623Z", "answer_score": 1050 }
Please answer the following Stack Overflow question: Title: HTTP GET request in JavaScript? <p>I need to do an <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">HTTP GET</a> request in JavaScript. What's the best way to do that?</p> <p>I need to do this in a Mac OS X dashcode widget.</p>
<p>Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:</p> <pre><code>function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); // false for synchronous request xmlHttp.send( null ); return xmlHttp.responseText; } </code></pre> <p>However, synchronous requests are discouraged and will generate a warning along the lines of:</p> <blockquote> <p>Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), <strong>synchronous requests on the main thread have been deprecated</strong> due to the negative effects to the user experience.</p> </blockquote> <p>You should make an asynchronous request and handle the response inside an event handler.</p> <pre><code>function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) callback(xmlHttp.responseText); } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } </code></pre>
{ "question_id": 247483, "question_date": "2008-10-29T16:31:34.800Z", "question_score": 1008, "tags": "javascript|http-get|dashcode", "answer_id": 4033310, "answer_date": "2010-10-27T12:43:51.507Z", "answer_score": 1430 }
Please answer the following Stack Overflow question: Title: How to remove files from git staging area? <p>I made changes to some of my files in my local repo, and then I did <code>git add -A</code> which I think added too many files to the staging area. How can I delete all the files from the staging area?</p> <p>After I do that, I'll just manually do <code>git add "filename"</code>.</p>
<p>You can unstage files from the index using</p> <pre><code>git reset HEAD -- path/to/file </code></pre> <p>Just like <code>git add</code>, you can unstage files recursively by directory and so forth, so to unstage everything at once, run this from the root directory of your repository:</p> <pre><code>git reset HEAD -- . </code></pre> <p>Also, for future reference, the output of <code>git status</code> will tell you the commands you need to run to move files from one state to another.</p>
{ "question_id": 19730565, "question_date": "2013-11-01T16:03:45.543Z", "question_score": 1008, "tags": "git", "answer_id": 19730687, "answer_date": "2013-11-01T16:10:11.090Z", "answer_score": 1187 }
Please answer the following Stack Overflow question: Title: Creating a comma separated list from IList<string> or IEnumerable<string> <p>What is the cleanest way to create a comma-separated list of string values from an <code>IList&lt;string&gt;</code> or <code>IEnumerable&lt;string&gt;</code>?</p> <p><code>String.Join(...)</code> operates on a <code>string[]</code> so can be cumbersome to work with when types such as <code>IList&lt;string&gt;</code> or <code>IEnumerable&lt;string&gt;</code> cannot easily be converted into a string array.</p>
<p><strong>.NET 4+</strong></p> <pre><code>IList&lt;string&gt; strings = new List&lt;string&gt;{"1","2","testing"}; string joined = string.Join(",", strings); </code></pre> <p><strong>Detail &amp; Pre .Net 4.0 Solutions</strong></p> <p><code>IEnumerable&lt;string&gt;</code> can be converted into a string array <em>very</em> easily with LINQ (.NET 3.5):</p> <pre><code>IEnumerable&lt;string&gt; strings = ...; string[] array = strings.ToArray(); </code></pre> <p>It's easy enough to write the equivalent helper method if you need to:</p> <pre><code>public static T[] ToArray(IEnumerable&lt;T&gt; source) { return new List&lt;T&gt;(source).ToArray(); } </code></pre> <p>Then call it like this:</p> <pre><code>IEnumerable&lt;string&gt; strings = ...; string[] array = Helpers.ToArray(strings); </code></pre> <p>You can then call <code>string.Join</code>. Of course, you don't <em>have</em> to use a helper method:</p> <pre><code>// C# 3 and .NET 3.5 way: string joined = string.Join(",", strings.ToArray()); // C# 2 and .NET 2.0 way: string joined = string.Join(",", new List&lt;string&gt;(strings).ToArray()); </code></pre> <p>The latter is a bit of a mouthful though :)</p> <p>This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) <a href="https://stackoverflow.com/questions/219519/whats-the-c-method-syntax-for-converting-an-array-to-a-simple-string">this one</a>.</p> <p>As of .NET 4.0, there are more overloads available in <a href="http://msdn.microsoft.com/en-us/library/system.string.join" rel="noreferrer"><code>string.Join</code></a>, so you can actually just write:</p> <pre><code>string joined = string.Join(",", strings); </code></pre> <p>Much simpler :)</p>
{ "question_id": 799446, "question_date": "2009-04-28T19:15:58.033Z", "question_score": 1008, "tags": "c#|string", "answer_id": 799454, "answer_date": "2009-04-28T19:17:41.977Z", "answer_score": 1715 }
Please answer the following Stack Overflow question: Title: Force "git push" to overwrite remote files <p>I want to push my local files, and have them on a remote repo, without having to deal with merge conflicts. I just want my local version to have priority over the remote one.</p> <p>How can I do this with Git?</p>
<p>You should be able to force your local revision to the remote repo by using </p> <pre><code>git push -f &lt;remote&gt; &lt;branch&gt; </code></pre> <p>(e.g. <code>git push -f origin master</code>). Leaving off <code>&lt;remote&gt;</code> and <code>&lt;branch&gt;</code> will force push all local branches that have set <code>--set-upstream</code>.</p> <p>Just be warned, if other people are sharing this repository their revision history will conflict with the new one. And if they have any local commits after the point of change they will become invalid.</p> <p><strong>Update</strong>: Thought I would add a side-note. If you are creating changes that others will review, then it's not uncommon to create a branch with those changes and rebase periodically to keep them up-to-date with the main development branch. Just let other developers know this will happen periodically so they'll know what to expect.</p> <p><strong>Update 2</strong>: Because of the increasing number of viewers I'd like to add some additional information on what to do when your <code>upstream</code> does experience a force push.</p> <p>Say I've cloned your repo and have added a few commits like so:</p> <pre> D----E topic / A----B----C development </pre> <p>But later the <code>development</code> branch is hit with a <code>rebase</code>, which will cause me to receive an error like so when I run <code>git pull</code>:</p> <pre> Unpacking objects: 100% (3/3), done. From &lt;repo-location&gt; * branch development -> FETCH_HEAD Auto-merging &lt;files&gt; CONFLICT (content): Merge conflict in &lt;locations&gt; Automatic merge failed; fix conflicts and then commit the result. </pre> <p>Here I could fix the conflicts and <code>commit</code>, but that would leave me with a really ugly commit history:</p> <pre> C----D----E----F topic / / A----B--------------C' development </pre> <p>It might look enticing to use <code>git pull --force</code> but be careful because that'll leave you with stranded commits:</p> <pre> D----E topic A----B----C' development </pre> <p>So probably the best option is to do a <code>git pull --rebase</code>. This will require me to resolve any conflicts like before, but for each step instead of committing I'll use <code>git rebase --continue</code>. In the end the commit history will look much better:</p> <pre> D'---E' topic / A----B----C' development </pre> <p><strong>Update 3:</strong> You can also use the <code>--force-with-lease</code> option as a "safer" force push, <a href="https://stackoverflow.com/a/24768381/456814">as mentioned by Cupcake in his answer</a>:</p> <blockquote> <p>Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:</p> <pre><code>git push &lt;remote&gt; &lt;branch&gt; --force-with-lease </code></pre> <p>You can learn more details about how to use <code>--force-with-lease</code> by reading any of the following:</p> <ul> <li><a href="http://jk.gs/git-push.html" rel="noreferrer"><code>git push</code> documentation</a></li> <li><a href="https://stackoverflow.com/questions/3166713/git-how-to-ignore-fast-forward-and-revert-origin-branch-to-earlier-commit/18505634#18505634">Git: How to ignore fast forward and revert origin [branch] to earlier commit?</a></li> </ul> </blockquote>
{ "question_id": 10510462, "question_date": "2012-05-09T05:45:38.680Z", "question_score": 1007, "tags": "git|git-push", "answer_id": 10510482, "answer_date": "2012-05-09T05:48:23.470Z", "answer_score": 1360 }
Please answer the following Stack Overflow question: Title: How can I write a `try`/`except` block that catches all exceptions? <p>How can I write a <code>try</code>/<code>except</code> block that catches all exceptions?</p>
<p>You can but you probably shouldn't:</p> <pre><code>try: do_something() except: print(&quot;Caught it!&quot;) </code></pre> <p>However, this will also catch exceptions like <code>KeyboardInterrupt</code> and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example <a href="http://docs.python.org/tutorial/errors.html" rel="noreferrer">from the docs</a>:</p> <pre><code>try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print(&quot;I/O error({0}): {1}&quot;.format(errno, strerror)) except ValueError: print(&quot;Could not convert data to an integer.&quot;) except: print(&quot;Unexpected error:&quot;, sys.exc_info()[0]) raise </code></pre>
{ "question_id": 4990718, "question_date": "2011-02-14T09:46:58.300Z", "question_score": 1007, "tags": "python|exception", "answer_id": 4990739, "answer_date": "2011-02-14T09:49:45.027Z", "answer_score": 727 }
Please answer the following Stack Overflow question: Title: How can I calculate the number of lines changed between two commits in Git? <p>Is there any easy way to calculate the number of lines changed between two commits in Git?</p> <p>I know I can do a <code>git diff</code>, and count the lines, but this seems tedious. I'd also like to know how I can do this, including only my own commits in the line counts.</p>
<p>You want the <code>--stat</code> option of <code>git diff</code>, or if you're looking to parse this in a script, the <code>--numstat</code> option.</p> <pre><code>git diff --stat &lt;commit-ish&gt; &lt;commit-ish&gt; </code></pre> <p><code>--stat</code> produces the human-readable output you're used to seeing after merges; <code>--numstat</code> produces a nice table layout that scripts can easily interpret.</p> <p>I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for <code>git log</code>. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since <code>git log</code> internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just <code>--shortstat</code>. What you likely want to use is:</p> <pre><code>git log --author="Your name" --stat &lt;commit1&gt;..&lt;commit2&gt; </code></pre> <p>but you can use <code>--numstat</code> or <code>--shortstat</code> as well. <code>git log</code> can also select commits in a variety other ways - have a look at the <a href="http://git-scm.com/docs/git-log" rel="noreferrer">documentation</a>. You might be interested in things like <code>--since</code> (rather than specifying commit ranges, just select commits since last week) and <code>--no-merges</code> (merge commits don't actually introduce changes), as well as the pretty output options (<code>--pretty=oneline, short, medium, full...</code>).</p> <p>Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):</p> <pre><code>git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}' </code></pre> <p>(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)</p>
{ "question_id": 2528111, "question_date": "2010-03-27T04:02:58.547Z", "question_score": 1007, "tags": "git", "answer_id": 2528129, "answer_date": "2010-03-27T04:14:51.367Z", "answer_score": 1430 }
Please answer the following Stack Overflow question: Title: Drop data frame columns by name <p>I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:</p> <pre><code>df$x &lt;- NULL </code></pre> <p>But I was hoping to do this with fewer commands.</p> <p>Also, I know that I could drop columns using integer indexing like this:</p> <pre><code>df &lt;- df[ -c(1, 3:6, 12) ] </code></pre> <p>But I am concerned that the relative position of my variables may change.</p> <p>Given how powerful R is, I figured there might be a better way than dropping each column one by one.</p>
<p>There's also the <code>subset</code> command, useful if you know which columns you want:</p> <pre><code>df &lt;- data.frame(a = 1:10, b = 2:11, c = 3:12) df &lt;- subset(df, select = c(a, c)) </code></pre> <p>UPDATED after comment by @hadley: To <em>drop</em> columns a,c you could do:</p> <pre><code>df &lt;- subset(df, select = -c(a, c)) </code></pre>
{ "question_id": 4605206, "question_date": "2011-01-05T14:34:29.173Z", "question_score": 1005, "tags": "r|dataframe|r-faq", "answer_id": 4605405, "answer_date": "2011-01-05T14:52:40.727Z", "answer_score": 518 }
Please answer the following Stack Overflow question: Title: Getting Git to work with a proxy server - fails with "Request timed out" <p>How do I get Git to use a proxy server?</p> <p>I need to check out code from a Git server, but it shows "Request timed out" every time. How do I get around this? </p> <p>Alternatively, how can I set a proxy server?</p>
<p>Command to use:</p> <pre><code>git config --global http.proxy http://proxyuser:[email protected]:8080 </code></pre> <ul> <li>change <code>proxyuser</code> to your proxy user</li> <li>change <code>proxypwd</code> to your proxy password</li> <li>change <code>proxy.server.com</code> to the URL of your proxy server</li> <li>change <code>8080</code> to the proxy port configured on your proxy server</li> </ul> <p>Note that this works for both http and https repos.</p> <p>If you decide at any time to reset this proxy and work without proxy:</p> <p>Command to use:</p> <pre><code>git config --global --unset http.proxy </code></pre> <p>Finally, to check the currently set proxy:</p> <pre><code>git config --global --get http.proxy </code></pre>
{ "question_id": 783811, "question_date": "2009-04-23T22:32:53.877Z", "question_score": 1004, "tags": "git|version-control|proxy", "answer_id": 19213999, "answer_date": "2013-10-06T21:10:25.603Z", "answer_score": 1767 }
Please answer the following Stack Overflow question: Title: How do you set a default value for a MySQL Datetime column? <p>How do you set a default value for a MySQL Datetime column?</p> <p>In SQL Server it's <code>getdate()</code>. What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.</p>
<p><strong>IMPORTANT EDIT:</strong> It is now possible to achieve this with DATETIME fields since <strong>MySQL 5.6.5</strong>, take a look at the <a href="https://stackoverflow.com/a/10603198/24820">other post</a> below...</p> <p>Previous versions can't do that with DATETIME...</p> <p>But you can do it with TIMESTAMP:</p> <pre><code>mysql&gt; create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP); Query OK, 0 rows affected (0.00 sec) mysql&gt; desc test; +-------+-------------+------+-----+-------------------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+-------------------+-------+ | str | varchar(32) | YES | | NULL | | | ts | timestamp | NO | | CURRENT_TIMESTAMP | | +-------+-------------+------+-----+-------------------+-------+ 2 rows in set (0.00 sec) mysql&gt; insert into test (str) values (&quot;demo&quot;); Query OK, 1 row affected (0.00 sec) mysql&gt; select * from test; +------+---------------------+ | str | ts | +------+---------------------+ | demo | 2008-10-03 22:59:52 | +------+---------------------+ 1 row in set (0.00 sec) mysql&gt; </code></pre> <p><strong>CAVEAT:</strong> <em>IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to &quot;now()&quot; on update. This means that if you do not want the value to change, your UPDATE statement must contain &quot;[your column name] = [your column name]&quot; (or some other value) or the value will become &quot;now()&quot;. Weird, but true. I am using 5.5.56-MariaDB</em></p>
{ "question_id": 168736, "question_date": "2008-10-03T20:24:30.523Z", "question_score": 1003, "tags": "mysql|datetime", "answer_id": 168832, "answer_date": "2008-10-03T20:48:00.650Z", "answer_score": 953 }
Please answer the following Stack Overflow question: Title: What does T&& (double ampersand) mean in C++11? <p>I've been looking into some of the new features of C++11 and one I've noticed is the double ampersand in declaring variables, like <code>T&amp;&amp; var</code>.</p> <p>For a start, what is this beast called? I wish Google would allow us to search for punctuation like this.</p> <p>What exactly does it <em>mean?</em></p> <p>At first glance, it appears to be a double reference (like the C-style double pointers <code>T** var</code>), but I'm having a hard time thinking of a use case for that.</p>
<p>It declares an <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html" rel="noreferrer">rvalue reference</a> (standards proposal doc).</p> <p>Here's an introduction to rvalue <a href="https://www.artima.com/cppsource/rvalue.html" rel="noreferrer">references</a>.</p> <p>Here's a fantastic in-depth look at rvalue references by one of Microsoft's standard library <a href="https://docs.microsoft.com/archive/blogs/vcblog/rvalue-references-c0x-features-in-vc10-part-2" rel="noreferrer">developers</a>.</p> <blockquote> <p><em><strong>CAUTION:</strong> the linked article on MSDN (&quot;Rvalue References: C++0x Features in VC10, Part 2&quot;) is a very clear introduction to Rvalue references, but makes statements about Rvalue references that were once true in the draft C++11 standard, but are not true for the final one! Specifically, it says at various points that rvalue references can bind to lvalues, which was once true, but was changed.(e.g. int x; int &amp;&amp;rrx = x; no longer compiles in GCC) – drewbarbs Jul 13 '14 at 16:12</em></p> </blockquote> <p>The biggest difference between a C++03 reference (now called an lvalue reference in C++11) is that it can bind to an rvalue like a temporary without having to be const. Thus, this syntax is now legal:</p> <pre><code>T&amp;&amp; r = T(); </code></pre> <p>rvalue references primarily provide for the following:</p> <p><strong>Move semantics</strong>. A move constructor and move assignment operator can now be defined that takes an rvalue reference instead of the usual const-lvalue reference. A move functions like a copy, except it is not obliged to keep the source unchanged; in fact, it usually modifies the source such that it no longer owns the moved resources. This is great for eliminating extraneous copies, especially in standard library implementations.</p> <p>For example, a copy constructor might look like this:</p> <pre><code>foo(foo const&amp; other) { this-&gt;length = other.length; this-&gt;ptr = new int[other.length]; copy(other.ptr, other.ptr + other.length, this-&gt;ptr); } </code></pre> <p>If this constructor were passed a temporary, the copy would be unnecessary because we know the temporary will just be destroyed; why not make use of the resources the temporary already allocated? In C++03, there's no way to prevent the copy as we cannot determine whether we were passed a temporary. In C++11, we can overload a move constructor:</p> <pre><code>foo(foo&amp;&amp; other) { this-&gt;length = other.length; this-&gt;ptr = other.ptr; other.length = 0; other.ptr = nullptr; } </code></pre> <p>Notice the big difference here: the move constructor actually modifies its argument. This would effectively &quot;move&quot; the temporary into the object being constructed, thereby eliminating the unnecessary copy.</p> <p>The move constructor would be used for temporaries and for non-const lvalue references that are explicitly converted to rvalue references using the <code>std::move</code> function (it just performs the conversion). The following code both invoke the move constructor for <code>f1</code> and <code>f2</code>:</p> <pre><code>foo f1((foo())); // Move a temporary into f1; temporary becomes &quot;empty&quot; foo f2 = std::move(f1); // Move f1 into f2; f1 is now &quot;empty&quot; </code></pre> <p><strong>Perfect forwarding</strong>. rvalue references allow us to properly forward arguments for templated functions. Take for example this factory function:</p> <pre><code>template &lt;typename T, typename A1&gt; std::unique_ptr&lt;T&gt; factory(A1&amp; a1) { return std::unique_ptr&lt;T&gt;(new T(a1)); } </code></pre> <p>If we called <code>factory&lt;foo&gt;(5)</code>, the argument will be deduced to be <code>int&amp;</code>, which will not bind to a literal 5, even if <code>foo</code>'s constructor takes an <code>int</code>. Well, we could instead use <code>A1 const&amp;</code>, but what if <code>foo</code> takes the constructor argument by non-const reference? To make a truly generic factory function, we would have to overload factory on <code>A1&amp;</code> and on <code>A1 const&amp;</code>. That might be fine if factory takes 1 parameter type, but each additional parameter type would multiply the necessary overload set by 2. That's very quickly unmaintainable.</p> <p>rvalue references fix this problem by allowing the standard library to define a <code>std::forward</code> function that can properly forward lvalue/rvalue references. For more information about how <code>std::forward</code> works, see <a href="https://stackoverflow.com/a/3582313/530189">this excellent answer</a>.</p> <p>This enables us to define the factory function like this:</p> <pre><code>template &lt;typename T, typename A1&gt; std::unique_ptr&lt;T&gt; factory(A1&amp;&amp; a1) { return std::unique_ptr&lt;T&gt;(new T(std::forward&lt;A1&gt;(a1))); } </code></pre> <p>Now the argument's rvalue/lvalue-ness is preserved when passed to <code>T</code>'s constructor. That means that if factory is called with an rvalue, <code>T</code>'s constructor is called with an rvalue. If factory is called with an lvalue, <code>T</code>'s constructor is called with an lvalue. The improved factory function works because of one special rule:</p> <blockquote> <p>When the function parameter type is of the form <code>T&amp;&amp;</code> where <code>T</code> is a template parameter, and the function argument is an lvalue of type <code>A</code>, the type <code>A&amp;</code> is used for template argument deduction.</p> </blockquote> <p>Thus, we can use factory like so:</p> <pre><code>auto p1 = factory&lt;foo&gt;(foo()); // calls foo(foo&amp;&amp;) auto p2 = factory&lt;foo&gt;(*p1); // calls foo(foo const&amp;) </code></pre> <p><strong>Important rvalue reference properties</strong>:</p> <ul> <li>For overload resolution, <strong>lvalues prefer binding to lvalue references and rvalues prefer binding to rvalue references</strong>. Hence why temporaries prefer invoking a move constructor / move assignment operator over a copy constructor / assignment operator.</li> <li><strong>rvalue references will implicitly bind to rvalues and to temporaries that are the result of an implicit conversion</strong>. i.e. <code>float f = 0f; int&amp;&amp; i = f;</code> is well formed because float is implicitly convertible to int; the reference would be to a temporary that is the result of the conversion.</li> <li><strong>Named rvalue references are lvalues. Unnamed rvalue references are rvalues.</strong> This is important to understand why the <code>std::move</code> call is necessary in: <code>foo&amp;&amp; r = foo(); foo f = std::move(r);</code></li> </ul>
{ "question_id": 5481539, "question_date": "2011-03-30T03:29:58Z", "question_score": 1003, "tags": "c++|c++11|rvalue-reference|c++-faq|perfect-forwarding", "answer_id": 5481588, "answer_date": "2011-03-30T03:36:55.843Z", "answer_score": 801 }
Please answer the following Stack Overflow question: Title: #pragma mark in Swift? <p>In Objective C, I can use <code>#pragma mark</code> to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?</p>
<p>You can use <code>// MARK:</code></p> <hr> <p>There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than <code>#pragma mark</code> is capable of. </p>
{ "question_id": 24017316, "question_date": "2014-06-03T14:05:56.693Z", "question_score": 1003, "tags": "swift|documentation", "answer_id": 24037870, "answer_date": "2014-06-04T12:46:48.413Z", "answer_score": 1279 }
Please answer the following Stack Overflow question: Title: How would you count occurrences of a string (actually a char) within a string? <p>I am doing something where I realised I wanted to count how many <code>/</code>s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was.</p> <p>At the moment I'm going with something like:</p> <pre><code>string source = "/once/upon/a/time/"; int count = source.Length - source.Replace("/", "").Length; </code></pre> <p>But I don't like it at all, any takers?</p> <p>I don't really want to dig out <code>RegEx</code> for this, do I?</p> <p>I know my string is going to have the term I'm searching for, so you can assume that...</p> <p>Of course for strings <em>where</em> <strong>length > 1</strong>,</p> <pre><code>string haystack = "/once/upon/a/time"; string needle = "/"; int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length; </code></pre>
<p>If you're using .NET 3.5 you can do this in a one-liner with LINQ:</p> <pre><code>int count = source.Count(f =&gt; f == '/'); </code></pre> <p>If you don't want to use LINQ you can do it with:</p> <pre><code>int count = source.Split('/').Length - 1; </code></pre> <hr> <p>You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:</p> <blockquote> <p>Your original = 12s<br> source.Count = 19s<br> source.Split = 17s<br> foreach (<a href="https://stackoverflow.com/a/541976/662581">from bobwienholt's answer</a>) = 10s </p> </blockquote> <p>(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)</p>
{ "question_id": 541954, "question_date": "2009-02-12T15:57:40.907Z", "question_score": 1001, "tags": "c#|string", "answer_id": 541994, "answer_date": "2009-02-12T16:02:49.383Z", "answer_score": 1176 }
Please answer the following Stack Overflow question: Title: How to check a radio button with jQuery? <p>I try to check a radio button with jQuery. Here's my code:</p> <pre><code>&lt;form&gt; &lt;div id='type'&gt; &lt;input type='radio' id='radio_1' name='type' value='1' /&gt; &lt;input type='radio' id='radio_2' name='type' value='2' /&gt; &lt;input type='radio' id='radio_3' name='type' value='3' /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>And the JavaScript: </p> <pre><code>jQuery("#radio_1").attr('checked', true); </code></pre> <p>Doesn't work:</p> <pre><code>jQuery("input[value='1']").attr('checked', true); </code></pre> <p>Doesn't work:</p> <pre><code>jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true); </code></pre> <p>Doesn't work:</p> <p>Do you have another idea? What am I missing?</p>
<p>For versions of jQuery equal or above (>=) 1.6, use:</p> <pre><code>$("#radio_1").prop("checked", true); </code></pre> <p>For versions prior to (&lt;) 1.6, use:</p> <pre><code>$("#radio_1").attr('checked', 'checked'); </code></pre> <p><strong>Tip:</strong> You may also want to call <code>click()</code> or <code>change()</code> on the radio button afterwards. <em>See comments for more info.</em></p>
{ "question_id": 5665915, "question_date": "2011-04-14T15:47:52.363Z", "question_score": 1000, "tags": "javascript|jquery|radio-button", "answer_id": 5665942, "answer_date": "2011-04-14T15:49:39.273Z", "answer_score": 1636 }
Please answer the following Stack Overflow question: Title: Behaviour of increment and decrement operators in Python <p>How do I use pre-increment/decrement operators (<code>++</code>, <code>--</code>), just like in C++?</p> <p>Why does <code>++count</code> run, but not change the value of the variable?</p>
<p><code>++</code> is not an operator. It is two <code>+</code> operators. The <code>+</code> operator is the <strong>identity</strong> operator, which does nothing. (Clarification: the <code>+</code> and <code>-</code> unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical <code>++</code> operator to work on strings.)</p> <pre><code>++count </code></pre> <p>Parses as</p> <pre><code>+(+count) </code></pre> <p>Which translates to</p> <pre><code>count </code></pre> <p>You have to use the slightly longer <code>+=</code> operator to do what you want to do:</p> <pre><code>count += 1 </code></pre> <p>I suspect the <code>++</code> and <code>--</code> operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:</p> <ul> <li>Simpler parsing. Technically, parsing <code>++count</code> is ambiguous, as it could be <code>+</code>, <code>+</code>, <code>count</code> (two unary <code>+</code> operators) just as easily as it could be <code>++</code>, <code>count</code> (one unary <code>++</code> operator). It's not a significant syntactic ambiguity, but it does exist.</li> <li>Simpler language. <code>++</code> is nothing more than a synonym for <code>+= 1</code>. It was a shorthand invented because C compilers were stupid and didn't know how to optimize <code>a += 1</code> into the <code>inc</code> instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.</li> <li>Confusing side-effects. One common newbie error in languages with <code>++</code> operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The <a href="https://en.cppreference.com/w/c/language/operator_precedence" rel="noreferrer">precedence issues</a> of <a href="https://stackoverflow.com/a/17819123/1449799">pre-/post-increment in C</a> are pretty hairy, and incredibly easy to mess up.</li> </ul>
{ "question_id": 1485841, "question_date": "2009-09-28T07:33:19.673Z", "question_score": 1000, "tags": "python|operators|increment|decrement", "answer_id": 1485854, "answer_date": "2009-09-28T07:39:36.027Z", "answer_score": 1277 }
Please answer the following Stack Overflow question: Title: Scroll to bottom of div? <p>I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.</p> <p>I am wrapping everything in this div:</p> <pre><code>#scroll { height:400px; overflow:scroll; } </code></pre> <p>Is there a way to keep it scrolled to the bottom by default using JS?</p> <p>Is there a way to keep it scrolled to the bottom after an ajax request?</p>
<p>Here's what I use on my site:</p> <pre><code>var objDiv = document.getElementById("your_div"); objDiv.scrollTop = objDiv.scrollHeight; </code></pre>
{ "question_id": 270612, "question_date": "2008-11-06T22:37:30.420Z", "question_score": 1000, "tags": "javascript|html|ajax|chat", "answer_id": 270628, "answer_date": "2008-11-06T22:42:51.563Z", "answer_score": 1636 }
Please answer the following Stack Overflow question: Title: How do I specify unique constraint for multiple columns in MySQL? <p>I have a table:</p> <pre><code>table votes ( id, user, email, address, primary key(id), ); </code></pre> <p>Now I want to make the columns <strong>user, email, address</strong> unique (together).</p> <p>How do I do this in MySql?</p> <p>Of course the example is just... an example. So please don't worry about the semantics.</p>
<p>To add a unique constraint, you need to use two components:</p> <p><code>ALTER TABLE</code> - to change the table schema and,</p> <p><code>ADD UNIQUE</code> - to add the unique constraint.</p> <p>You then can define your new unique key with the format <code>'name'('column1', 'column2'...)</code></p> <p>So for your particular issue, you could use this command:</p> <pre><code>ALTER TABLE `votes` ADD UNIQUE `unique_index`(`user`, `email`, `address`); </code></pre>
{ "question_id": 635937, "question_date": "2009-03-11T19:12:31.843Z", "question_score": 1000, "tags": "mysql|unique-constraint|composite-key|database-table", "answer_id": 635943, "answer_date": "2009-03-11T19:14:20.480Z", "answer_score": 1640 }
Please answer the following Stack Overflow question: Title: How to remove old and unused Docker images <p>When running Docker for a long time, there are a lot of images in system. How can I remove all unused Docker images at once safety to free up the storage?</p> <p>In addition, I also want to remove images pulled months ago, which have the correct <code>TAG</code>.</p> <p>So, I'm not asking for removing untagged images only. I'm searching for a way to remove general unused images, which includes both untagged and other images such as pulled months ago with correct <code>TAG</code>.</p>
<h3>(original answer see below)</h3> <hr /> <p>Update Sept. 2016: Docker 1.13: <a href="https://github.com/docker/docker/pull/26108" rel="noreferrer">PR 26108</a> and <a href="https://github.com/docker/docker/commit/86de7c000f5d854051369754ad1769194e8dd5e1" rel="noreferrer">commit 86de7c0</a> introduce a few new commands to help facilitate visualizing how much space the docker daemon data is taking on disk and allowing for easily cleaning up &quot;unneeded&quot; excess.</p> <p><a href="https://docs.docker.com/engine/reference/commandline/system_prune/" rel="noreferrer"><strong><code>docker system prune</code></strong></a> will delete ALL dangling data (i.e. In order: containers stopped, volumes without containers and images with no containers). Even unused data, with <code>-a</code> option.</p> <p>You also have:</p> <ul> <li><a href="https://docs.docker.com/engine/reference/commandline/container_prune/" rel="noreferrer"><code>docker container prune</code></a></li> <li><a href="https://docs.docker.com/engine/reference/commandline/image_prune/" rel="noreferrer"><code>docker image prune</code></a></li> <li><a href="https://docs.docker.com/engine/reference/commandline/network_prune/" rel="noreferrer"><code>docker network prune</code></a></li> <li><a href="https://docs.docker.com/engine/reference/commandline/volume_prune/" rel="noreferrer"><code>docker volume prune</code></a></li> </ul> <p>For <em>unused</em> images, use <code>docker image prune -a</code> (for removing dangling <em>and</em> ununsed images).<br /> Warning: '<em>unused</em>' means &quot;images not referenced by any container&quot;: be careful before using <code>-a</code>.</p> <p>As illustrated in <a href="https://stackoverflow.com/users/1207596/a-l">A L</a>'s <a href="https://stackoverflow.com/a/50405599/6309">answer</a>, <code>docker system prune --all</code> will remove all <em>unused</em> images not just dangling ones... which can be a bit too much.</p> <p>Combining <code>docker xxx prune</code> with the <a href="https://docs.docker.com/engine/reference/commandline/system_prune/#filtering" rel="noreferrer"><code>--filter</code> option</a> can be a great way to limit the pruning (<a href="https://docs.docker.com/develop/sdk/#api-version-matrix" rel="noreferrer">docker SDK API 1.28 minimum, so docker 17.04+</a>)</p> <blockquote> <p>The currently supported filters are:</p> </blockquote> <ul> <li><code>until (&lt;timestamp&gt;)</code> - only remove containers, images, and networks created before given timestamp</li> <li><code>label</code> (<code>label=&lt;key&gt;</code>, <code>label=&lt;key&gt;=&lt;value&gt;</code>, <code>label!=&lt;key&gt;</code>, or <code>label!=&lt;key&gt;=&lt;value&gt;</code>) - only remove containers, images, networks, and volumes with (or <em>without</em>, in case <code>label!=...</code> is used) the specified labels.</li> </ul> <p>See &quot;<a href="https://docs.docker.com/config/pruning/#prune-images" rel="noreferrer">Prune images</a>&quot; for an example.</p> <h1>Original answer (Sep. 2016)</h1> <p>I usually do:</p> <pre><code>docker rmi $(docker images --filter &quot;dangling=true&quot; -q --no-trunc) </code></pre> <p>I have an [alias for removing those <a href="https://github.com/docker/docker/blob/634a848b8e3bdd8aed834559f3b2e0dfc7f5ae3a/man/docker-images.1.md#options" rel="noreferrer">dangling images</a>: <code>drmi</code>]<a href="https://github.com/docker/docker/blob/634a848b8e3bdd8aed834559f3b2e0dfc7f5ae3a/man/docker-images.1.md#options" rel="noreferrer">13</a></p> <blockquote> <p>The <code>dangling=true</code> filter finds unused images</p> </blockquote> <p>That way, any intermediate image no longer referenced by a labelled image is removed.</p> <p>I do the same <strong>first</strong> for <a href="https://github.com/VonC/b2d/blob/b010ab51974ac7de6162cdcbff795d7b9e84fd67/.bash_aliases#L21" rel="noreferrer">exited processes (containers)</a></p> <pre><code>alias drmae='docker rm $(docker ps -qa --no-trunc --filter &quot;status=exited&quot;)' </code></pre> <p>As <a href="https://stackoverflow.com/users/95750/haridsv">haridsv</a> points out <a href="https://stackoverflow.com/questions/32723111/how-to-remove-old-and-unused-docker-images/32723127#comment63457575_32723127">in the comments</a>:</p> <blockquote> <p>Technically, <strong>you should first clean up containers before cleaning up images, as this will catch more dangling images and less errors</strong>.</p> </blockquote> <hr /> <p><a href="https://github.com/jfrazelle" rel="noreferrer">Jess Frazelle (jfrazelle)</a> has the <a href="https://github.com/jfrazelle/dotfiles/blob/a7fd3df6ab423e6dd04f27727f653753453db837/.dockerfunc#L8-L11" rel="noreferrer">bashrc function</a>:</p> <pre><code>dcleanup(){ docker rm -v $(docker ps --filter status=exited -q 2&gt;/dev/null) 2&gt;/dev/null docker rmi $(docker images --filter dangling=true -q 2&gt;/dev/null) 2&gt;/dev/null } </code></pre> <hr /> <p>To remove old images, and not just &quot;unreferenced-dangling&quot; images, you can consider <a href="https://github.com/spotify/docker-gc" rel="noreferrer"><strong><code>docker-gc</code></strong></a>:</p> <hr /> <blockquote> <p>A simple Docker container and image garbage collection script.</p> </blockquote> <blockquote> <ul> <li>Containers that exited more than an hour ago are removed.</li> <li>Images that don't belong to any remaining container after that are removed.</li> </ul> </blockquote>
{ "question_id": 32723111, "question_date": "2015-09-22T17:23:37.043Z", "question_score": 1000, "tags": "docker|docker-image", "answer_id": 32723127, "answer_date": "2015-09-22T17:24:26.077Z", "answer_score": 1760 }
Please answer the following Stack Overflow question: Title: How can I see which Git branches are tracking which remote / upstream branch? <p>I know I can do <code>git branch --all</code>, and that shows me both local and remote branches, but it's not that useful in showing me the relationships between them.</p> <p>How do I list branches in a way that shows which local branch is tracking which remote?</p>
<p>Very much a porcelain command, not good if you want this for scripting:</p> <pre><code>git branch -vv # doubly verbose! </code></pre> <p>Note that with git 1.8.3, that upstream branch is displayed in <strong>blue</strong> (see &quot;<a href="https://stackoverflow.com/a/16162827/6309">What is this branch tracking (if anything) in git?</a>&quot;)</p> <hr /> <p>If you want clean output, see <a href="https://stackoverflow.com/a/16879922/119963">Carl Suster's answer</a> - it uses a porcelain command that I don't believe existed at the time I originally wrote this answer, so it's a bit more concise and works with branches configured for rebase, not just merge.</p>
{ "question_id": 4950725, "question_date": "2011-02-09T21:30:46.490Z", "question_score": 999, "tags": "git", "answer_id": 4952368, "answer_date": "2011-02-10T01:02:39.130Z", "answer_score": 1409 }
Please answer the following Stack Overflow question: Title: How to use Jackson to deserialise an array of objects <p>The <a href="http://jackson.codehaus.org/DataBindingDeepDive" rel="noreferrer">Jackson data binding documentation</a> indicates that Jackson supports deserialising "Arrays of all supported types" but I can't figure out the exact syntax for this.</p> <p>For a single object I would do this:</p> <pre><code>//json input { "id" : "junk", "stuff" : "things" } //Java MyClass instance = objectMapper.readValue(json, MyClass.class); </code></pre> <p>Now for an array I want to do this:</p> <pre><code>//json input [{ "id" : "junk", "stuff" : "things" }, { "id" : "spam", "stuff" : "eggs" }] //Java List&lt;MyClass&gt; entries = ? </code></pre> <p>Anyone know if there is a magic missing command? If not then what is the solution?</p>
<p>First create a mapper :</p> <pre><code>import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3 ObjectMapper mapper = new ObjectMapper(); </code></pre> <p>As Array:</p> <pre><code>MyClass[] myObjects = mapper.readValue(json, MyClass[].class); </code></pre> <p>As List:</p> <pre><code>List&lt;MyClass&gt; myObjects = mapper.readValue(jsonInput, new TypeReference&lt;List&lt;MyClass&gt;&gt;(){}); </code></pre> <p>Another way to specify the List type:</p> <pre><code>List&lt;MyClass&gt; myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class)); </code></pre>
{ "question_id": 6349421, "question_date": "2011-06-14T20:05:11.613Z", "question_score": 998, "tags": "java|json|jackson", "answer_id": 6349488, "answer_date": "2011-06-14T20:09:25.417Z", "answer_score": 2130 }
Please answer the following Stack Overflow question: Title: mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource <p>I am trying to select data from a MySQL table, but I get one of the following error messages:</p> <blockquote> <p>mysql_fetch_array() expects parameter 1 to be resource, boolean given</p> </blockquote> <p>This is my code:</p> <pre><code>$username = $_POST['username']; $password = $_POST['password']; $result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username'); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; } </code></pre>
<p>A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return <code>false</code> from their respective query functions/methods. You need to test for that error condition and handle it accordingly.</p> <p><strong><a href="http://docs.php.net/book.mysql" rel="nofollow noreferrer">mysql_ extension</a></strong>:</p> <blockquote> <p><strong>NOTE</strong> The <a href="https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php">mysql_ functions are deprecated</a> and have been removed in php version 7.</p> </blockquote> <p>Check <code>$result</code> before passing it to <code>mysql_fetch_array</code>. You'll find that it's <code>false</code> because the query failed. See the [<code>mysql_query</code>][1] documentation for possible return values and suggestions for how to deal with them.</p> <pre><code>$username = mysql_real_escape_string($_POST['username']); $password = $_POST['password']; $result = mysql_query(&quot;SELECT * FROM Users WHERE UserName LIKE '$username'&quot;); if($result === FALSE) { trigger_error(mysql_error(), E_USER_ERROR); } while($row = mysql_fetch_array($result)) { echo $row['FirstName']; } </code></pre>
{ "question_id": 2973202, "question_date": "2010-06-04T10:18:08.993Z", "question_score": 998, "tags": "php|mysql", "answer_id": 2973209, "answer_date": "2010-06-04T10:19:19.753Z", "answer_score": 678 }
Please answer the following Stack Overflow question: Title: Obfuscated C Code Contest 2006. Please explain sykes2.c <p>How does this C program work?</p> <pre><code>main(_){_^448&amp;&amp;main(-~_);putchar(--_%64?32|-~7[__TIME__-_/8%8]["&gt;'txiZ^(~z?"-48]&gt;&gt;";;;====~$::199"[_*2&amp;8|_/64]/(_&amp;2?1:8)%8&amp;1:10);} </code></pre> <p>It compiles as it is (tested on <code>gcc 4.6.3</code>). It prints the time when compiled. On my system:</p> <pre><code> !! !!!!!! !! !!!!!! !! !!!!!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!!!!! !! !! !! !! !! !!!!!! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!!!!! !! !! !! !!!!!! </code></pre> <p>Source: <a href="http://www.ioccc.org/years-spoiler.html#2006" rel="noreferrer">sykes2 - A clock in one line</a>, <a href="http://www.ioccc.org/2006/sykes2/hint.text" rel="noreferrer">sykes2 author hints</a></p> <p>Some hints: No compile warnings per default. Compiled with <code>-Wall</code>, the following warnings are emitted:</p> <pre><code>sykes2.c:1:1: warning: return type defaults to ‘int’ [-Wreturn-type] sykes2.c: In function ‘main’: sykes2.c:1:14: warning: value computed is not used [-Wunused-value] sykes2.c:1:1: warning: implicit declaration of function ‘putchar’ [-Wimplicit-function-declaration] sykes2.c:1:1: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses] sykes2.c:1:1: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses] sykes2.c:1:1: warning: control reaches end of non-void function [-Wreturn-type] </code></pre>
<p>Let's de-obfuscate it.</p> <p>Indenting:</p> <pre><code>main(_) { _^448 &amp;&amp; main(-~_); putchar(--_%64 ? 32 | -~7[__TIME__-_/8%8]["&gt;'txiZ^(~z?"-48] &gt;&gt; ";;;====~$::199"[_*2&amp;8|_/64]/(_&amp;2?1:8)%8&amp;1 : 10); } </code></pre> <p>Introducing variables to untangle this mess:</p> <pre><code>main(int i) { if(i^448) main(-~i); if(--i % 64) { char a = -~7[__TIME__-i/8%8]["&gt;'txiZ^(~z?"-48]; char b = a &gt;&gt; ";;;====~$::199"[i*2&amp;8|i/64]/(i&amp;2?1:8)%8; putchar(32 | (b &amp; 1)); } else { putchar(10); // newline } } </code></pre> <p>Note that <code>-~i == i+1</code> because of twos-complement. Therefore, we have</p> <pre><code>main(int i) { if(i != 448) main(i+1); i--; if(i % 64 == 0) { putchar('\n'); } else { char a = -~7[__TIME__-i/8%8]["&gt;'txiZ^(~z?"-48]; char b = a &gt;&gt; ";;;====~$::199"[i*2&amp;8|i/64]/(i&amp;2?1:8)%8; putchar(32 | (b &amp; 1)); } } </code></pre> <p>Now, note that <a href="https://stackoverflow.com/a/1995156/1204143"><code>a[b]</code> is the same as <code>b[a]</code></a>, and apply the <code>-~ == 1+</code> change again:</p> <pre><code>main(int i) { if(i != 448) main(i+1); i--; if(i % 64 == 0) { putchar('\n'); } else { char a = ("&gt;'txiZ^(~z?"-48)[(__TIME__-i/8%8)[7]] + 1; char b = a &gt;&gt; ";;;====~$::199"[(i*2&amp;8)|i/64]/(i&amp;2?1:8)%8; putchar(32 | (b &amp; 1)); } } </code></pre> <p>Converting the recursion to a loop and sneaking in a bit more simplification:</p> <pre><code>// please don't pass any command-line arguments main() { int i; for(i=447; i&gt;=0; i--) { if(i % 64 == 0) { putchar('\n'); } else { char t = __TIME__[7 - i/8%8]; char a = "&gt;'txiZ^(~z?"[t - 48] + 1; int shift = ";;;====~$::199"[(i*2&amp;8) | (i/64)]; if((i &amp; 2) == 0) shift /= 8; shift = shift % 8; char b = a &gt;&gt; shift; putchar(32 | (b &amp; 1)); } } } </code></pre> <p>This outputs one character per iteration. Every 64th character, it outputs a newline. Otherwise, it uses a pair of data tables to figure out what to output, and puts either character 32 (a space) or character 33 (a <code>!</code>). The first table (<code>"&gt;'txiZ^(~z?"</code>) is a set of 10 bitmaps describing the appearance of each character, and the second table (<code>";;;====~$::199"</code>) selects the appropriate bit to display from the bitmap.</p> <h3>The second table</h3> <p>Let's start by examining the second table, <code>int shift = ";;;====~$::199"[(i*2&amp;8) | (i/64)];</code>. <code>i/64</code> is the line number (6 to 0) and <code>i*2&amp;8</code> is 8 iff <code>i</code> is 4, 5, 6 or 7 mod 8.</p> <p><code>if((i &amp; 2) == 0) shift /= 8; shift = shift % 8</code> selects either the high octal digit (for <code>i%8</code> = 0,1,4,5) or the low octal digit (for <code>i%8</code> = 2,3,6,7) of the table value. The shift table ends up looking like this:</p> <pre><code>row col val 6 6-7 0 6 4-5 0 6 2-3 5 6 0-1 7 5 6-7 1 5 4-5 7 5 2-3 5 5 0-1 7 4 6-7 1 4 4-5 7 4 2-3 5 4 0-1 7 3 6-7 1 3 4-5 6 3 2-3 5 3 0-1 7 2 6-7 2 2 4-5 7 2 2-3 3 2 0-1 7 1 6-7 2 1 4-5 7 1 2-3 3 1 0-1 7 0 6-7 4 0 4-5 4 0 2-3 3 0 0-1 7 </code></pre> <p>or in tabular form</p> <pre><code>00005577 11775577 11775577 11665577 22773377 22773377 44443377 </code></pre> <p>Note that the author used the null terminator for the first two table entries (sneaky!).</p> <p>This is designed after a seven-segment display, with <code>7</code>s as blanks. So, the entries in the first table must define the segments that get lit up.</p> <h3>The first table</h3> <p><a href="http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html" rel="noreferrer"><code>__TIME__</code></a> is a special macro defined by the preprocessor. It expands to a string constant containing the time at which the preprocessor was run, in the form <code>"HH:MM:SS"</code>. Observe that it contains exactly 8 characters. Note that 0-9 have ASCII values 48 through 57 and <code>:</code> has ASCII value 58. The output is 64 characters per line, so that leaves 8 characters per character of <code>__TIME__</code>.</p> <p><code>7 - i/8%8</code> is thus the index of <code>__TIME__</code> that is presently being output (the <code>7-</code> is needed because we are iterating <code>i</code> downwards). So, <code>t</code> is the character of <code>__TIME__</code> being output.</p> <p><code>a</code> ends up equalling the following in binary, depending on the input <code>t</code>:</p> <pre><code>0 00111111 1 00101000 2 01110101 3 01111001 4 01101010 5 01011011 6 01011111 7 00101001 8 01111111 9 01111011 : 01000000 </code></pre> <p>Each number is a <em>bitmap</em> describing the segments that are lit up in our seven-segment display. Since the characters are all 7-bit ASCII, the high bit is always cleared. Thus, <code>7</code> in the segment table always prints as a blank. The second table looks like this with the <code>7</code>s as blanks:</p> <pre><code>000055 11 55 11 55 116655 22 33 22 33 444433 </code></pre> <p>So, for example, <code>4</code> is <code>01101010</code> (bits 1, 3, 5, and 6 set), which prints as</p> <pre><code>----!!-- !!--!!-- !!--!!-- !!!!!!-- ----!!-- ----!!-- ----!!-- </code></pre> <hr> <p>To show we really understand the code, let's adjust the output a bit with this table:</p> <pre><code> 00 11 55 11 55 66 22 33 22 33 44 </code></pre> <p>This is encoded as <code>"?;;?==? '::799\x07"</code>. For artistic purposes, we'll add 64 to a few of the characters (since only the low 6 bits are used, this won't affect the output); this gives <code>"?{{?}}?gg::799G"</code> (note that the 8th character is unused, so we can actually make it whatever we want). Putting our new table in the original code:</p> <pre><code>main(_){_^448&amp;&amp;main(-~_);putchar(--_%64?32|-~7[__TIME__-_/8%8]["&gt;'txiZ^(~z?"-48]&gt;&gt;"?{{?}}?gg::799G"[_*2&amp;8|_/64]/(_&amp;2?1:8)%8&amp;1:10);} </code></pre> <p>we get</p> <pre><code> !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !! </code></pre> <p>just as we expected. It's not as solid-looking as the original, which explains why the author chose to use the table he did.</p>
{ "question_id": 15393441, "question_date": "2013-03-13T18:22:49.453Z", "question_score": 998, "tags": "c|obfuscation|deobfuscation", "answer_id": 15395030, "answer_date": "2013-03-13T19:46:48.970Z", "answer_score": 1834 }
Please answer the following Stack Overflow question: Title: How can I vertically align elements in a div? <p>I have a <code>div</code> with two images and an <code>h1</code>. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be <code>absolute</code> positioned within the <code>div</code>.</p> <p>What is the CSS needed for this to work on all common browsers?</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;header&quot;&gt; &lt;img src=&quot;..&quot; &gt;&lt;/img&gt; &lt;h1&gt;testing...&lt;/h1&gt; &lt;img src=&quot;...&quot;&gt;&lt;/img&gt; &lt;/div&gt; </code></pre>
<p>Wow, this problem is popular. It's based on a misunderstanding in the <code>vertical-align</code> property. This excellent article explains it:</p> <p><a href="http://phrogz.net/CSS/vertical-align/index.html" rel="noreferrer">Understanding <code>vertical-align</code>, or &quot;How (Not) To Vertically Center Content&quot;</a> by Gavin Kistner.</p> <p><strong><a href="http://howtocenterincss.com/" rel="noreferrer">“How to center in CSS”</a></strong> is a great web tool which helps to find the necessary CSS centering attributes for different situations.</p> <hr /> <p>In a nutshell <sub><sup>(and to prevent link rot)</sup></sub>:</p> <ul> <li><strong>Inline elements</strong> (and <em>only</em> inline elements) can be vertically aligned in their context via <code>vertical-align: middle</code>. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. <a href="http://jsfiddle.net/jBthq/" rel="noreferrer">jsfiddle example</a></li> <li>For block elements, vertical alignment is harder and strongly depends on the specific situation: <ul> <li>If the inner element can have a <strong>fixed height</strong>, you can make its position <code>absolute</code> and specify its <code>height</code>, <code>margin-top</code> and <code>top</code> position. <a href="http://jsfiddle.net/YFncP/2/" rel="noreferrer">jsfiddle example</a></li> <li>If the centered element <strong>consists of a single line</strong> <em>and</em> <strong>its parent height is fixed</strong> you can simply set the container’s <code>line-height</code> to fill its height. This method is quite versatile in my experience. <a href="http://jsfiddle.net/d4zGF/" rel="noreferrer">jsfiddle example</a></li> <li>… there are more such special cases.</li> </ul> </li> </ul>
{ "question_id": 79461, "question_date": "2008-09-17T02:53:36.477Z", "question_score": 997, "tags": "html|css|vertical-alignment", "answer_id": 84616, "answer_date": "2008-09-17T15:38:49.320Z", "answer_score": 1070 }
Please answer the following Stack Overflow question: Title: Where are Docker images stored on the host machine? <p>I managed to find the containers under directory <code>/var/lib/docker/containers</code>, but I can't find the images.</p> <p>What are the directories and files under <code>/var/lib/docker</code>?</p>
<p>The contents of the <code>/var/lib/docker</code> directory vary depending on the <a href="https://github.com/docker/docker/blob/990a3e30fa66e7bd3df3c78c873c97c5b1310486/daemon/graphdriver/driver.go#L37-L43" rel="noreferrer">driver Docker is using for storage</a>. </p> <p>By default this will be <code>aufs</code> but can fall back to <code>overlay</code>, <code>overlay2</code>, <code>btrfs</code>, <code>devicemapper</code> or <code>zfs</code> depending on your kernel support. In most places this will be <code>aufs</code> but the <a href="http://developerblog.redhat.com/2014/09/30/overview-storage-scalability-docker/" rel="noreferrer">RedHats went with <code>devicemapper</code></a>.</p> <p>You can manually set the storage driver with the <a href="https://docs.docker.com/engine/reference/commandline/dockerd/#/daemon-storage-driver-option" rel="noreferrer"><code>-s</code> or <code>--storage-driver=</code></a> option to the <a href="https://docs.docker.com/engine/reference/commandline/dockerd/" rel="noreferrer">Docker daemon</a>. </p> <ul> <li><code>/var/lib/docker/{driver-name}</code> will contain the driver specific storage for contents of the images. </li> <li><code>/var/lib/docker/graph/&lt;id&gt;</code> now only contains metadata about the image, in the <code>json</code> and <code>layersize</code> files.</li> </ul> <p>In the case of <code>aufs</code>:</p> <ul> <li><code>/var/lib/docker/aufs/diff/&lt;id&gt;</code> has the file contents of the images.</li> <li><code>/var/lib/docker/repositories-aufs</code> is a JSON file containing local image information. This can be viewed with the command <code>docker images</code>.</li> </ul> <p>In the case of <code>devicemapper</code>:</p> <ul> <li><code>/var/lib/docker/devicemapper/devicemapper/data</code> stores the images</li> <li><code>/var/lib/docker/devicemapper/devicemapper/metadata</code> the metadata</li> <li>Note these files are thin provisioned "sparse" files so aren't as big as they seem.</li> </ul>
{ "question_id": 19234831, "question_date": "2013-10-07T21:08:48.880Z", "question_score": 997, "tags": "docker|docker-image", "answer_id": 25978888, "answer_date": "2014-09-22T16:31:39.593Z", "answer_score": 705 }
Please answer the following Stack Overflow question: Title: Differences between dependencyManagement and dependencies in Maven <p>What is the difference between <code>dependencyManagement</code> and <code>dependencies</code>? I have seen the docs at Apache Maven web site. It seems that a dependency defined under the <code>dependencyManagement</code> can be used in its child modules without specifying the version. </p> <p>For example:</p> <p>A parent project (Pro-par) defines a dependency under the <code>dependencyManagement</code>:</p> <pre><code>&lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; </code></pre> <p>Then in the child of Pro-par, I can use the junit:</p> <pre><code> &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>However, I wonder if it is necessary to define junit in the parent pom? Why not define it directly in the needed module?</p>
<p><a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management" rel="noreferrer">Dependency Management</a> allows to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. This is especially useful when you have <strong>a set of projects</strong> (i.e. more than one) that inherits a common parent.</p> <p>Another extremely important use case of <code>dependencyManagement</code> is the control of versions of artifacts used in transitive dependencies. This is hard to explain without an example. Luckily, this is illustrated in the documentation.</p>
{ "question_id": 2619598, "question_date": "2010-04-12T02:43:16.690Z", "question_score": 996, "tags": "maven|pom.xml|dependency-management", "answer_id": 2619732, "answer_date": "2010-04-12T03:31:11.633Z", "answer_score": 561 }
Please answer the following Stack Overflow question: Title: What is the difference between pip and conda? <p>I know <code>pip</code> is a package manager for python packages. However, I saw the installation on IPython's website use <code>conda</code> to install IPython.</p> <p>Can I use <code>pip</code> to install IPython? Why should I use <code>conda</code> as another python package manager when I already have <code>pip</code>?</p> <p>What is the difference between <code>pip</code> and <code>conda</code>?</p>
<p>Quoting from the <a href="http://web.archive.org/web/20170415041123/www.continuum.io/blog/developer-blog/python-packages-and-environments-conda" rel="noreferrer">Conda blog</a>:</p> <blockquote> <p>Having been involved in the python world for so long, we are all aware of pip, easy_install, and virtualenv, but these tools did not meet all of our specific requirements. The main problem is that they are focused around Python, neglecting non-Python library dependencies, such as HDF5, MKL, LLVM, etc., which do not have a setup.py in their source code and also do not install files into Python’s site-packages directory.</p> </blockquote> <p>So Conda is a packaging tool and installer that aims to do more than what <code>pip</code> does; handle library dependencies <em>outside</em> of the Python packages as well as the Python packages themselves. Conda also creates a virtual environment, like <code>virtualenv</code> does.</p> <p>As such, Conda should be compared to <a href="http://www.buildout.org/en/latest/" rel="noreferrer">Buildout</a> perhaps, another tool that lets you handle both Python and non-Python installation tasks.</p> <p>Because Conda introduces a new packaging format, you cannot use <code>pip</code> and Conda interchangeably; <code>pip</code> cannot install the Conda package format. You can use the two tools side by side (by installing <code>pip</code> with <code>conda install pip</code>) but they do not interoperate either.</p> <p>Since writing this answer, Anaconda has published a <a href="https://www.anaconda.com/understanding-conda-and-pip/" rel="noreferrer">new page on <em>Understanding Conda and Pip</em></a>, which echoes this as well:</p> <blockquote> <p>This highlights a key difference between conda and pip. Pip installs Python packages whereas conda installs packages which may contain software written in any language. For example, before using pip, a Python interpreter must be installed via a system package manager or by downloading and running an installer. Conda on the other hand can install Python packages as well as the Python interpreter directly.</p> </blockquote> <p>and further on</p> <blockquote> <p>Occasionally a package is needed which is not available as a conda package but is available on PyPI and can be installed with pip. In these cases, it makes sense to try to use both conda and pip.</p> </blockquote>
{ "question_id": 20994716, "question_date": "2014-01-08T11:44:44.623Z", "question_score": 995, "tags": "python|pip|ipython|package-managers|conda", "answer_id": 20994790, "answer_date": "2014-01-08T11:47:46.423Z", "answer_score": 682 }
Please answer the following Stack Overflow question: Title: What is the difference between a definition and a declaration? <p>The meaning of both eludes me.</p>
<p>A <strong><em>declaration</em></strong> introduces an identifier and describes its type, be it a type, object, or function. A declaration is <strong><em>what the compiler needs</em></strong> to accept references to that identifier. These are declarations: </p> <pre><code>extern int bar; extern int g(int, int); double f(int, double); // extern can be omitted for function declarations class foo; // no extern allowed for type declarations </code></pre> <p>A <strong><em>definition</em></strong> actually instantiates/implements this identifier. It's <strong><em>what the linker needs</em></strong> in order to link references to those entities. These are definitions corresponding to the above declarations: </p> <pre><code>int bar; int g(int lhs, int rhs) {return lhs*rhs;} double f(int i, double d) {return i+d;} class foo {}; </code></pre> <p>A definition can be used in the place of a declaration. </p> <p>An identifier can be <em>declared</em> as often as you want. Thus, the following is legal in C and C++: </p> <pre><code>double f(int, double); double f(int, double); extern double f(int, double); // the same as the two above extern double f(int, double); </code></pre> <p>However, it must be <em>defined</em> exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know <em>which</em> of the definitions to link references to and complains about duplicated symbols. </p> <hr> <p>Since the debate what is a class <em>declaration</em> vs. a class <em>definition</em> in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.<br> At 3.1/2, C++03 says:</p> <blockquote> <p>A declaration is a definition unless it [...] is a class name declaration [...].</p> </blockquote> <p>3.1/3 then gives a few examples. Amongst them:</p> <pre> [Example: [...] struct S { int a; int b; }; // defines S, S::a, and S::b [...] struct S; // declares S —end example </pre> <p>To sum it up: The C++ standard considers <code>struct x;</code> to be a <em>declaration</em> and <code>struct x {};</code> a <em>definition</em>. (In other words, <strong><em>"forward declaration" a misnomer</em></strong>, since there are no other forms of class declarations in C++.) </p> <p>Thanks to <a href="https://stackoverflow.com/users/34509/johannes-schaub-litb">litb (Johannes Schaub)</a> who dug out the actual chapter and verse in one of his answers. </p>
{ "question_id": 1410563, "question_date": "2009-09-11T12:27:12.883Z", "question_score": 995, "tags": "c|terminology|c++-faq", "answer_id": 1410632, "answer_date": "2009-09-11T12:43:03.240Z", "answer_score": 1000 }
Please answer the following Stack Overflow question: Title: How to make vim paste from (and copy to) system's clipboard? <p>Unlike other editors, vim stores copied text in its own clipboard. So, it's very hard for me to copy some text from a webpage and paste it into the current working file. It so happens I have to either open gedit or type it manually.</p> <p>Can I make vim paste from and to the system's clipboard?</p>
<p>Be aware that copying/pasting from the system clipboard <strong>will not work if <code>:echo has('clipboard')</code> returns 0</strong>. In this case, vim is not compiled with the <code>+clipboard</code> feature and you'll have to install a different version or recompile it. Some linux distros supply a minimal vim installation by default, but if you <strong>install the <code>vim-gtk</code> or <code>vim-gtk3</code> package</strong> you can get the extra features nonetheless.</p> <p>The <code>&quot;*</code> and <code>&quot;+</code> registers are for the system's clipboard (<code>:help registers</code>). Depending on your system, they may do different things. For instance, on systems that don't use X11 like OSX or Windows, the <code>&quot;*</code> register is used to read and write to the system clipboard. On X11 systems both registers can be used. See <code>:help x11-selection</code> for more details, but basically the <code>&quot;*</code> is analogous to X11's <code>_PRIMARY_</code> selection (which usually copies things you select with the mouse and pastes with the middle mouse button) and <code>&quot;+</code> is analogous to X11's <code>_CLIPBOARD_</code> selection (which is the clipboard proper).</p> <p>If all that went over your head, try using <code>&quot;*yy</code> or <code>&quot;+yy</code> to copy a line to your system's clipboard. Assuming you have the appropriate compile options, one or the other should work.</p> <p>You might like to remap this to something more convenient for you. For example, you could put <code>vnoremap &lt;C-c&gt; &quot;*y</code> in your <code>~/.vimrc</code> so that you can visually select and press <kbd>Ctrl</kbd>+<kbd>c</kbd> to yank to your system's clipboard.</p> <p>You also may want to have a look at the <code>'clipboard'</code> option described in <code>:help cb</code>. In this case you can <code>:set clipboard=unnamed</code> or <code>:set clipboard=unnamedplus</code> to make all yanking/deleting operations automatically copy to the system clipboard. This could be an inconvenience in some cases where you are storing something else in the clipboard as it will override it.</p> <p>To paste you can use <code>&quot;+p</code> or <code>&quot;*p</code> (again, depending on your system and/or desired selection) or you can map these to something else. I type them explicitly, but I often find myself in insert mode. If you're in insert mode you can still paste them with proper indentation by using <code>&lt;C-r&gt;&lt;C-p&gt;*</code> or <code>&lt;C-r&gt;&lt;C-p&gt;+</code>. See <code>:help i_CTRL-R_CTRL-P</code>.</p> <p>It's also worth mentioning vim's <code>paste</code> option (<code>:help paste</code>). This puts vim into a special <strong>&quot;paste mode&quot;</strong> that disables several other options, allowing you to easily paste into vim using your terminal emulator's or multiplexer's familiar paste shortcut. (Simply type <code>:set paste</code> to enable it, paste your content and then type <code>:set nopaste</code> to disable it.) Alternatively, you can use the <code>pastetoggle</code> option to set a keycode that toggles the mode (<code>:help pastetoggle</code>).</p> <p>I recommend using registers instead of these options, but if they are still too scary, this can be a convenient workaround while you're perfecting your vim chops.</p> <p>See <code>:help clipboard</code> for more detailed information.</p>
{ "question_id": 11489428, "question_date": "2012-07-15T04:28:19.017Z", "question_score": 994, "tags": "vim|editor|clipboard", "answer_id": 11489440, "answer_date": "2012-07-15T04:31:17.700Z", "answer_score": 1073 }
Please answer the following Stack Overflow question: Title: How to get a function name as a string? <p>How do I get a function's name as a string?</p> <pre><code>def foo(): pass &gt;&gt;&gt; name_of(foo) &quot;foo&quot; </code></pre>
<pre><code>my_function.__name__ </code></pre> <p>Using <code>__name__</code> is the preferred method as it applies uniformly. Unlike <code>func_name</code>, it works on built-in functions as well:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.time.func_name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' &gt;&gt;&gt; time.time.__name__ 'time' </code></pre> <p>Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a <code>__name__</code> attribute too, so you only have remember one special name.</p>
{ "question_id": 251464, "question_date": "2008-10-30T19:38:24.750Z", "question_score": 994, "tags": "python|string|function", "answer_id": 255297, "answer_date": "2008-11-01T00:07:17.713Z", "answer_score": 1282 }
Please answer the following Stack Overflow question: Title: How can one change the timestamp of an old commit in Git? <p>The answers to <a href="https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git">How to modify existing, unpushed commits?</a> describe a way to amend previous commit messages that haven't yet been pushed upstream. The new messages inherit the timestamps of the original commits. This seems logical, but is there a way to also re-set the times?</p>
<p>Use <code>git filter-branch</code> with an env filter that sets <code>GIT_AUTHOR_DATE</code> and <code>GIT_COMMITTER_DATE</code> for the specific hash of the commit you're looking to fix.</p> <p>This will invalidate that and all future hashes.</p> <p><strong>Example:</strong></p> <p>If you wanted to change the <a href="https://www.kernel.org/pub/software/scm/git/docs/git-commit.html#_date_formats" rel="noreferrer">dates</a> of commit <code>119f9ecf58069b265ab22f1f97d2b648faf932e0</code>, you could do so with something like this:</p> <pre><code>git filter-branch --env-filter \ 'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ] then export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800" export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700" fi' </code></pre>
{ "question_id": 454734, "question_date": "2009-01-18T06:13:46.923Z", "question_score": 993, "tags": "git|timestamp|commit|git-rewrite-history", "answer_id": 454750, "answer_date": "2009-01-18T06:48:07.273Z", "answer_score": 625 }
Please answer the following Stack Overflow question: Title: How to retrieve a single file from a specific revision in Git? <p>I have a Git repository and I'd like to see how some files looked a few months ago. I found the revision at that date; it's <code>27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8</code>. I need to see what one file looks like, and also save it as a ("new") file.</p> <p>I managed to see the file using <code>gitk</code>, but it doesn't have an option to save it. I tried with command-line tools, the closest I got was:</p> <pre><code>git-show 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8 my_file.txt </code></pre> <p>However, this command shows a diff, and not the file contents. I know I can later use something like <code>PAGER=cat</code> and redirect output to a file, but I don't know how to get to the actual file content.</p> <p>Basically, I'm looking for something like <strong>svn cat</strong>.</p>
<h2>Using <code>git show</code></h2> <p>To complete your own answer, the syntax is indeed</p> <pre><code>git show object git show $REV:$FILE git show somebranch:from/the/root/myfile.txt git show HEAD^^^:test/test.py </code></pre> <p>The command takes the usual style of revision, meaning you can use any of the following:</p> <ol> <li>branch name (as <a href="https://stackoverflow.com/review/suggested-edits/3041393">suggested</a> by <a href="https://stackoverflow.com/users/17708/ash">ash</a>)</li> <li><code>HEAD</code> + x number of <code>^</code> characters</li> <li>The SHA1 hash of a given revision</li> <li>The first few (maybe 5) characters of a given SHA1 hash</li> </ol> <p><strong>Tip</strong> It's important to remember that when using &quot;<code>git show</code>&quot;, <strong>always specify a path from the root of the repository</strong>, not your current directory position.</p> <p>(Although <a href="https://stackoverflow.com/users/179675/mike-morearty">Mike Morearty</a> mentions that, at least with git 1.7.5.4, you can specify a relative path by putting &quot;<code>./</code>&quot; at the beginning of the path. For example:</p> <pre><code>git show HEAD^^:./test.py </code></pre> <p>)</p> <h2>Using <code>git restore</code></h2> <p>With Git 2.23+ (August 2019), you can also use <strong><a href="https://git-scm.com/docs/git-restore" rel="noreferrer"><code>git restore</code></a></strong> which replaces <a href="https://stackoverflow.com/a/57066202/6309">the confusing <code>git checkout</code> command</a></p> <pre><code>git restore -s &lt;SHA1&gt; -- afile git restore -s somebranch -- afile </code></pre> <p>That would restore on the working tree only the file as present in the <strong>&quot;source&quot; (<code>-s</code>)</strong> commit SHA1 or branch <code>somebranch</code>.<br /> To restore also the index:</p> <pre><code>git restore -s &lt;SHA1&gt; -SW -- afile </code></pre> <p>(<code>-SW</code>: short for <code>--staged --worktree</code>)</p> <hr /> <p>As noted in <a href="https://stackoverflow.com/questions/610208/how-to-retrieve-a-single-file-from-a-specific-revision-in-git/610315#comment120557219_610315">the comments</a> by <a href="https://stackoverflow.com/users/3249197/starwarswii">starwarswii</a></p> <blockquote> <p>It lets you pipe the contents into a file, which is great if you want to just quickly compare files from a commit.</p> <p>E.g. you can do:</p> <pre><code>git show 1234:path/to/file.txt &gt; new.txt git show 1234~:path/to/file.txt &gt; old.txt </code></pre> <p>then compare them.</p> </blockquote> <hr /> <h2>Using low-level git plumbing commands</h2> <p>Before git1.5.x, this was done with some plumbing:</p> <p><code>git ls-tree &lt;rev&gt;</code><br /> show a list of one or more 'blob' objects within a commit</p> <p><code>git cat-file blob &lt;file-SHA1&gt;</code><br /> cat a file as it has been committed within a specific revision (similar to svn cat). use <code>git ls-tree</code> to retrieve the value of a given file-sha1</p> <pre><code>git cat-file -p $(git-ls-tree $REV $file | cut -d &quot; &quot; -f 3 | cut -f 1):: </code></pre> <p><code>git-ls-tree</code> lists the object ID for <code>$file</code> in revision <code>$REV</code>, this is cut out of the output and used as an argument to <code>git-cat-file</code>, which should really be called <code>git-cat-object</code>, and simply dumps that object to <code>stdout</code>.</p> <hr /> <p>Note: since Git 2.11 (Q4 2016), you can apply a content filter to the <code>git cat-file</code> output.</p> <p>See <a href="https://github.com/git/git/commit/321459439e19517c412cab1cfbb64a2749f272c9" rel="noreferrer">commit 3214594</a>, <a href="https://github.com/git/git/commit/7bcf341453572a227036afec76bdab451b798870" rel="noreferrer">commit 7bcf341</a> (09 Sep 2016), <a href="https://github.com/git/git/commit/7bcf341453572a227036afec76bdab451b798870" rel="noreferrer">commit 7bcf341</a> (09 Sep 2016), and <a href="https://github.com/git/git/commit/b9e62f60115c75c5be5de593862925c8b8d7e683" rel="noreferrer">commit b9e62f6</a>, <a href="https://github.com/git/git/commit/16dcc2992b80d30f99c41fd7cc858e9d1c9dbca3" rel="noreferrer">commit 16dcc29</a> (24 Aug 2016) by <a href="https://github.com/dscho" rel="noreferrer">Johannes Schindelin (<code>dscho</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/7889ed25ac709624446b0b4d887dd3633e81f44a" rel="noreferrer">commit 7889ed2</a>, 21 Sep 2016)</sup></p> <pre><code>git config diff.txt.textconv &quot;tr A-Za-z N-ZA-Mn-za-m &lt;&quot; git cat-file --textconv --batch </code></pre> <p>Note: &quot;<code>git cat-file --textconv</code>&quot; started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)</p> <p>See <a href="https://github.com/git/git/commit/cc0ea7c9e5c3d3bf9623415737b595c9d26b9b6d" rel="noreferrer">commit cc0ea7c</a> (21 Sep 2017) by <a href="https://github.com/peff" rel="noreferrer">Jeff King (<code>peff</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/bfbc2fccfdff0fe189337de67e16fc132b8ee2a5" rel="noreferrer">commit bfbc2fc</a>, 28 Sep 2017)</sup></p>
{ "question_id": 610208, "question_date": "2009-03-04T11:43:13.107Z", "question_score": 993, "tags": "git|single-file", "answer_id": 610315, "answer_date": "2009-03-04T12:22:46.363Z", "answer_score": 914 }
Please answer the following Stack Overflow question: Title: Writing a pandas DataFrame to CSV file <p>I have a dataframe in pandas which I would like to write to a CSV file.</p> <p>I am doing this using:</p> <pre><code>df.to_csv('out.csv') </code></pre> <p>And getting the following error:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) </code></pre> <ul> <li>Is there any way to get around this easily (i.e. I have unicode characters in my data frame)?</li> <li>And is there a way to write to a tab delimited file instead of a CSV using e.g. a 'to-tab' method (that I don't think exists)?</li> </ul>
<p>To delimit by a tab you can use the <code>sep</code> argument of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html"><code>to_csv</code></a>:</p> <pre><code>df.to_csv(file_name, sep='\t') </code></pre> <p>To use a specific encoding (e.g. 'utf-8') use the <code>encoding</code> argument:</p> <pre><code>df.to_csv(file_name, sep='\t', encoding='utf-8') </code></pre>
{ "question_id": 16923281, "question_date": "2013-06-04T16:46:56.137Z", "question_score": 992, "tags": "python|csv|pandas|dataframe", "answer_id": 16923367, "answer_date": "2013-06-04T16:52:17.853Z", "answer_score": 1356 }
Please answer the following Stack Overflow question: Title: How to configure port for a Spring Boot application <p>How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.</p>
<p>As <a href="http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-change-the-http-port" rel="noreferrer">said in docs</a> either set <code>server.port</code> as system property using command line option to jvm <code>-Dserver.port=8090</code> or add <code>application.properties</code> in <code>/src/main/resources/</code> with</p> <pre><code>server.port=8090 </code></pre> <p>For a random port use:</p> <pre><code>server.port=0 </code></pre> <p>Similarly add <code>application.yml</code> in <code>/src/main/resources/</code> with:</p> <pre><code>server: port: 8090 </code></pre>
{ "question_id": 21083170, "question_date": "2014-01-13T02:59:47.077Z", "question_score": 992, "tags": "java|spring|spring-boot|server|port", "answer_id": 21083284, "answer_date": "2014-01-13T03:14:01.850Z", "answer_score": 1476 }
Please answer the following Stack Overflow question: Title: How to reference a method in javadoc? <p>How can I use the <code>@link</code> tag to link to a method?</p> <p>I want to change:</p> <pre><code>/** * Returns the Baz object owned by the Bar object owned by Foo owned by this. * A convenience method, equivalent to getFoo().getBar().getBaz() * @return baz */ public Baz fooBarBaz() </code></pre> <p><strong>to:</strong></p> <pre><code>/** * Returns the Baz object owned by the Bar object owned by Foo owned by this. * A convenience method, equivalent to {@link getFoo()}.{@link getBar()}.{@link getBaz()} * @return baz */ public Baz fooBarBaz() </code></pre> <p>but I don't know how to format the <code>@link</code> tag correctly.</p>
<p>You will find much information about JavaDoc at the <em><a href="https://docs.oracle.com/en/java/javase/17/docs/specs/javadoc/doc-comment-spec.html" rel="noreferrer">Documentation Comment Specification for the Standard Doclet</a></em>, including the information on the</p> <blockquote> <p><strong><a href="https://docs.oracle.com/en/java/javase/17/docs/specs/javadoc/doc-comment-spec.html#link" rel="noreferrer">{@link module/package.class#member label}</a></strong></p> </blockquote> <p>tag (that you are looking for). The corresponding example from the documentation is as follows</p> <blockquote> <p>For example, here is a comment that refers to the getComponentAt(int, int) method:</p> <p><code>Use the {@link #getComponentAt(int, int) getComponentAt} method.</code></p> </blockquote> <p>The <code>module/package.class</code> part can be ommited if the referred method is in the current class.</p> <hr /> <p>Other useful links about JavaDoc are:</p> <ul> <li><a href="https://docs.oracle.com/en/java/javase/17/docs/specs/man/javadoc.html" rel="noreferrer">JDK 17 Tool Specifications - The javadoc Command</a></li> <li><a href="https://docs.oracle.com/en/java/javase/17/javadoc/javadoc.html" rel="noreferrer">JavaDoc Guide</a></li> <li><a href="https://www.oracle.com/de/technical-resources/articles/java/javadoc-tool.html" rel="noreferrer">How to Write Doc Comments for the Javadoc Tool</a></li> </ul>
{ "question_id": 5915992, "question_date": "2011-05-06T19:15:05.127Z", "question_score": 992, "tags": "java|hyperlink|javadoc", "answer_id": 5916098, "answer_date": "2011-05-06T19:25:02.570Z", "answer_score": 1267 }
Please answer the following Stack Overflow question: Title: How do I create a transparent Activity on Android? <p>I want to create a transparent Activity on top of another activity.</p> <p>How can I achieve this?</p>
<p>Add the following style in your <code>res/values/styles.xml</code> file (if you don’t have one, create it.) Here’s a complete file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;style name="Theme.Transparent" parent="android:Theme"&gt; &lt;item name="android:windowIsTranslucent"&gt;true&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@android:color/transparent&lt;/item&gt; &lt;item name="android:windowContentOverlay"&gt;@null&lt;/item&gt; &lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt; &lt;item name="android:windowIsFloating"&gt;true&lt;/item&gt; &lt;item name="android:backgroundDimEnabled"&gt;false&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>(The value <code>@color/transparent</code> is the color value <code>#00000000</code> which I put in the <code>res/values/color.xml</code> file. You can also use <code>@android:color/transparent</code> in later Android versions.)</p> <p>Then apply the style to your activity, for example:</p> <pre><code>&lt;activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent"&gt; ... &lt;/activity&gt; </code></pre>
{ "question_id": 2176922, "question_date": "2010-02-01T13:28:02.957Z", "question_score": 992, "tags": "android|android-activity|transparent", "answer_id": 2700683, "answer_date": "2010-04-23T17:37:26.347Z", "answer_score": 1464 }
Please answer the following Stack Overflow question: Title: In CSS Flexbox, why are there no "justify-items" and "justify-self" properties? <p>Consider the main axis and cross axis of a flex container:</p> <p><a href="https://i.stack.imgur.com/9Oxw7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Oxw7.png" alt="An illustration of the various directions and sizing terms as applied to a row flex container" /></a> <sub>Source: <a href="https://www.w3.org/TR/css-flexbox-1/#box-model" rel="noreferrer">W3C</a></sub></p> <p>To align flex items along the main axis there is one property:</p> <ul> <li><a href="https://www.w3.org/TR/css-flexbox-1/#justify-content-property" rel="noreferrer"><code>justify-content</code></a></li> </ul> <p>To align flex items along the cross axis there are three properties:</p> <ul> <li><a href="https://www.w3.org/TR/css-flexbox-1/#align-content-property" rel="noreferrer"><code>align-content</code></a></li> <li><a href="https://www.w3.org/TR/css-flexbox-1/#align-items-property" rel="noreferrer"><code>align-items</code></a></li> <li><a href="https://www.w3.org/TR/css-flexbox-1/#align-items-property" rel="noreferrer"><code>align-self</code></a></li> </ul> <p>In the image above, the main axis is horizontal and the cross axis is vertical. These are the default directions of a flex container.</p> <p>However, these directions can be easily interchanged with the <a href="https://www.w3.org/TR/css-flexbox-1/#propdef-flex-direction" rel="noreferrer"><code>flex-direction</code></a> property.</p> <pre><code>/* main axis is horizontal, cross axis is vertical */ flex-direction: row; flex-direction: row-reverse; /* main axis is vertical, cross axis is horizontal */ flex-direction: column; flex-direction: column-reverse; </code></pre> <p>(The cross axis is always perpendicular to the main axis.)</p> <p>My point in describing how the axes' work is that there doesn't seem to be anything special about either direction. Main axis, cross axis, they're both equal in terms of importance and <code>flex-direction</code> makes it easy to switch back and forth.</p> <p><em>So why does the cross axis get two additional alignment properties?</em></p> <p><em>Why are <code>align-content</code> and <code>align-items</code> consolidated into one property for the main axis?</em></p> <p><em>Why does the main axis not get a <code>justify-self</code> property?</em></p> <hr /> <p>Scenarios where these properties would be useful:</p> <ul> <li><p>placing a flex item in the corner of the flex container<br> <code>#box3 { align-self: flex-end; justify-self: flex-end; }</code></p> </li> <li><p>making a group of flex items align-right (<code>justify-content: flex-end</code>) but have the first item align left (<code>justify-self: flex-start</code>)</p> </li> </ul> <p><em>Consider a header section with a group of nav items and a logo. With <code>justify-self</code> the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly (&quot;flexes&quot;) to different screen sizes.</em></p> <ul> <li>in a row of three flex items, affix the middle item to the center of the container (<code>justify-content: center</code>) and align the adjacent items to the container edges (<code>justify-self: flex-start</code> and <code>justify-self: flex-end</code>).</li> </ul> <p><em>Note that values <code>space-around</code> and <code>space-between</code> on <code>justify-content</code> property will not keep the middle item centered about the container if the adjacent items have different widths.</em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { display: flex; justify-content: space-between; background-color: lightyellow; } .box { height: 50px; width: 75px; background-color: springgreen; } .box1 { width: 100px; } .box3 { width: 200px; } #center { text-align: center; margin-bottom: 5px; } #center &gt; span { background-color: aqua; padding: 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="center"&gt; &lt;span&gt;TRUE CENTER&lt;/span&gt; &lt;/div&gt; &lt;div id="container"&gt; &lt;div class="box box1"&gt;&lt;/div&gt; &lt;div class="box box2"&gt;&lt;/div&gt; &lt;div class="box box3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p&gt;note that the middlebox will only be truly centered if adjacent boxes are equal width&lt;/p&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/7an37m20/12/" rel="noreferrer">jsFiddle version</a></p> <hr /> <p>As of this writing, there is no mention of <code>justify-self</code> or <code>justify-items</code> in the <a href="https://www.w3.org/TR/css-flexbox-1/" rel="noreferrer">flexbox spec</a>.</p> <p>However, in the <a href="http://www.w3.org/TR/css-align-3/" rel="noreferrer">CSS Box Alignment Module</a>, which is the W3C's unfinished proposal to establish a common set of alignment properties for use across all box models, there is this:</p> <p><a href="https://i.stack.imgur.com/uu2tP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uu2tP.png" alt="enter image description here" /></a>                                                                                                                                                    <sub>Source: <a href="https://www.w3.org/TR/css3-align/#overview" rel="noreferrer">W3C</a></sub></p> <p>You'll notice that <code>justify-self</code> and <code>justify-items</code> are being considered... <em>but not for flexbox</em>.</p> <hr /> <p>I'll end by reiterating the main question:</p> <blockquote> <p>Why are there no &quot;justify-items&quot; and &quot;justify-self&quot; properties?</p> </blockquote>
<h2>Methods for Aligning Flex Items along the Main Axis</h2> <p>As stated in the question:</p> <blockquote> <p>To align flex items along the main axis there is one property: <a href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property" rel="noreferrer"><code>justify-content</code></a></p> <p>To align flex items along the cross axis there are three properties: <a href="http://www.w3.org/TR/css-flexbox-1/#align-content-property" rel="noreferrer"><code>align-content</code></a>, <a href="http://www.w3.org/TR/css-flexbox-1/#align-items-property" rel="noreferrer"><code>align-items</code> and <code>align-self</code></a>.</p> </blockquote> <p>The question then asks:</p> <blockquote> <p>Why are there no <code>justify-items</code> and <code>justify-self</code> properties?</p> </blockquote> <p>One answer may be: <em>Because they're not necessary.</em></p> <p>The <a href="http://www.w3.org/TR/css-flexbox-1/" rel="noreferrer">flexbox specification</a> provides <em>two</em> methods for aligning flex items along the main axis:</p> <ol> <li>The <code>justify-content</code> keyword property, and</li> <li><a href="http://www.w3.org/TR/css-flexbox-1/#auto-margins" rel="noreferrer"><code>auto</code> margins</a></li> </ol> <hr> <p><em><h2>justify-content</h2></em></p> <p>The <a href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property" rel="noreferrer"><code>justify-content</code></a> property aligns flex items along the main axis of the flex container. </p> <p>It is applied to the flex container but only affects flex items. </p> <p>There are five alignment options:</p> <ul> <li><p><strong><code>flex-start</code></strong> ~ Flex items are packed toward the start of the line.</p> <p><a href="https://i.stack.imgur.com/YOzeU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YOzeU.png" alt="enter image description here"></a></p></li> <li><p><strong><code>flex-end</code></strong> ~ Flex items are packed toward the end of the line.</p> <p><a href="https://i.stack.imgur.com/13Z1u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/13Z1u.png" alt="enter image description here"></a></p></li> <li><p><strong><code>center</code></strong> ~ Flex items are packed toward the center of the line.</p> <p><a href="https://i.stack.imgur.com/oKi7M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oKi7M.png" alt="enter image description here"></a></p></li> <li><p><strong><code>space-between</code></strong> ~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on <a href="http://www.w3.org/TR/css-flexbox-1/#flex-direction-property" rel="noreferrer"><code>flex-direction</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/direction" rel="noreferrer">writing mode</a> (<code>ltr</code> or <code>rtl</code>).</p> <p><a href="https://i.stack.imgur.com/0mQqd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0mQqd.png" alt="enter image description here"></a></p></li> <li><p><strong><code>space-around</code></strong> ~ Same as <code>space-between</code> except with half-size spaces on both ends.</p> <p><a href="https://i.stack.imgur.com/u4BH6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u4BH6.png" alt="enter image description here"></a></p></li> </ul> <hr> <h2>Auto Margins</h2> <p>With <a href="http://www.w3.org/TR/css-flexbox-1/#auto-margins" rel="noreferrer"><code>auto</code> margins</a>, flex items can be centered, spaced away or packed into sub-groups.</p> <p>Unlike <code>justify-content</code>, which is applied to the flex container, <code>auto</code> margins go on flex items.</p> <p>They work by consuming all free space in the specified direction.</p> <hr> <h3>Align group of flex items to the right, but first item to the left</h3> <p>Scenario from the question:</p> <blockquote> <ul> <li><p>making a group of flex items align-right (<code>justify-content: flex-end</code>) but have the first item align left (<code>justify-self: flex-start</code>)</p> <p><em>Consider a header section with a group of nav items and a logo. With <code>justify-self</code> the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.</em></p></li> </ul> </blockquote> <p><a href="https://i.stack.imgur.com/D3Vnv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/D3Vnv.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Um8DM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Um8DM.png" alt="enter image description here"></a></p> <hr> <p><strong><em>Other useful scenarios:</em></strong></p> <p><a href="https://i.stack.imgur.com/qLzgU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qLzgU.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/HtaOc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HtaOc.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/M2WkZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M2WkZ.png" alt="enter image description here"></a></p> <hr> <h3>Place a flex item in the corner</h3> <p>Scenario from the question:</p> <blockquote> <ul> <li>placing a flex item in a corner <code>.box { align-self: flex-end; justify-self: flex-end; }</code></li> </ul> </blockquote> <p><a href="https://i.stack.imgur.com/BtbfK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BtbfK.png" alt="enter image description here"></a></p> <hr> <h3>Center a flex item vertically and horizontally</h3> <p><a href="https://i.stack.imgur.com/lV9a0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lV9a0.png" alt="enter image description here"></a></p> <p><code>margin: auto</code> is an alternative to <code>justify-content: center</code> and <code>align-items: center</code>.</p> <p>Instead of this code on the flex container:</p> <pre><code>.container { justify-content: center; align-items: center; } </code></pre> <p>You can use this on the flex item:</p> <pre><code>.box56 { margin: auto; } </code></pre> <p>This alternative is useful when <a href="https://stackoverflow.com/q/33454533/3597276"><strong>centering a flex item that overflows the container</strong></a>.</p> <hr> <h3>Center a flex item, and center a second flex item between the first and the edge</h3> <p>A flex container aligns flex items by distributing free space.</p> <p>Hence, in order to create <em>equal balance</em>, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.</p> <p>In the examples below, invisible third flex items (boxes 61 &amp; 68) are introduced to balance out the "real" items (box 63 &amp; 66).</p> <p><a href="https://i.stack.imgur.com/3IeTy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3IeTy.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/BmtRt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BmtRt.png" alt="enter image description here"></a></p> <p>Of course, this method is nothing great in terms of semantics.</p> <p>Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: <strong><a href="https://stackoverflow.com/q/36191516/3597276">Center and bottom-align flex items</a></strong></p> <p><em>NOTE: The examples above will only work &ndash; in terms of true centering &ndash; when the outermost items are equal height/width. When flex items are different lengths, see next example.</em></p> <hr> <h3>Center a flex item when adjacent items vary in size</h3> <p>Scenario from the question:</p> <blockquote> <ul> <li><p>in a row of three flex items, affix the middle item to the center of the container (<code>justify-content: center</code>) and align the adjacent items to the container edges (<code>justify-self: flex-start</code> and <code>justify-self: flex-end</code>). </p> <p><em>Note that values <code>space-around</code> and <code>space-between</code> on <code>justify-content</code> property will not keep the middle item centered in relation to the container if the adjacent items have different widths (<a href="http://jsfiddle.net/7an37m20/12/" rel="noreferrer">see demo</a>).</em></p></li> </ul> </blockquote> <p>As noted, unless all flex items are of equal width or height (depending on <code>flex-direction</code>), the middle item cannot be truly centered. This problem makes a strong case for a <code>justify-self</code> property (designed to handle the task, of course).</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { display: flex; justify-content: space-between; background-color: lightyellow; } .box { height: 50px; width: 75px; background-color: springgreen; } .box1 { width: 100px; } .box3 { width: 200px; } #center { text-align: center; margin-bottom: 5px; } #center &gt; span { background-color: aqua; padding: 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="center"&gt; &lt;span&gt;TRUE CENTER&lt;/span&gt; &lt;/div&gt; &lt;div id="container"&gt; &lt;div class="box box1"&gt;&lt;/div&gt; &lt;div class="box box2"&gt;&lt;/div&gt; &lt;div class="box box3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;p&gt;The middle box will be truly centered only if adjacent boxes are equal width.&lt;/p&gt;</code></pre> </div> </div> </p> <p><em>Here are two methods for solving this problem:</em></p> <p><strong><em>Solution #1: Absolute Positioning</em></strong></p> <p>The flexbox spec allows for <a href="http://www.w3.org/TR/css-flexbox-1/#abspos-items" rel="noreferrer">absolute positioning of flex items</a>. This allows for the middle item to be perfectly centered regardless of the size of its siblings.</p> <p>Just keep in mind that, like all absolutely positioned elements, the items are removed from the <a href="https://www.w3.org/TR/CSS22/visuren.html#normal-flow" rel="noreferrer">document flow</a>. This means they don't take up space in the container and can overlap their siblings. </p> <p>In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with <code>justify-content: center</code> and absolutely position the outer items.</p> <p><a href="https://i.stack.imgur.com/U1eLb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U1eLb.png" alt="enter image description here"></a></p> <p><strong><em>Solution #2: Nested Flex Containers (no absolute positioning)</em></strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: flex; } .box { flex: 1; display: flex; justify-content: center; } .box71 &gt; span { margin-right: auto; } .box73 &gt; span { margin-left: auto; } /* non-essential */ .box { align-items: center; border: 1px solid #ccc; background-color: lightgreen; height: 40px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="box box71"&gt;&lt;span&gt;71 short&lt;/span&gt;&lt;/div&gt; &lt;div class="box box72"&gt;&lt;span&gt;72 centered&lt;/span&gt;&lt;/div&gt; &lt;div class="box box73"&gt;&lt;span&gt;73 loooooooooooooooong&lt;/span&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Here's how it works:</p> <ul> <li>The top-level div (<code>.container</code>) is a flex container.</li> <li>Each child div (<code>.box</code>) is now a flex item.</li> <li>Each <code>.box</code> item is given <code>flex: 1</code> in order to distribute container space equally.</li> <li>Now the items are consuming all space in the row and are equal width.</li> <li>Make each item a (nested) flex container and add <code>justify-content: center</code>.</li> <li>Now each <code>span</code> element is a centered flex item.</li> <li>Use flex <code>auto</code> margins to shift the outer <code>span</code>s left and right.</li> </ul> <p>You could also forgo <code>justify-content</code> and use <code>auto</code> margins exclusively.</p> <p>But <code>justify-content</code> can work here because <code>auto</code> margins always have priority. From the spec:</p> <blockquote> <p><a href="https://www.w3.org/TR/css-flexbox-1/#auto-margins" rel="noreferrer"><strong>8.1. Aligning with <code>auto</code> margins</strong></a></p> <p>Prior to alignment via <code>justify-content</code> and <code>align-self</code>, any positive free space is distributed to auto margins in that dimension.</p> </blockquote> <hr> <p><em><h3>justify-content: space-same (concept)</h3></em></p> <p>Going back to <a href="https://stackoverflow.com/a/33856609/3597276"><code>justify-content</code></a> for a minute, here's an idea for one more option.</p> <ul> <li><strong><code>space-same</code></strong> ~ A hybrid of <code>space-between</code> and <code>space-around</code>. Flex items are evenly spaced (like <code>space-between</code>), except instead of half-size spaces on both ends (like <code>space-around</code>), there are full-size spaces on both ends.</li> </ul> <p>This layout can be achieved with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Abefore" rel="noreferrer"><code>::before</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Aafter" rel="noreferrer"><code>::after</code></a> pseudo-elements on the flex container.</p> <p><a href="https://i.stack.imgur.com/Jjw9w.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jjw9w.png" alt="enter image description here"></a></p> <p><em><sup>(credit: <a href="https://stackoverflow.com/a/34455480/3597276">@oriol</a> for the code, and <a href="https://stackoverflow.com/users/3183756/crl">@crl</a> for the label)</sup></em></p> <p><strong>UPDATE:</strong> Browsers have begun implementing <strong><code>space-evenly</code></strong>, which accomplishes the above. See this post for details: <a href="https://stackoverflow.com/q/45134400/3597276">Equal space between flex items</a></p> <hr> <p><a href="http://jsfiddle.net/mz1ft6jx/8/" rel="noreferrer"><strong>PLAYGROUND</strong></a> (includes code for all examples above)</p>
{ "question_id": 32551291, "question_date": "2015-09-13T15:30:27.517Z", "question_score": 992, "tags": "css|flexbox|language-lawyer|w3c", "answer_id": 33856609, "answer_date": "2015-11-22T15:37:55.153Z", "answer_score": 1772 }
Please answer the following Stack Overflow question: Title: Why dict.get(key) instead of dict[key]? <p>Today, I came across the <code>dict</code> method <code>get</code> which, given a key in the dictionary, returns the associated value.</p> <p>For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do <code>dict[key]</code>, and it returns the same thing:</p> <pre><code>dictionary = {"Name": "Harry", "Age": 17} dictionary["Name"] dictionary.get("Name") </code></pre>
<p>It allows you to provide a default value if the key is missing:</p> <pre><code>dictionary.get("bogus", default_value) </code></pre> <p>returns <code>default_value</code> (whatever you choose it to be), whereas</p> <pre><code>dictionary["bogus"] </code></pre> <p>would raise a <code>KeyError</code>. </p> <p>If omitted, <code>default_value</code> is <code>None</code>, such that</p> <pre><code>dictionary.get("bogus") # &lt;-- No default specified -- defaults to None </code></pre> <p>returns <code>None</code> just like </p> <pre><code>dictionary.get("bogus", None) </code></pre> <p>would. </p>
{ "question_id": 11041405, "question_date": "2012-06-14T21:10:39.030Z", "question_score": 991, "tags": "python|dictionary", "answer_id": 11041421, "answer_date": "2012-06-14T21:12:12.963Z", "answer_score": 1457 }
Please answer the following Stack Overflow question: Title: How to convert a Java 8 Stream to an Array? <p>What is the easiest/shortest way to convert a Java 8 <code>Stream</code> into an array?</p>
<p>The easiest method is to use the <code>toArray(IntFunction&lt;A[]&gt; generator)</code> method with an array constructor reference. This is suggested in the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-" rel="noreferrer">API documentation for the method</a>.</p> <pre><code>String[] stringArray = stringStream.toArray(String[]::new); </code></pre> <p>What it does is find a method that takes in an integer (the size) as argument, and returns a <code>String[]</code>, which is exactly what (one of the overloads of) <code>new String[]</code> does.</p> <p>You could also write your own <code>IntFunction</code>:</p> <pre><code>Stream&lt;String&gt; stringStream = ...; String[] stringArray = stringStream.toArray(size -&gt; new String[size]); </code></pre> <p>The purpose of the <code>IntFunction&lt;A[]&gt; generator</code> is to convert an integer, the size of the array, to a new array.</p> <p>Example code:</p> <pre><code>Stream&lt;String&gt; stringStream = Stream.of("a", "b", "c"); String[] stringArray = stringStream.toArray(size -&gt; new String[size]); Arrays.stream(stringArray).forEach(System.out::println); </code></pre> <p>Prints:</p> <pre><code>a b c </code></pre>
{ "question_id": 23079003, "question_date": "2014-04-15T09:00:13.977Z", "question_score": 991, "tags": "java|arrays|java-8|java-stream", "answer_id": 23079174, "answer_date": "2014-04-15T09:07:26.847Z", "answer_score": 1494 }
Please answer the following Stack Overflow question: Title: What do 3 dots next to a parameter type mean in Java? <p>What do the 3 dots following <code>String</code> in the following method mean?</p> <pre><code>public void myMethod(String... strings) { // method body } </code></pre>
<p>It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.</p> <p>See the &quot;Arbitrary Number of Arguments&quot; section here: <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs" rel="noreferrer">http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs</a></p> <p>In your example, you could call it as any of the following:</p> <pre><code>myMethod(); // Likely useless, but possible myMethod(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;); myMethod(&quot;solo&quot;); myMethod(new String[]{&quot;a&quot;, &quot;b&quot;, &quot;c&quot;}); </code></pre> <p><strong>Important Note:</strong> The argument(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.</p> <p><strong>Important Note 2:</strong> The argument that gets the <code>...</code> must be the last in the method signature. So, <code>myMethod(int i, String... strings)</code> is okay, but <code>myMethod(String... strings, int i)</code> is not okay.</p> <p>Thanks to Vash for the clarifications in his comment.</p>
{ "question_id": 3158730, "question_date": "2010-07-01T14:27:49.187Z", "question_score": 991, "tags": "java|variadic-functions", "answer_id": 3158767, "answer_date": "2010-07-01T14:32:37.220Z", "answer_score": 1196 }
Please answer the following Stack Overflow question: Title: How to display Base64 images in HTML <p>I'm having trouble displaying a Base64 image inline.</p> <p>How can I do it?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Display Image&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;img style='display:block; width:100px;height:100px;' id='base64image' src='data:image/jpeg;base64, LzlqLzRBQ... &lt;!-- Base64 data --&gt;' /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>My suspect is of course the actual Base64 data. Otherwise it looks good to me. See <a href="http://jsfiddle.net/hpP45/" rel="noreferrer">this fiddle</a> where a similar scheme is working. You may try specifying the character set.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;p&gt;Taken from wikpedia&lt;/p&gt; &lt;img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>You can try <a href="http://www.opinionatedgeek.com/dotnet/tools/base64decode/" rel="noreferrer">this Base64 decoder</a> to see if your Base64 data is correct or not.</p>
{ "question_id": 8499633, "question_date": "2011-12-14T04:53:21.693Z", "question_score": 990, "tags": "html|image|base64|inline", "answer_id": 8499716, "answer_date": "2011-12-14T05:06:26.807Z", "answer_score": 1485 }
Please answer the following Stack Overflow question: Title: How to retrieve a module's path? <p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p> <p>How do I retrieve a module's path in python?</p>
<pre><code>import a_module print(a_module.__file__) </code></pre> <p>Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:</p> <pre><code>import os path = os.path.abspath(a_module.__file__) </code></pre> <p>You can also try:</p> <pre><code>path = os.path.dirname(a_module.__file__) </code></pre> <p>To get the module's directory.</p>
{ "question_id": 247770, "question_date": "2008-10-29T17:52:40.673Z", "question_score": 990, "tags": "python|module|inotify", "answer_id": 248862, "answer_date": "2008-10-29T23:57:13.760Z", "answer_score": 1182 }
Please answer the following Stack Overflow question: Title: How do you find out the caller function in JavaScript? <pre><code>function main() { Hello(); } function Hello() { // How do you find out the caller function is 'main'? } </code></pre> <p>Is there a way to find out the call stack?</p>
<p><strong>Note that this solution is deprecated and should no longer be used according to MDN documentation</strong></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller</a></p> <hr /> <pre><code>function Hello() { alert(&quot;caller is &quot; + Hello.caller); } </code></pre> <p>Note that this feature is <strong>non-standard</strong>, from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller" rel="noreferrer"><code>Function.caller</code></a>:</p> <blockquote> <p><strong>Non-standard</strong><br /> This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.</p> </blockquote> <hr /> <p>The following is the old answer from 2008, which is no longer supported in modern Javascript:</p> <pre><code>function Hello() { alert(&quot;caller is &quot; + arguments.callee.caller.toString()); } </code></pre>
{ "question_id": 280389, "question_date": "2008-11-11T09:04:39.123Z", "question_score": 990, "tags": "javascript|callstack", "answer_id": 280396, "answer_date": "2008-11-11T09:07:16.327Z", "answer_score": 1062 }
Please answer the following Stack Overflow question: Title: What is the yield keyword used for in C#? <p>In the <a href="https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist">How Can I Expose Only a Fragment of IList&lt;></a> question one of the answers had the following code snippet:</p> <pre><code>IEnumerable&lt;object&gt; FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item)) yield return item; } } </code></pre> <p>What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.</p>
<p>The <code>yield</code> contextual keyword actually does quite a lot here.</p> <p>The function returns an object that implements the <code>IEnumerable&lt;object&gt;</code> interface. If a calling function starts <code>foreach</code>ing over this object, the function is called again until it &quot;yields&quot;. This is syntactic sugar introduced in <strong>C# 2.0</strong>. In earlier versions you had to create your own <code>IEnumerable</code> and <code>IEnumerator</code> objects to do stuff like this.</p> <p>The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:</p> <pre><code>public void Consumer() { foreach(int i in Integers()) { Console.WriteLine(i.ToString()); } } public IEnumerable&lt;int&gt; Integers() { yield return 1; yield return 2; yield return 4; yield return 8; yield return 16; yield return 16777216; } </code></pre> <p>When you step through the example, you'll find the first call to <code>Integers()</code> returns <code>1</code>. The second call returns <code>2</code> and the line <code>yield return 1</code> is not executed again.</p> <p>Here is a real-life example:</p> <pre><code>public IEnumerable&lt;T&gt; Read&lt;T&gt;(string sql, Func&lt;IDataReader, T&gt; make, params object[] parms) { using (var connection = CreateConnection()) { using (var command = CreateCommand(CommandType.Text, sql, connection, parms)) { command.CommandTimeout = dataBaseSettings.ReadCommandTimeout; using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return make(reader); } } } } } </code></pre>
{ "question_id": 39476, "question_date": "2008-09-02T13:15:24.877Z", "question_score": 990, "tags": "c#|yield", "answer_id": 39496, "answer_date": "2008-09-02T13:23:16.200Z", "answer_score": 890 }
Please answer the following Stack Overflow question: Title: What is the difference between substr and substring? <p>What is the difference between</p> <pre><code>alert("abc".substr(0,2)); </code></pre> <p>and</p> <pre><code>alert("abc".substring(0,2)); </code></pre> <p>They both seem to output “ab”.</p>
<p>The difference is in the second argument. The second argument to <code>substring</code> is the index to stop at (but not include), but the second argument to <code>substr</code> is the maximum length to return.</p> <p>Links?</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring</a></p>
{ "question_id": 3745515, "question_date": "2010-09-19T11:40:10.347Z", "question_score": 990, "tags": "javascript|substring", "answer_id": 3745518, "answer_date": "2010-09-19T11:41:06.993Z", "answer_score": 1079 }
Please answer the following Stack Overflow question: Title: How to rollback a specific migration? <p>I have the following <a href="https://guides.rubyonrails.org/active_record_migrations.html" rel="noreferrer">migration</a> file <code>db\migrate\20100905201547_create_blocks.rb</code></p> <p>How can I specifically rollback that migration file?</p>
<pre><code>rake db:rollback STEP=1 </code></pre> <p>Is a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.</p> <p>For example:</p> <pre><code>rake db:rollback STEP=5 </code></pre> <p>Will also rollback all the migration that happened later (4, 3, 2 and also 1).</p> <p>To roll back all migrations back to (and including) a target migration, use: (This corrected command was added AFTER all the comments pointing out the error in the original post)</p> <pre><code>rake db:migrate VERSION=20100905201547 </code></pre> <p>In order to rollback ONLY ONE specific migration (OUT OF ORDER) use:</p> <pre><code>rake db:migrate:down VERSION=20100905201547 </code></pre> <p>Note that this will NOT rollback any interceding migrations -- only the one listed. If that is not what you intended, you can safely run <code>rake db:migrate</code> and it will re-run only that one, skipping any others that were not previously rolled back. </p> <p>And if you ever want to migrate a single migration out of order, there is also its inverse <code>db:migrate:up</code>:</p> <pre><code>rake db:migrate:up VERSION=20100905201547 </code></pre>
{ "question_id": 3647685, "question_date": "2010-09-05T20:30:17.447Z", "question_score": 989, "tags": "ruby-on-rails|schema|database-schema|rollback", "answer_id": 3647820, "answer_date": "2010-09-05T21:10:53.987Z", "answer_score": 1675 }
Please answer the following Stack Overflow question: Title: Switch focus between editor and integrated terminal <p>Does anyone know the keyboard shortcut (Mac and Linux) to switch the focus between editor and integrated terminal in Visual Studio Code?</p>
<p>While there are a lot of modal toggles and navigation shortcuts for VS Code, there isn't one specifically for &quot;move from editor to terminal, and back again&quot;. However you can compose the two steps by overloading the <code>key</code> and using the <code>when</code> <a href="https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts" rel="noreferrer">clause</a>.</p> <hr /> <h1>Solution</h1> <p>You can achieve the desired effect by adding the appropriate settings to the <code>keybindings.json</code> file. Here are the required steps:</p> <ol> <li><p>Open the <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette" rel="noreferrer">Command Palette</a> (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd> Windows/Linux or <kbd>⇧</kbd> <kbd>⌘</kbd> <kbd>P</kbd> Mac).</p> </li> <li><p>Type &quot;<em>Preferences: Open Keyboard Shortcuts File</em>&quot; and press <kbd>Enter</kbd>.</p> </li> <li><p>Add the following entries to the <code>keybindings.json</code> file:</p> </li> </ol> <pre class="lang-json prettyprint-override"><code>// Toggle between terminal and editor focus { &quot;key&quot;: &quot;ctrl+`&quot;, &quot;command&quot;: &quot;workbench.action.terminal.focus&quot; }, { &quot;key&quot;: &quot;ctrl+`&quot;, &quot;command&quot;: &quot;workbench.action.focusActiveEditorGroup&quot;, &quot;when&quot;: &quot;terminalFocus&quot; } </code></pre> <p>With these shortcuts you can focus between the editor and the Integrated Terminal using the same keystroke.</p> <hr /> <h3>NOTE</h3> <p>In modern versions of VS Code (as of 2022) the <em>Default Keyboard Shortcuts (JSON)</em> file is <em><strong>read-only</strong></em>, so that is why for the <em>custom</em> settings you need to edit a separate dedicated file <code>keybindings.json</code>.</p> <p>More info can be found on the official Visual Studio documentation page:</p> <ul> <li><a href="https://code.visualstudio.com/docs/getstarted/keybindings#_advanced-customization" rel="noreferrer">Key Bindings for Visual Studio Code: Advanced customization</a></li> </ul>
{ "question_id": 42796887, "question_date": "2017-03-14T21:29:52.673Z", "question_score": 989, "tags": "visual-studio-code", "answer_id": 43012779, "answer_date": "2017-03-25T05:10:11.113Z", "answer_score": 1720 }
Please answer the following Stack Overflow question: Title: How do you format code in Visual Studio Code (VSCode)? <p>What is the equivalent of <kbd>Ctrl</kbd> + <kbd>K</kbd> + <kbd>F</kbd> and <kbd>Ctrl</kbd> + <kbd>K</kbd> + <kbd>D</kbd> on Windows in Visual Studio for formatting, or "beautifying" code in the Visual Studio Code editor?</p>
<p>The code formatting is available in Visual Studio Code through the following shortcuts:</p> <ul> <li>On Windows <kbd>Shift</kbd> + <kbd>Alt</kbd> + <kbd>F</kbd></li> <li>On Mac <kbd>Shift</kbd> + <kbd>Option</kbd> + <kbd>F</kbd></li> <li>On Linux <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd></li> </ul> <p>Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with <kbd>Ctrl</kbd> +<kbd>Shift</kbd>+ <kbd>P</kbd> (or <kbd>Command</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> on Mac), and then searching for <em><strong>format document</strong>.</em></p> <h1>For unsaved snippets</h1> <ol> <li><p>Open command palette (Win: <kbd>F1</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)</p> </li> <li><p>Find &quot;Change Language Mode&quot;</p> </li> <li><p>Select language e.g. <code>json</code>. By now syntax should be highlighted.</p> </li> <li><p>Format document (e.g. Open Command Palette -&gt; &quot;<em>Format Document</em>&quot;)</p> </li> </ol> <h1>Unformat</h1> <ol> <li>Select text</li> <li>Command Palette -&gt; Join Lines</li> </ol> <h1>'<em>Show the pics</em>'</h1> <p><a href="https://i.stack.imgur.com/wPRmb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wPRmb.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/uirnx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uirnx.png" alt="enter image description here" /></a></p>
{ "question_id": 29973357, "question_date": "2015-04-30T16:43:35.850Z", "question_score": 988, "tags": "code-formatting|visual-studio-code", "answer_id": 29973358, "answer_date": "2015-04-30T16:43:35.850Z", "answer_score": 5107 }
Please answer the following Stack Overflow question: Title: Is there any way to change input type="date" format? <p>By default, the input <code>type=&quot;date&quot;</code> shows date as <code>YYYY-MM-DD</code>.</p> <p>The question is, is it possible to force it's format to something like: <code>DD-MM-YYYY</code>?</p>
<p><strong>It is impossible to change the format</strong></p> <p>We have to differentiate between the over the wire format and the browser's presentation format.</p> <h2>Wire format</h2> <p>The <a href="https://www.w3.org/TR/2011/WD-html-markup-20110405/input.date.html" rel="noreferrer">HTML5 date input specification</a> refers to the <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer">RFC 3339 specification</a>, which specifies a full-date format equal to: <code>yyyy-mm-dd</code>. See <a href="https://www.rfc-editor.org/rfc/rfc3339#section-5.6" rel="noreferrer">section 5.6</a> of the RFC 3339 specification for more details.</p> <p>This format is used by the <code>value</code> HTML attribute and DOM property and is the one used when doing an ordinary form submission.</p> <h2>Presentation format</h2> <p>Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Browser_compatibility" rel="noreferrer">here</a>). They all display a date picker and format the text in the input field.</p> <p><strong>Desktop devices</strong></p> <p>For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to <code>en-us</code> will be shown <code>01/30/2019</code> instead of the format they are accustomed to: <code>30-01-2019</code>.</p> <p>Internet Explorer 9, 10, and 11 display a text input field with the wire format.</p> <p><strong>Mobile devices</strong></p> <p>Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.</p>
{ "question_id": 7372038, "question_date": "2011-09-10T13:33:36.517Z", "question_score": 988, "tags": "html|css|date|input", "answer_id": 9519493, "answer_date": "2012-03-01T15:59:39.677Z", "answer_score": 756 }
Please answer the following Stack Overflow question: Title: What's the difference between the 'ref' and 'out' keywords? <p>I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:</p> <pre><code>public void myFunction(ref MyClass someClass) </code></pre> <p>and</p> <pre><code>public void myFunction(out MyClass someClass) </code></pre> <p>Which should I use and why?</p>
<p><code>ref</code> tells the compiler that the object is initialized before entering the function, while <code>out</code> tells the compiler that the object will be initialized inside the function. </p> <p>So while <code>ref</code> is two-ways, <code>out</code> is out-only.</p>
{ "question_id": 388464, "question_date": "2008-12-23T09:16:43.613Z", "question_score": 988, "tags": "c#|reference|keyword|out|ref", "answer_id": 388467, "answer_date": "2008-12-23T09:18:03.860Z", "answer_score": 1270 }
Please answer the following Stack Overflow question: Title: What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA? <p>What is the difference between <a href="https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html" rel="noreferrer">CrudRepository</a> and <a href="https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html" rel="noreferrer">JpaRepository</a> interfaces in <a href="https://spring.io/projects/spring-data-jpa" rel="noreferrer">Spring Data JPA</a>? </p> <p>When I see the examples on the web, I see them there used kind of interchangeably.</p> <p>What is the difference between them?</p> <p>Why would you want to use one over the other?</p>
<p><a href="http://static.springsource.org/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html" rel="noreferrer"><code>JpaRepository</code></a> extends <a href="http://static.springsource.org/spring-data/data-commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html" rel="noreferrer"><code>PagingAndSortingRepository</code></a> which in turn extends <a href="http://static.springsource.org/spring-data/data-commons/docs/current/api/org/springframework/data/repository/CrudRepository.html" rel="noreferrer"><code>CrudRepository</code></a>.</p> <p>Their main functions are:</p> <ul> <li><a href="http://static.springsource.org/spring-data/data-commons/docs/current/api/org/springframework/data/repository/CrudRepository.html" rel="noreferrer"><code>CrudRepository</code></a> mainly provides CRUD functions.</li> <li><a href="http://static.springsource.org/spring-data/data-commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html" rel="noreferrer"><code>PagingAndSortingRepository</code></a> provides methods to do pagination and sorting records.</li> <li><a href="http://static.springsource.org/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html" rel="noreferrer"><code>JpaRepository</code></a> provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.</li> </ul> <p>Because of the inheritance mentioned above, <code>JpaRepository</code> will have all the functions of <code>CrudRepository</code> and <code>PagingAndSortingRepository</code>. So if you don't need the repository to have the functions provided by <code>JpaRepository</code> and <code>PagingAndSortingRepository</code> , use <code>CrudRepository</code>.</p>
{ "question_id": 14014086, "question_date": "2012-12-23T19:35:12.087Z", "question_score": 988, "tags": "java|spring|jpa|spring-data|spring-data-jpa", "answer_id": 14025100, "answer_date": "2012-12-24T19:36:34.490Z", "answer_score": 1363 }
Please answer the following Stack Overflow question: Title: Recursively counting files in a Linux directory <p>How can I recursively count files in a Linux directory?</p> <p>I found this:</p> <pre><code>find DIR_NAME -type f ¦ wc -l </code></pre> <p>But when I run this it returns the following error.</p> <blockquote> <p>find: paths must precede expression: ¦</p> </blockquote>
<p>This should work:</p> <pre><code>find DIR_NAME -type f | wc -l </code></pre> <p><strong>Explanation:</strong></p> <ul> <li><code>-type f</code> to include only files.</li> <li><code>|</code> (<strong>and not <code>¦</code></strong>) redirects <code>find</code> command's standard output to <code>wc</code> command's standard input.</li> <li><code>wc</code> (short for word count) counts newlines, words and bytes on its input (<a href="http://man7.org/linux/man-pages/man1/wc.1.html" rel="noreferrer">docs</a>).</li> <li><code>-l</code> to count just newlines.</li> </ul> <p><strong>Notes:</strong> </p> <ul> <li>Replace <code>DIR_NAME</code> with <code>.</code> to execute the command in the current folder.</li> <li>You can also remove the <code>-type f</code> to include directories (and symlinks) in the count.</li> <li>It's possible this command will overcount if filenames can contain newline characters.</li> </ul> <p><strong>Explanation of why your example does not work:</strong></p> <p>In the command you showed, you do not use the "Pipe" (<code>|</code>) to kind-of connect two commands, but the broken bar (<code>¦</code>) which the shell does not recognize as a command or something similar. That's why you get that error message.</p>
{ "question_id": 9157138, "question_date": "2012-02-06T07:59:18.960Z", "question_score": 987, "tags": "linux|bash", "answer_id": 9157162, "answer_date": "2012-02-06T08:02:30.153Z", "answer_score": 1714 }
Please answer the following Stack Overflow question: Title: Styling an input type="file" button <p>How do you style an input <code>type=&quot;file&quot;</code> button?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="file" /&gt;</code></pre> </div> </div> </p>
<p>Styling file inputs are notoriously difficult, as most browsers will not change the appearance from either CSS or javascript.</p> <p>Even the size of the input will not respond to the likes of:</p> <pre><code>&lt;input type="file" style="width:200px"&gt; </code></pre> <p>Instead, you will need to use the size attribute:</p> <pre><code>&lt;input type="file" size="60" /&gt; </code></pre> <p>For any styling more sophisticated than that (e.g. changing the look of the browse button) you will need to look at the tricksy approach of overlaying a styled button and input box on top of the native file input. The article already mentioned by rm at <a href="http://www.quirksmode.org/dom/inputfile.html" rel="noreferrer">www.quirksmode.org/dom/inputfile.html</a> is the best one I've seen.</p> <p><strong>UPDATE</strong></p> <p>Although it's difficult to style an <code>&lt;input&gt;</code> tag directly, this is easily possible with the help of a <code>&lt;label&gt;</code> tag. See answer below from @JoshCrozier: <a href="https://stackoverflow.com/a/25825731/10128619">https://stackoverflow.com/a/25825731/10128619</a></p>
{ "question_id": 572768, "question_date": "2009-02-21T10:36:49.020Z", "question_score": 986, "tags": "html|css", "answer_id": 714626, "answer_date": "2009-04-03T16:11:44.500Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: How to copy to clipboard in Vim? <p>Is it possible to copy to clipboard directly from Vim? <code>yy</code> only copies stuff to Vim's internal buffer. I want to copy to the OS's clipboard. Is there any such command in Vim or you can only yank stuff within Vim?</p>
<p>The <code>*</code> register will do this. In Windows, <code>+</code> and <code>*</code> are equivalent. In unix there is a subtle difference between <code>+</code> and <code>*</code>:</p> <blockquote> <p>Under Windows, the * and + registers are equivalent. For X11 systems, though, they differ. For X11 systems, * is the selection, and + is the cut buffer (like clipboard). <a href="http://vim.wikia.com/wiki/Accessing_the_system_clipboard" rel="noreferrer">http://vim.wikia.com/wiki/Accessing_the_system_clipboard</a></p> </blockquote> <p><code>*</code> is probably what you want most of the time, so I use <code>*</code> because it functions as I expect it to in both environments.</p> <p>In Linux distros you have to install <code>vim-gtk</code> (aka <code>gvim</code>) first to gain clipboard functionality. This is because non-gtk vim is typically compiled without X11 support. This is to allow it to run on console only machines (often servers).</p> <p>And for those confused about how to use registers when yanking or putting, you merely write <code>"</code> then the name of the register. So for copying something to the clipboard register you type <code>"*y</code> and then to put you type <code>"*p</code> (credit: Kyle Mathews)</p>
{ "question_id": 3961859, "question_date": "2010-10-18T17:49:38.940Z", "question_score": 986, "tags": "vim|clipboard", "answer_id": 3961954, "answer_date": "2010-10-18T17:59:50.797Z", "answer_score": 638 }
Please answer the following Stack Overflow question: Title: class << self idiom in Ruby <p>What does <code>class &lt;&lt; self</code> do in <strong>Ruby</strong>?</p>
<p>First, the <code>class &lt;&lt; foo</code> syntax opens up <code>foo</code>'s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.</p> <pre><code>a = 'foo' class &lt;&lt; a def inspect '"bar"' end end a.inspect # =&gt; "bar" a = 'foo' # new object, new singleton class a.inspect # =&gt; "foo" </code></pre> <hr> <p>Now, to answer the question: <code>class &lt;&lt; self</code> opens up <code>self</code>'s singleton class, so that methods can be redefined for the current <code>self</code> object (which inside a class or module body is the class or module <em>itself</em>). Usually, this is used to define class/module ("static") methods:</p> <pre><code>class String class &lt;&lt; self def value_of obj obj.to_s end end end String.value_of 42 # =&gt; "42" </code></pre> <p>This can also be written as a shorthand:</p> <pre><code>class String def self.value_of obj obj.to_s end end </code></pre> <p>Or even shorter:</p> <pre><code>def String.value_of obj obj.to_s end </code></pre> <hr> <p>When inside a function definition, <code>self</code> refers to the object the function is being called with. In this case, <code>class &lt;&lt; self</code> opens the singleton class for that object; one use of that is to implement a poor man's state machine:</p> <pre><code>class StateMachineExample def process obj process_hook obj end private def process_state_1 obj # ... class &lt;&lt; self alias process_hook process_state_2 end end def process_state_2 obj # ... class &lt;&lt; self alias process_hook process_state_1 end end # Set up initial state alias process_hook process_state_1 end </code></pre> <p>So, in the example above, each instance of <code>StateMachineExample</code> has <code>process_hook</code> aliased to <code>process_state_1</code>, but note how in the latter, it can redefine <code>process_hook</code> (for <code>self</code> only, not affecting other <code>StateMachineExample</code> instances) to <code>process_state_2</code>. So, each time a caller calls the <code>process</code> method (which calls the redefinable <code>process_hook</code>), the behaviour changes depending on what state it's in.</p>
{ "question_id": 2505067, "question_date": "2010-03-24T03:02:42.203Z", "question_score": 986, "tags": "ruby|metaclass|eigenclass|singleton", "answer_id": 2505077, "answer_date": "2010-03-24T03:05:37.750Z", "answer_score": 993 }
Please answer the following Stack Overflow question: Title: How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds <p>I am trying to work with <a href="http://www.springsource.org/spring-data/neo4j" rel="noreferrer">Spring Data and Neo4j</a>. I started by trying to follow <a href="https://github.com/SpringSource/spring-data-graph" rel="noreferrer">this guide</a> linked to by the main site. In particular I based my pom.xml off of the <a href="https://github.com/SpringSource/spring-data-graph-examples/blob/master/hello-worlds/pom.xml" rel="noreferrer">"Hello, World!" example file</a>. Here is a snip from my pom.xml for the plugin that is causing the issues...</p> <pre class="lang-xml prettyprint-override"><code>&lt;plugin&gt; &lt;!-- Required to resolve aspectj-enhanced class features --&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;aspectj-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;configuration&gt; &lt;outxml&gt;true&lt;/outxml&gt; &lt;aspectLibraries&gt; &lt;aspectLibrary&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aspects&lt;/artifactId&gt; &lt;/aspectLibrary&gt; &lt;aspectLibrary&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-neo4j&lt;/artifactId&gt; &lt;/aspectLibrary&gt; &lt;/aspectLibraries&gt; &lt;source&gt;1.6&lt;/source&gt; &lt;target&gt;1.6&lt;/target&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;!-- ERROR HERE IN ECLIPSE SEE BELOW FOR FULL MESSAGE --&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;goal&gt;test-compile&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt; &lt;version&gt;${aspectj.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjtools&lt;/artifactId&gt; &lt;version&gt;${aspectj.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/plugin&gt; </code></pre> <p>The error I am seeing is:</p> <pre><code> Multiple annotations found at this line: - Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:aspectj-maven-plugin:1.0:compile (execution: default, phase: process-classes) - Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:aspectj-maven-plugin:1.0:test-compile (execution: default, phase: process-classes) </code></pre> <p>I am running Eclipse 3.6.2 and m2e 0.13. I'm not a Maven expert, so please be very explanatory in your answers if possible.</p> <p>I've also tried <a href="http://www.eclipse.org/m2e/download/" rel="noreferrer">m2e 1.0.0</a> via <a href="http://download.eclipse.org/technology/m2e/milestones/1.0" rel="noreferrer">this update site</a> and still get the same error.</p>
<p>What a mess. I don't remember where I found this but I had to add the following to get M2Eclipse to be happy. Even more sad is that it isn't exactly easy to understand why this tag is needed.</p> <pre class="lang-xml prettyprint-override"><code>&lt;build&gt; ... various plugins ... &lt;pluginManagement&gt; &lt;plugins&gt; &lt;!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --&gt; &lt;plugin&gt; &lt;groupId&gt;org.eclipse.m2e&lt;/groupId&gt; &lt;artifactId&gt;lifecycle-mapping&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;configuration&gt; &lt;lifecycleMappingMetadata&gt; &lt;pluginExecutions&gt; &lt;pluginExecution&gt; &lt;pluginExecutionFilter&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;aspectj-maven-plugin&lt;/artifactId&gt; &lt;versionRange&gt;[1.0,)&lt;/versionRange&gt; &lt;goals&gt; &lt;goal&gt;test-compile&lt;/goal&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;/pluginExecutionFilter&gt; &lt;action&gt; &lt;execute /&gt; &lt;/action&gt; &lt;/pluginExecution&gt; &lt;/pluginExecutions&gt; &lt;/lifecycleMappingMetadata&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; </code></pre> <p>There were a number of other issues with the M2Eclipse plug-in that simply didn't work with Spring Data. In the end I disabled M2Eclipse in favor of the <a href="http://maven.apache.org/plugins/maven-eclipse-plugin/" rel="noreferrer">Apache Eclipse plug-in</a>.</p>
{ "question_id": 6352208, "question_date": "2011-06-15T02:04:40.723Z", "question_score": 985, "tags": "eclipse|maven|spring-data|m2eclipse", "answer_id": 6372575, "answer_date": "2011-06-16T13:22:38.217Z", "answer_score": 426 }
Please answer the following Stack Overflow question: Title: Java string to date conversion <p>What is the best way to convert a <code>String</code> in the format 'January 2, 2010' to a <code>Date</code> in Java?</p> <p>Ultimately, I want to break out the month, the day, and the year as integers so that I can use</p> <pre><code>Date date = new Date(); date.setMonth().. date.setYear().. date.setDay().. date.setlong currentTime = date.getTime(); </code></pre> <p>to convert the date into time.</p>
<p>That's the hard way, and those <code>java.util.Date</code> setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole <code>java.util.Date</code> class was de-facto deprecated (discommended) since introduction of <code>java.time</code> API in Java 8 (2014).</p> <p>Simply format the date using <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer"><code>DateTimeFormatter</code></a> with a pattern matching the input string (<a href="https://docs.oracle.com/javase/tutorial/datetime/iso/format.html" rel="noreferrer">the tutorial is available here</a>).</p> <p>In your specific case of &quot;January 2, 2010&quot; as the input string:</p> <ol> <li>&quot;January&quot; is the full text month, so use the <code>MMMM</code> pattern for it</li> <li>&quot;2&quot; is the short day-of-month, so use the <code>d</code> pattern for it.</li> <li>&quot;2010&quot; is the 4-digit year, so use the <code>yyyy</code> pattern for it.</li> </ol> <pre><code>String string = &quot;January 2, 2010&quot;; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;MMMM d, yyyy&quot;, Locale.ENGLISH); LocalDate date = LocalDate.parse(string, formatter); System.out.println(date); // 2010-01-02 </code></pre> <p>Note: if your format pattern happens to contain the time part as well, then use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>LocalDateTime#parse(text, formatter)</code></a> instead of <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>LocalDate#parse(text, formatter)</code></a>. And, if your format pattern happens to contain the time zone as well, then use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-" rel="noreferrer"><code>ZonedDateTime#parse(text, formatter)</code></a> instead.</p> <p>Here's an extract of relevance from <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer">the javadoc</a>, listing all available format patterns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Symbol</th> <th>Meaning</th> <th>Presentation</th> <th>Examples</th> </tr> </thead> <tbody> <tr> <td><code>G</code></td> <td>era</td> <td>text</td> <td>AD; Anno Domini; A</td> </tr> <tr> <td><code>u</code></td> <td>year</td> <td>year</td> <td>2004; 04</td> </tr> <tr> <td><code>y</code></td> <td>year-of-era</td> <td>year</td> <td>2004; 04</td> </tr> <tr> <td><code>D</code></td> <td>day-of-year</td> <td>number</td> <td>189</td> </tr> <tr> <td><code>M</code>/<code>L</code></td> <td>month-of-year</td> <td>number/text</td> <td>7; 07; Jul; July; J</td> </tr> <tr> <td><code>d</code></td> <td>day-of-month</td> <td>number</td> <td>10</td> </tr> <tr> <td><code>Q</code>/<code>q</code></td> <td>quarter-of-year</td> <td>number/text</td> <td>3; 03; Q3; 3rd quarter</td> </tr> <tr> <td><code>Y</code></td> <td>week-based-year</td> <td>year</td> <td>1996; 96</td> </tr> <tr> <td><code>w</code></td> <td>week-of-week-based-year</td> <td>number</td> <td>27</td> </tr> <tr> <td><code>W</code></td> <td>week-of-month</td> <td>number</td> <td>4</td> </tr> <tr> <td><code>E</code></td> <td>day-of-week</td> <td>text</td> <td>Tue; Tuesday; T</td> </tr> <tr> <td><code>e</code>/<code>c</code></td> <td>localized day-of-week</td> <td>number/text</td> <td>2; 02; Tue; Tuesday; T</td> </tr> <tr> <td><code>F</code></td> <td>week-of-month</td> <td>number</td> <td>3</td> </tr> <tr> <td><code>a</code></td> <td>am-pm-of-day</td> <td>text</td> <td>PM</td> </tr> <tr> <td><code>h</code></td> <td>clock-hour-of-am-pm (1-12)</td> <td>number</td> <td>12</td> </tr> <tr> <td><code>K</code></td> <td>hour-of-am-pm (0-11)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>k</code></td> <td>clock-hour-of-am-pm (1-24)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>H</code></td> <td>hour-of-day (0-23)</td> <td>number</td> <td>0</td> </tr> <tr> <td><code>m</code></td> <td>minute-of-hour</td> <td>number</td> <td>30</td> </tr> <tr> <td><code>s</code></td> <td>second-of-minute</td> <td>number</td> <td>55</td> </tr> <tr> <td><code>S</code></td> <td>fraction-of-second</td> <td>fraction</td> <td>978</td> </tr> <tr> <td><code>A</code></td> <td>milli-of-day</td> <td>number</td> <td>1234</td> </tr> <tr> <td><code>n</code></td> <td>nano-of-second</td> <td>number</td> <td>987654321</td> </tr> <tr> <td><code>N</code></td> <td>nano-of-day</td> <td>number</td> <td>1234000000</td> </tr> <tr> <td><code>V</code></td> <td>time-zone ID</td> <td>zone-id</td> <td>America/Los_Angeles; Z; -08:30</td> </tr> <tr> <td><code>z</code></td> <td>time-zone name</td> <td>zone-name</td> <td>Pacific Standard Time; PST</td> </tr> <tr> <td><code>O</code></td> <td>localized zone-offset</td> <td>offset-O</td> <td>GMT+8; GMT+08:00; UTC-08:00;</td> </tr> <tr> <td><code>X</code></td> <td>zone-offset 'Z' for zero</td> <td>offset-X</td> <td>Z; -08; -0830; -08:30; -083015; -08:30:15;</td> </tr> <tr> <td><code>x</code></td> <td>zone-offset</td> <td>offset-x</td> <td>+0000; -08; -0830; -08:30; -083015; -08:30:15;</td> </tr> <tr> <td><code>Z</code></td> <td>zone-offset</td> <td>offset-Z</td> <td>+0000; -0800; -08:00;</td> </tr> </tbody> </table> </div> <p>Do note that it has several <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#predefined" rel="noreferrer">predefined formatters</a> for the more popular patterns. So instead of e.g. <code>DateTimeFormatter.ofPattern(&quot;EEE, d MMM yyyy HH:mm:ss Z&quot;, Locale.ENGLISH);</code>, you could use <code>DateTimeFormatter.RFC_1123_DATE_TIME</code>. This is possible because they are, on the contrary to <code>SimpleDateFormat</code>, thread safe. You could thus also define your own, if necessary.</p> <p>For a particular input string format, you don't need to use an explicit <code>DateTimeFormatter</code>: a standard <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> date, like 2016-09-26T17:44:57Z, can be parsed directly with <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>LocalDateTime#parse(text)</code></a> as it already uses the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME" rel="noreferrer"><code>ISO_LOCAL_DATE_TIME</code></a> formatter. Similarly, <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>LocalDate#parse(text)</code></a> parses an ISO date without the time component (see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE" rel="noreferrer"><code>ISO_LOCAL_DATE</code></a>), and <a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#parse-java.lang.CharSequence-" rel="noreferrer"><code>ZonedDateTime#parse(text)</code></a> parses an ISO date with an offset and time zone added (see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_ZONED_DATE_TIME" rel="noreferrer"><code>ISO_ZONED_DATE_TIME</code></a>).</p> <hr /> <h2>Pre-Java 8</h2> <p>In case you're not on Java 8 yet, or are forced to use <code>java.util.Date</code>, then format the date using <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a> using a format pattern matching the input string.</p> <pre><code>String string = &quot;January 2, 2010&quot;; DateFormat format = new SimpleDateFormat(&quot;MMMM d, yyyy&quot;, Locale.ENGLISH); Date date = format.parse(string); System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010 </code></pre> <p>Note the importance of the explicit <code>Locale</code> argument. If you omit it, then it will use the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#getDefault--" rel="noreferrer">default locale</a> which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a <code>java.text.ParseException</code> even though when the format pattern seems valid.</p> <p>Here's an extract of relevance from <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">the javadoc</a>, listing all available format patterns:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Letter</th> <th>Date or Time Component</th> <th>Presentation</th> <th>Examples</th> </tr> </thead> <tbody> <tr> <td><code>G</code></td> <td>Era designator</td> <td>Text</td> <td>AD</td> </tr> <tr> <td><code>y</code></td> <td>Year</td> <td>Year</td> <td>1996; 96</td> </tr> <tr> <td><code>Y</code></td> <td>Week year</td> <td>Year</td> <td>2009; 09</td> </tr> <tr> <td><code>M</code>/<code>L</code></td> <td>Month in year</td> <td>Month</td> <td>July; Jul; 07</td> </tr> <tr> <td><code>w</code></td> <td>Week in year</td> <td>Number</td> <td>27</td> </tr> <tr> <td><code>W</code></td> <td>Week in month</td> <td>Number</td> <td>2</td> </tr> <tr> <td><code>D</code></td> <td>Day in year</td> <td>Number</td> <td>189</td> </tr> <tr> <td><code>d</code></td> <td>Day in month</td> <td>Number</td> <td>10</td> </tr> <tr> <td><code>F</code></td> <td>Day of week in month</td> <td>Number</td> <td>2</td> </tr> <tr> <td><code>E</code></td> <td>Day in week</td> <td>Text</td> <td>Tuesday; Tue</td> </tr> <tr> <td><code>u</code></td> <td>Day number of week</td> <td>Number</td> <td>1</td> </tr> <tr> <td><code>a</code></td> <td>Am/pm marker</td> <td>Text</td> <td>PM</td> </tr> <tr> <td><code>H</code></td> <td>Hour in day (0-23)</td> <td>Number</td> <td>0</td> </tr> <tr> <td><code>k</code></td> <td>Hour in day (1-24)</td> <td>Number</td> <td>24</td> </tr> <tr> <td><code>K</code></td> <td>Hour in am/pm (0-11)</td> <td>Number</td> <td>0</td> </tr> <tr> <td><code>h</code></td> <td>Hour in am/pm (1-12)</td> <td>Number</td> <td>12</td> </tr> <tr> <td><code>m</code></td> <td>Minute in hour</td> <td>Number</td> <td>30</td> </tr> <tr> <td><code>s</code></td> <td>Second in minute</td> <td>Number</td> <td>55</td> </tr> <tr> <td><code>S</code></td> <td>Millisecond</td> <td>Number</td> <td>978</td> </tr> <tr> <td><code>z</code></td> <td>Time zone</td> <td>General time zone</td> <td>Pacific Standard Time; PST; GMT-08:00</td> </tr> <tr> <td><code>Z</code></td> <td>Time zone</td> <td>RFC 822 time zone</td> <td>-0800</td> </tr> <tr> <td><code>X</code></td> <td>Time zone</td> <td>ISO 8601 time zone</td> <td>-08; -0800; -08:00</td> </tr> </tbody> </table> </div> <p>Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. <code>MMMMM</code> or more is unnecessary.</p> <p>Here are some examples of valid <code>SimpleDateFormat</code> patterns to parse a given string to date:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Input string</th> <th>Pattern</th> </tr> </thead> <tbody> <tr> <td>2001.07.04 AD at 12:08:56 PDT</td> <td><code>yyyy.MM.dd G 'at' HH:mm:ss z</code></td> </tr> <tr> <td>Wed, Jul 4, '01</td> <td><code>EEE, MMM d, ''yy</code></td> </tr> <tr> <td>12:08 PM</td> <td><code>h:mm a</code></td> </tr> <tr> <td>12 o'clock PM, Pacific Daylight Time</td> <td><code>hh 'o''clock' a, zzzz</code></td> </tr> <tr> <td>0:08 PM, PDT</td> <td><code>K:mm a, z</code></td> </tr> <tr> <td>02001.July.04 AD 12:08 PM</td> <td><code>yyyyy.MMMM.dd GGG hh:mm aaa</code></td> </tr> <tr> <td>Wed, 4 Jul 2001 12:08:56 -0700</td> <td><code>EEE, d MMM yyyy HH:mm:ss Z</code></td> </tr> <tr> <td>010704120856-0700</td> <td><code>yyMMddHHmmssZ</code></td> </tr> <tr> <td>2001-07-04T12:08:56.235-0700</td> <td><code>yyyy-MM-dd'T'HH:mm:ss.SSSZ</code></td> </tr> <tr> <td>2001-07-04T12:08:56.235-07:00</td> <td><code>yyyy-MM-dd'T'HH:mm:ss.SSSXXX</code></td> </tr> <tr> <td>2001-W27-3</td> <td><code>YYYY-'W'ww-u</code></td> </tr> </tbody> </table> </div> <p>An important note is that <code>SimpleDateFormat</code> is <strong>not</strong> thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope.</p>
{ "question_id": 4216745, "question_date": "2010-11-18T15:53:01.240Z", "question_score": 984, "tags": "java|string|date|time|data-conversion", "answer_id": 4216767, "answer_date": "2010-11-18T15:55:27.587Z", "answer_score": 1811 }
Please answer the following Stack Overflow question: Title: Can you force a React component to rerender without calling setState? <p>I have an external (to the component), observable object that I want to listen for changes on. When the object is updated it emits change events, and then I want to rerender the component when any change is detected.</p> <p>With a top-level <code>React.render</code> this has been possible, but within a component it doesn't work (which makes some sense since the <code>render</code> method just returns an object).</p> <p>Here's a code example:</p> <pre class="lang-js prettyprint-override"><code>export default class MyComponent extends React.Component { handleButtonClick() { this.render(); } render() { return ( &lt;div&gt; {Math.random()} &lt;button onClick={this.handleButtonClick.bind(this)}&gt; Click me &lt;/button&gt; &lt;/div&gt; ) } } </code></pre> <p>Clicking the button internally calls <code>this.render()</code>, but that's not what actually causes the rendering to happen (you can see this in action because the text created by <code>{Math.random()}</code> doesn't change). However, if I simply call <code>this.setState()</code> instead of <code>this.render()</code>, it works fine.</p> <p><strong>So I guess my question is:</strong> do React components <em>need</em> to have state in order to rerender? Is there a way to force the component to update on demand without changing the state?</p>
<p>In class components, you can call <code>this.forceUpdate()</code> to force a rerender.</p> <p>Documentation: <a href="https://facebook.github.io/react/docs/react-component.html#forceupdate" rel="noreferrer">https://facebook.github.io/react/docs/component-api.html</a></p> <p>In function components, there's no equivalent of <code>forceUpdate</code>, but you can <a href="https://stackoverflow.com/a/53837442/200224">contrive a way to force updates with the <code>useState</code> hook</a>.</p>
{ "question_id": 30626030, "question_date": "2015-06-03T16:44:58.480Z", "question_score": 984, "tags": "reactjs", "answer_id": 30626072, "answer_date": "2015-06-03T16:47:29.790Z", "answer_score": 990 }
Please answer the following Stack Overflow question: Title: How do I time a method's execution in Java? <ol> <li>How do I get a method's execution time? </li> <li>Is there a <code>Timer</code> utility class for things like timing how long a task takes, etc? </li> </ol> <p>Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.</p>
<p>There is always the old-fashioned way:</p> <pre><code>long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime(); long duration = (endTime - startTime); //divide by 1000000 to get milliseconds. </code></pre>
{ "question_id": 180158, "question_date": "2008-10-07T20:10:25.200Z", "question_score": 984, "tags": "java|timing|execution-time", "answer_id": 180191, "answer_date": "2008-10-07T20:16:16.373Z", "answer_score": 1404 }
Please answer the following Stack Overflow question: Title: How can I specify a branch/tag when adding a Git submodule? <p>How does <code>git submodule add -b</code> work?</p> <p>After adding a submodule with a specific branch, a new cloned repository (after <code>git submodule update --init</code>) will be at a specific commit, not the branch itself (<code>git status</code> on the submodule shows "Not currently on any branch").</p> <p>I can't find any information on <code>.gitmodules</code> or <code>.git/config</code> about the submodule's branch or any specific commit, so how does Git figure it out?</p> <p>Also, is it possible to specify a tag instead of a branch?</p> <p>I'm using version 1.6.5.2.</p>
<p>Note: Git 1.8.2 added the possibility to track branches. See some of the answers below.</p> <hr> <p>It's a little confusing to get used to this, but submodules are not on a branch. They are, like you say, just a pointer to a particular commit of the submodule's repository.</p> <p>This means, when someone else checks out your repository, or pulls your code, and does git submodule update, the submodule is checked out to that particular commit. </p> <p>This is great for a submodule that does not change often, because then everyone on the project can have the submodule at the same commit. </p> <p>If you want to move the submodule to a particular tag:</p> <pre><code>cd submodule_directory git checkout v1.0 cd .. git add submodule_directory git commit -m "moved submodule to v1.0" git push </code></pre> <p>Then, another developer who wants to have submodule_directory changed to that tag, does this</p> <pre><code>git pull git submodule update --init </code></pre> <p><code>git pull</code> changes which commit their submodule directory points to. <code>git submodule update</code> actually merges in the new code.</p>
{ "question_id": 1777854, "question_date": "2009-11-22T04:55:48.433Z", "question_score": 984, "tags": "git|git-submodules", "answer_id": 1778247, "answer_date": "2009-11-22T09:19:34.167Z", "answer_score": 904 }
Please answer the following Stack Overflow question: Title: Can I specify multiple users for myself in .gitconfig? <p>In my <code>~/.gitconfig</code>, I list my personal email address under <code>[user]</code>, since that's what I want to use for Github repos.</p> <p>But, I've recently started using git for work, too. My company's git repo allows me to commit, but when it sends out announcements of new changesets, it says they are from Anonymous because it doesn't recognize the email address in my <code>.gitconfig</code> - at least, that's my theory.</p> <p>Is it possible to specify multiple <code>[user]</code> definitions in <code>.gitconfig</code>? Or is there some other way to override the default <code>.gitconfig</code> for a certain directory? In my case, I check out all work code in <code>~/worksrc/</code> - is there a way to specify a <code>.gitconfig</code> for only that directory (and its subdirectories)?</p>
<p>You can configure an individual repo to use a specific user / email address which overrides the global configuration. From the root of the repo, run</p> <pre><code>git config user.name "Your Name Here" git config user.email [email protected] </code></pre> <p>whereas the default user / email is configured in your ~/.gitconfig</p> <pre><code>git config --global user.name "Your Name Here" git config --global user.email [email protected] </code></pre>
{ "question_id": 4220416, "question_date": "2010-11-18T22:45:51.040Z", "question_score": 984, "tags": "git|git-config", "answer_id": 4220493, "answer_date": "2010-11-18T22:56:07.207Z", "answer_score": 1246 }
Please answer the following Stack Overflow question: Title: How can I get the data-id attribute? <p>I'm using the jQuery <em><a href="https://github.com/razorjack/quicksand" rel="noreferrer">Quicksand</a></em> plugin. I need to get the data-id of the clicked item and pass it to a webservice.</p> <p>How do I get the data-id attribute? I'm using the <code>.on()</code> method to re-bind the click event for sorted items.</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>$("#list li").on('click', function() { // ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError); alert($(this).attr("#data-id")); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"&gt;&lt;/script&gt; &lt;ul id="list" class="grid"&gt; &lt;li data-id="id-40" class="win"&gt; &lt;a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#"&gt; &lt;img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" /&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
<p>To get the contents of the attribute <code>data-id</code> (like in <code>&lt;a data-id="123"&gt;link&lt;/a&gt;</code>) you have to use</p> <pre><code>$(this).attr("data-id") // will return the string "123" </code></pre> <p>or <a href="http://api.jquery.com/data/" rel="noreferrer"><code>.data()</code></a> (if you use newer jQuery >= 1.4.3)</p> <pre><code>$(this).data("id") // will return the number 123 </code></pre> <p><strong>and the part after <code>data-</code> must be lowercase, e.g. <code>data-idNum</code> will not work, but <code>data-idnum</code> will.</strong></p>
{ "question_id": 5309926, "question_date": "2011-03-15T09:44:30.820Z", "question_score": 983, "tags": "javascript|html|jquery|custom-data-attribute", "answer_id": 5309947, "answer_date": "2011-03-15T09:46:42.943Z", "answer_score": 1929 }
Please answer the following Stack Overflow question: Title: How do I search for files in Visual Studio Code? <p>I am used to Resharper where I can search for files, not the content, but the filename, which makes it quick to open new files.</p> <p>Is this feature implemented in Visual Studio Code and is there a shortcut for it?</p>
<p>Using <strong>Go to File...</strong> which is under the <strong>Go</strong> menu or using keyboard shortcut:</p> <ul> <li>On Windows <kbd>Ctrl</kbd>+<kbd>p</kbd> or <kbd>Ctrl</kbd>+<kbd>e</kbd></li> <li>On macOS <kbd>Cmd ⌘</kbd>+<kbd>p</kbd> </li> <li>On Linux <kbd>Ctrl</kbd>+<kbd>p</kbd> or <kbd>Ctrl</kbd>+<kbd>e</kbd></li> </ul> <p>Then type the file name.</p> <p>Also be sure to checkout that you can set your own <a href="https://code.visualstudio.com/docs/getstarted/keybindings" rel="noreferrer">keybindings</a> and that there are cheatsheets available for <a href="https://go.microsoft.com/fwlink/?linkid=832145" rel="noreferrer">Windows</a>, <a href="https://go.microsoft.com/fwlink/?linkid=832143" rel="noreferrer">macOS</a> and <a href="https://go.microsoft.com/fwlink/?linkid=832144" rel="noreferrer">Linux</a>.</p>
{ "question_id": 30095376, "question_date": "2015-05-07T08:12:12.970Z", "question_score": 983, "tags": "visual-studio-code|keyboard-shortcuts", "answer_id": 30108348, "answer_date": "2015-05-07T17:52:30.620Z", "answer_score": 1555 }
Please answer the following Stack Overflow question: Title: How to make JavaScript execute after page load? <p>I'm executing an external script, using a <code>&lt;script&gt;</code> inside <code>&lt;head&gt;</code>.</p> <p>Now since the script executes <strong>before</strong> the page has loaded, I can't access the <code>&lt;body&gt;</code>, among other things. I'd like to execute some JavaScript after the document has been "loaded" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?</p>
<p>These solutions will work:</p> <p>As mentioned in comments use <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer" rel="noreferrer">defer</a>:</p> <pre><code>&lt;script src=&quot;deferMe.js&quot; defer&gt;&lt;/script&gt; </code></pre> <p>or</p> <pre><code>&lt;body onload=&quot;script();&quot;&gt; </code></pre> <p>or</p> <pre><code>document.onload = function ... </code></pre> <p>or even</p> <pre><code>window.onload = function ... </code></pre> <p>Note that <strong>the last option is a better way to go</strong> since it is <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="noreferrer">unobstrusive</a> and is <a href="https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load#comment617710_807891">considered more standard</a>.</p>
{ "question_id": 807878, "question_date": "2009-04-30T16:38:36.803Z", "question_score": 982, "tags": "javascript|html|dom|dom-events|pageload", "answer_id": 807895, "answer_date": "2009-04-30T16:41:16.300Z", "answer_score": 1116 }
Please answer the following Stack Overflow question: Title: How do I remove the first item from a list? <p>How do I remove the first item from a list?</p> <pre><code>[0, 1, 2, 3] → [1, 2, 3] </code></pre>
<p>You can find a short collection of useful list functions <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="noreferrer">here</a>.</p> <p><a href="https://www.programiz.com/python-programming/methods/list/pop" rel="noreferrer"><code>list.pop(index)</code></a></p> <pre><code>&gt;&gt;&gt; l = ['a', 'b', 'c', 'd'] &gt;&gt;&gt; l.pop(0) 'a' &gt;&gt;&gt; l ['b', 'c', 'd'] &gt;&gt;&gt; </code></pre> <p><a href="https://docs.python.org/3/tutorial/datastructures.html#the-del-statement" rel="noreferrer"><code>del list[index]</code></a></p> <pre><code>&gt;&gt;&gt; l = ['a', 'b', 'c', 'd'] &gt;&gt;&gt; del l[0] &gt;&gt;&gt; l ['b', 'c', 'd'] &gt;&gt;&gt; </code></pre> <p>These both modify your original list.</p> <p>Others have suggested using slicing:</p> <ul> <li>Copies the list</li> <li>Can return a subset</li> </ul> <p>Also, if you are performing many <code>pop(0)</code>, you should look at <a href="http://docs.python.org/library/collections.html#collections.deque" rel="noreferrer"><code>collections.deque</code></a></p> <pre><code>from collections import deque &gt;&gt;&gt; l = deque(['a', 'b', 'c', 'd']) &gt;&gt;&gt; l.popleft() 'a' &gt;&gt;&gt; l deque(['b', 'c', 'd']) </code></pre> <ul> <li>Provides higher performance popping from left end of the list</li> </ul>
{ "question_id": 4426663, "question_date": "2010-12-13T07:38:38.647Z", "question_score": 982, "tags": "python|list", "answer_id": 4426727, "answer_date": "2010-12-13T07:45:58.617Z", "answer_score": 1553 }
Please answer the following Stack Overflow question: Title: How can I find all the tables in MySQL with specific column names in them? <p>I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?</p>
<p>To get all tables with columns <code>columnA</code> or <code>ColumnB</code> in the database <code>YourDatabase</code>:</p> <pre><code>SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('columnA','ColumnB') AND TABLE_SCHEMA='YourDatabase'; </code></pre>
{ "question_id": 193780, "question_date": "2008-10-11T07:02:05.463Z", "question_score": 982, "tags": "mysql|information-schema", "answer_id": 193860, "answer_date": "2008-10-11T08:42:40.427Z", "answer_score": 1598 }
Please answer the following Stack Overflow question: Title: Difference between <? super T> and <? extends T> in Java <p>What is the difference between <code>List&lt;? super T&gt;</code> and <code>List&lt;? extends T&gt;</code> ?</p> <p>I used to use <code>List&lt;? extends T&gt;</code>, but it does not allow me to add elements to it <code>list.add(e)</code>, whereas the <code>List&lt;? super T&gt;</code> does.</p>
<h3><code>extends</code></h3> <p>The wildcard declaration of <code>List&lt;? extends Number&gt; foo3</code> means that any of these are legal assignments:</p> <pre><code>List&lt;? extends Number&gt; foo3 = new ArrayList&lt;Number&gt;(); // Number "extends" Number (in this context) List&lt;? extends Number&gt; foo3 = new ArrayList&lt;Integer&gt;(); // Integer extends Number List&lt;? extends Number&gt; foo3 = new ArrayList&lt;Double&gt;(); // Double extends Number </code></pre> <ol> <li><p><strong>Reading</strong> - Given the above possible assignments, what type of object are you guaranteed to read from <code>List foo3</code>:</p> <ul> <li>You can read a <strong><code>Number</code></strong> because any of the lists that could be assigned to <code>foo3</code> contain a <code>Number</code> or a subclass of <code>Number</code>.</li> <li>You can't read an <code>Integer</code> because <code>foo3</code> could be pointing at a <code>List&lt;Double&gt;</code>.</li> <li>You can't read a <code>Double</code> because <code>foo3</code> could be pointing at a <code>List&lt;Integer&gt;</code>.</li> </ul></li> <li><p><strong>Writing</strong> - Given the above possible assignments, what type of object could you add to <code>List foo3</code> that would be legal for <strong>all</strong> the above possible <code>ArrayList</code> assignments:</p> <ul> <li>You can't add an <code>Integer</code> because <code>foo3</code> could be pointing at a <code>List&lt;Double&gt;</code>.</li> <li>You can't add a <code>Double</code> because <code>foo3</code> could be pointing at a <code>List&lt;Integer&gt;</code>.</li> <li>You can't add a <code>Number</code> because <code>foo3</code> could be pointing at a <code>List&lt;Integer&gt;</code>.</li> </ul></li> </ol> <p><em>You can't add any object to <code>List&lt;? extends T&gt;</code> because you can't guarantee what kind of <code>List</code> it is really pointing to, so you can't guarantee that the object is allowed in that <code>List</code>. The only "guarantee" is that you can only read from it and you'll get a <code>T</code> or subclass of <code>T</code>.</em></p> <h3><code>super</code></h3> <p>Now consider <code>List &lt;? super T&gt;</code>.</p> <p>The wildcard declaration of <code>List&lt;? super Integer&gt; foo3</code> means that any of these are legal assignments:</p> <pre><code>List&lt;? super Integer&gt; foo3 = new ArrayList&lt;Integer&gt;(); // Integer is a "superclass" of Integer (in this context) List&lt;? super Integer&gt; foo3 = new ArrayList&lt;Number&gt;(); // Number is a superclass of Integer List&lt;? super Integer&gt; foo3 = new ArrayList&lt;Object&gt;(); // Object is a superclass of Integer </code></pre> <ol> <li><p><strong>Reading</strong> - Given the above possible assignments, what type of object are you guaranteed to receive when you read from <code>List foo3</code>:</p> <ul> <li>You aren't guaranteed an <code>Integer</code> because <code>foo3</code> could be pointing at a <code>List&lt;Number&gt;</code> or <code>List&lt;Object&gt;</code>.</li> <li>You aren't guaranteed a <code>Number</code> because <code>foo3</code> could be pointing at a <code>List&lt;Object&gt;</code>.</li> <li>The <strong>only</strong> guarantee is that you will get an instance of an <strong><code>Object</code></strong> or subclass of <code>Object</code> (but you don't know what subclass).</li> </ul></li> <li><p><strong>Writing</strong> - Given the above possible assignments, what type of object could you add to <code>List foo3</code> that would be legal for <strong>all</strong> the above possible <code>ArrayList</code> assignments:</p> <ul> <li>You can add an <code>Integer</code> because an <code>Integer</code> is allowed in any of above lists.</li> <li>You can add an instance of a subclass of <code>Integer</code> because an instance of a subclass of <code>Integer</code> is allowed in any of the above lists.</li> <li>You can't add a <code>Double</code> because <code>foo3</code> could be pointing at an <code>ArrayList&lt;Integer&gt;</code>.</li> <li>You can't add a <code>Number</code> because <code>foo3</code> could be pointing at an <code>ArrayList&lt;Integer&gt;</code>.</li> <li>You can't add an <code>Object</code> because <code>foo3</code> could be pointing at an <code>ArrayList&lt;Integer&gt;</code>.</li> </ul></li> </ol> <h3>PECS</h3> <p>Remember <em>PECS</em>: <strong>"Producer Extends, Consumer Super"</strong>.</p> <ul> <li><p><strong>"Producer Extends"</strong> - If you need a <code>List</code> to produce <code>T</code> values (you want to read <code>T</code>s from the list), you need to declare it with <code>? extends T</code>, e.g. <code>List&lt;? extends Integer&gt;</code>. But you cannot add to this list.</p></li> <li><p><strong>"Consumer Super"</strong> - If you need a <code>List</code> to consume <code>T</code> values (you want to write <code>T</code>s into the list), you need to declare it with <code>? super T</code>, e.g. <code>List&lt;? super Integer&gt;</code>. But there are no guarantees what type of object you may read from this list.</p></li> <li><p>If you need to both read from and write to a list, you need to declare it exactly with no wildcards, e.g. <code>List&lt;Integer&gt;</code>.</p></li> </ul> <h3>Example</h3> <p>Note <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103" rel="noreferrer">this example from the Java Generics FAQ</a>. Note how the source list <code>src</code> (the producing list) uses <code>extends</code>, and the destination list <code>dest</code> (the consuming list) uses <code>super</code>:</p> <pre><code>public class Collections { public static &lt;T&gt; void copy(List&lt;? super T&gt; dest, List&lt;? extends T&gt; src) { for (int i = 0; i &lt; src.size(); i++) dest.set(i, src.get(i)); } } </code></pre> <p>Also see <a href="https://stackoverflow.com/questions/2776975/how-can-i-add-to-list-extends-number-data-structures/2777297#2777297">How can I add to List&lt;? extends Number&gt; data structures?</a></p>
{ "question_id": 4343202, "question_date": "2010-12-03T06:57:06.297Z", "question_score": 982, "tags": "java|generics|collections", "answer_id": 4343547, "answer_date": "2010-12-03T08:03:49.207Z", "answer_score": 1930 }
Please answer the following Stack Overflow question: Title: What are the differences between "git commit" and "git push"? <p>In a Git tutorial I'm going through, <code>git commit</code> is used to store the changes you've made. </p> <p>What is <code>git push</code> used for then?</p>
<p>Basically, <code>git commit</code> &quot;<em>records changes to the repository</em>&quot; while <code>git push</code> &quot;<em>updates remote refs along with associated objects</em>&quot;. So the first one is used in connection with your local repository, while the latter one is used to interact with a remote repository.</p> <p>Here is a nice picture from <a href="http://blog.osteele.com/2008/05/my-git-workflow/" rel="noreferrer">Oliver Steele</a>, that explains the Git model and the commands:</p> <p><img src="https://i.stack.imgur.com/MgaV9.png" alt="Git data transport commands" /></p> <p>Read more about <code>git push</code> and <code>git pull</code> on <em><a href="http://www.gitready.com/beginner/2009/01/21/pushing-and-pulling.html" rel="noreferrer">Pushing and pulling</a></em> (the article I referred to first).</p>
{ "question_id": 2745076, "question_date": "2010-04-30T14:17:12.077Z", "question_score": 981, "tags": "git|push|git-commit|git-push|git-index", "answer_id": 2745097, "answer_date": "2010-04-30T14:20:17.653Z", "answer_score": 1757 }
Please answer the following Stack Overflow question: Title: How to insert an element after another element in JavaScript without using a library? <p>There's <code>insertBefore()</code> in JavaScript, but how can I insert an element <em>after</em> another element without using jQuery or another library?</p>
<pre><code>referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); </code></pre> <p>Where <code>referenceNode</code> is the node you want to put <code>newNode</code> after. If <code>referenceNode</code> is the last child within its parent element, that's fine, because <code>referenceNode.nextSibling</code> will be <code>null</code> and <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-952280727" rel="noreferrer"><code>insertBefore</code></a> handles that case by adding to the end of the list.</p> <p>So:</p> <pre><code>function insertAfter(newNode, referenceNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } </code></pre> <hr /> <p>You can test it using the following snippet:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } var el = document.createElement("span"); el.innerHTML = "test"; var div = document.getElementById("foo"); insertAfter(div, el);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="foo"&gt;Hello&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 4793604, "question_date": "2011-01-25T12:39:36.280Z", "question_score": 981, "tags": "javascript|dom|insert|append", "answer_id": 4793630, "answer_date": "2011-01-25T12:42:32.950Z", "answer_score": 1586 }
Please answer the following Stack Overflow question: Title: What is the difference between .NET Core and .NET Standard Class Library project types? <p>In Visual Studio, there are at least three different types of class libraries you can create:</p> <ul> <li>Class Library (.NET Framework)</li> <li>Class Library (.NET Standard)</li> <li>Class Library (.NET Core)</li> </ul> <p>While the first is what we've been using for years, a major point of confusion I've been having is when to use the .NET Standard and .NET Core class library types. I've been bitten by this recently when attempting to <a href="https://stackoverflow.com/a/42748869/983064">multi-target different framework versions</a>, and <a href="https://stackoverflow.com/questions/42938879/cant-get-xunit-tests-to-run-with-net-core">creating a unit test project</a>.</p> <p>So, what is the difference between <em>Class Library (.NET Standard)</em> and <em>Class Library (.NET Core)</em>, why do both exist, and when should we use one over the other?</p>
<blockquote> <p>When should we use one over the other?</p> </blockquote> <p>The decision is a trade-off between compatibility and API access.</p> <p>Use a .NET Standard library when you want to increase the number of applications that will be compatible with your library, and you are okay with a decrease in the .NET API surface area your library can access.</p> <p>Use a .NET Core library when you want to increase the .NET API surface area your library can access, and you are okay with allowing only .NET Core applications to be compatible with your library.</p> <p>For example, a library that targets .NET Standard 1.3 <a href="https://docs.microsoft.com/en-us/dotnet/articles/standard/library#net-platforms-support" rel="noreferrer">will be compatible with</a> applications that target .NET Framework 4.6, .NET Core 1.0, Universal Windows Platform 10.0, and any other platform that supports .NET Standard 1.3. The library will not have access to some parts of the .NET API, though. For instance, the <a href="https://www.nuget.org/packages/Microsoft.NETCore.Runtime.CoreCLR/" rel="noreferrer"><code>Microsoft.NETCore.CoreCLR</code></a> package is compatible with .NET Core, but not with .NET Standard.</p> <blockquote> <p>What is the difference between Class Library (.NET Standard) and Class Library (.NET Core)?</p> </blockquote> <p>Compatibility: Libraries that target .NET Standard will run on any .NET Standard compliant runtime, such as .NET Core, .NET Framework, <a href="https://en.wikipedia.org/wiki/Mono_%28software%29" rel="noreferrer">Mono</a>/<a href="https://en.wikipedia.org/wiki/Xamarin" rel="noreferrer">Xamarin</a>. On the other hand, libraries that target .NET Core can only run on the .NET Core runtime.</p> <p>API Surface Area: .NET Standard libraries come with everything in <code>NETStandard.Library</code>, whereas .NET Core libraries come with everything in <code>Microsoft.NETCore.App</code>. The latter includes approximately 20 additional libraries, some of which we can add manually to our .NET Standard library (such as <code>System.Threading.Thread</code>) and some of which are not compatible with the .NET Standard (such as <code>Microsoft.NETCore.CoreCLR</code>).</p> <p>Also, .NET Core libraries specify a runtime and come with an application model. That's important, for instance, to make unit test class libraries runnable.</p> <blockquote> <p>Why do both exist?</p> </blockquote> <p>Ignoring libraries for a moment, the reason that .NET Standard exists is for portability; it defines a set of APIs that .NET platforms agree to implement. Any platform that implements a .NET Standard is compatible with libraries that target that .NET Standard. One of those compatible platforms is .NET Core.</p> <p>Coming back to libraries, the .NET Standard library templates exist to run on multiple runtimes (at the expense of API surface area). Conversely, the .NET Core library templates exist to access more API surface area (at the expense of compatibility) and to specify a platform against which to build an executable.</p> <p><a href="https://dotnet.microsoft.com/platform/dotnet-standard#versions" rel="noreferrer">Here is an interactive matrix</a> that shows which .NET Standard supports which .NET implementation(s) and how much API surface area is available.</p>
{ "question_id": 42939454, "question_date": "2017-03-21T22:34:24.367Z", "question_score": 981, "tags": ".net|.net-core|class-library|.net-standard", "answer_id": 42940138, "answer_date": "2017-03-21T23:33:09.347Z", "answer_score": 747 }
Please answer the following Stack Overflow question: Title: How to download Xcode DMG or XIP file? <p>Where does the Mac App Store download the files to under Lion? I need the DMG file in order to repair something in my system, but how can I access that file?</p>
<p>You must <a href="https://developer.apple.com/account/" rel="nofollow noreferrer">login</a> to have a valid session before downloading anything below.</p> <p>You can find the DMGs or XIPs for Xcode and other development tools on <a href="https://developer.apple.com/download/more/" rel="nofollow noreferrer">https://developer.apple.com/download/more/</a> (requires Apple ID to login). To get the available XCode version only <a href="https://developer.apple.com/download/all/?q=xcode" rel="nofollow noreferrer">https://developer.apple.com/download/all/?q=xcode</a></p> <p>*(Newest on top. For each minor version (6.3, 5.1, etc.) <strong>only the latest revision is kept</strong> in the list.)</p> <p><strong>Xcode 14</strong></p> <ul> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_14.0.1_Release_Candidate/Xcode_14.0.1_Release_Candidate.xip" rel="nofollow noreferrer">14.0.1 RC</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_14/Xcode_14.xip" rel="nofollow noreferrer">14.0</a>     <em>recently released: Sep. 12 2022</em></li> <li><a href="https://download.developer.apple.com/Developer_Tools/Xcode_14_Release_Candidate/Xcode_14_Release_Candidate.xip" rel="nofollow noreferrer">14.0 RC</a></li> <li><a href="https://download.developer.apple.com/Developer_Tools/Xcode_14_beta_6/Xcode_14_beta_6.xip" rel="nofollow noreferrer">14.0 beta 6</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_14_beta_5/Xcode_14_beta_5.xip" rel="nofollow noreferrer">14.0 beta 5</a></li> </ul> <p><strong>Xcode 13</strong></p> <ul> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_13.4.1/Xcode_13.4.1.xip" rel="nofollow noreferrer">13.4.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_13.3.1/Xcode_13.3.1.xip" rel="nofollow noreferrer">13.3.1</a> (Requires macOS 12.0 or later)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_13.2.1/Xcode_13.2.1.xip" rel="nofollow noreferrer">13.2.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_13.1/Xcode_13.1.xip" rel="nofollow noreferrer">13.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_13/Xcode_13.xip" rel="nofollow noreferrer">13.0</a></p> </li> </ul> <p><strong>Xcode 12</strong></p> <ul> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.5.1/Xcode_12.5.1.xip" rel="nofollow noreferrer">12.5.1</a> (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Big Sur 11 or later) (Latest as of 22-Jun-2021)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.4/Xcode_12.4.xip" rel="nofollow noreferrer">12.4</a> (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.3/Xcode_12.3.xip" rel="nofollow noreferrer">12.3</a> (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.2/Xcode_12.2.xip" rel="nofollow noreferrer">12.2</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.1/Xcode_12.1.xip" rel="nofollow noreferrer">12.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_12.0.1/Xcode_12.0.1.xip" rel="nofollow noreferrer">12.0.1</a> (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)</p> </li> </ul> <p><strong>Xcode 11</strong></p> <ul> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.7/Xcode_11.7.xip" rel="nofollow noreferrer">11.7</a> (Latest as of Sept 02 2020)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.6/Xcode_11.6.xip" rel="nofollow noreferrer">11.6</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.5/Xcode_11.5.xip" rel="nofollow noreferrer">11.5</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.4.1/Xcode_11.4.1.xip" rel="nofollow noreferrer">11.4.1</a> (Requires macOS 10.15.2 or later)</p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.3.1/Xcode_11.3.1.xip" rel="nofollow noreferrer">11.3.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.2.1/Xcode_11.2.1.xip" rel="nofollow noreferrer">11.2.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.1/Xcode_11.1.xip" rel="nofollow noreferrer">11.1</a></p> </li> <li><p><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11/Xcode_11.xip" rel="nofollow noreferrer">11</a> (Requires macOS 10.14.4 or later)</p> </li> </ul> <p><strong>Xcode 10</strong> (unsupported for iTunes Connect)</p> <ul> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.3/Xcode_10.3.xip" rel="nofollow noreferrer">10.3</a> (Requires macOS 10.14.3 or later)</li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2.1/Xcode_10.2.1.xip" rel="nofollow noreferrer">10.2.1</a> (Requires macOS 10.14.3 or later)</li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.1/Xcode_10.1.xip" rel="nofollow noreferrer">10.1</a> (Last version supporting macOS 10.13.6 High Sierra)</li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10/Xcode_10.xip" rel="nofollow noreferrer">10</a> (Subsequent versions were unsupported for iTunes Connect from March 2019)</li> </ul> <p><strong>Xcode 9</strong></p> <ul> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9.4.1/Xcode_9.4.1.xip" rel="nofollow noreferrer">9.4.1</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9.3.1/Xcode_9.3.1.xip" rel="nofollow noreferrer">9.3.1</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9.2/Xcode_9.2.xip" rel="nofollow noreferrer">9.2</a> (Last version supporting macOS 10.12.6 Sierra)</li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9.1/Xcode_9.1.xip" rel="nofollow noreferrer">9.1</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_9.0.1/Xcode_9.0.1.xip" rel="nofollow noreferrer">9.0.1</a></li> </ul> <p><strong>Xcode 8</strong></p> <ul> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_8.3.3/Xcode8.3.3.xip" rel="nofollow noreferrer">8.3.3</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_8.2.1/Xcode_8.2.1.xip" rel="nofollow noreferrer">8.2.1</a> (Last version supporting OS X 10.11.5 El Capitan)</li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_8.1/Xcode_8.1.xip" rel="nofollow noreferrer">8.1</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_8/Xcode_8.xip" rel="nofollow noreferrer">8.0</a></li> </ul> <p><strong>Xcode 7</strong></p> <ul> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_7.3.1/Xcode_7.3.1.dmg" rel="nofollow noreferrer">7.3.1</a></li> <li><a href="https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_7.2.1/Xcode_7.2.1.dmg" rel="nofollow noreferrer">7.2.1</a> (Last version supporting OS X 10.10 Yosemite)</li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/Xcode_7.1.1/Xcode_7.1.1.dmg" rel="nofollow noreferrer">7.1.1</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/Xcode_7.0.1/Xcode_7.0.1.dmg" rel="nofollow noreferrer">7.0.1</a></li> </ul> <p><strong>Xcode 6</strong></p> <ul> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/Xcode_6.4/Xcode_6.4.dmg" rel="nofollow noreferrer">6.4</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/Xcode_6.3.2/Xcode_6.3.2.dmg" rel="nofollow noreferrer">6.3.2</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/Xcode_6.2/Xcode_6.2.dmg" rel="nofollow noreferrer">6.2</a> (Last version supporting OS X 10.9.5 Mavericks)</li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_6.1.1/xcode_6.1.1.dmg" rel="nofollow noreferrer">6.1.1</a></li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_6.0.1/xcode_6.0.1.dmg" rel="nofollow noreferrer">6.0.1</a></li> </ul> <p><strong>Even Older Versions</strong> (unsupported for iTunes Connect)</p> <ul> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_5.1.1/xcode_5.1.1.dmg" rel="nofollow noreferrer">5.1.1</a> (Latest version supporting OS X 10.8 Mountain Lion)</li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_5.0.2/xcode_5.0.2.dmg" rel="nofollow noreferrer">5.0.2</a></li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.6.3/xcode4630916281a.dmg" rel="nofollow noreferrer">4.6.3</a></li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.5.2/xcode4520418508a.dmg" rel="nofollow noreferrer">4.5.2</a></li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.4.1/xcode_4.4.1_6938145.dmg" rel="nofollow noreferrer">4.4.1</a></li> <li><a href="https://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.3.2/xcode_432_lion.dmg" rel="nofollow noreferrer">4.3.2</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.2_for_lion_21264/installxcode_42_lion.dmg" rel="nofollow noreferrer">4.2</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.1_for_lion_21263/installxcode_41_lion.dmg" rel="nofollow noreferrer">4.1</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_4.0.2_and_ios_sdk_4.3/xcode_4.0.2_and_ios_sdk_4.3.dmg" rel="nofollow noreferrer">4.0.2</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_3.2.6_and_ios_sdk_4.3__final/xcode_3.2.6_and_ios_sdk_4.3.dmg" rel="nofollow noreferrer">3.2.6</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_3.1.4_developer_tools/xcode314_2809_developerdvd.dmg" rel="nofollow noreferrer">3.1.4</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_3.0/xcode_3.0.dmg" rel="nofollow noreferrer">3.0</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_2.5_developer_tools/xcode25_8m2558_developerdvd.dmg" rel="nofollow noreferrer">2.5</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_2.4.1/xcode_2.4.1_8m1910_6936315.dmg" rel="nofollow noreferrer">2.4.1</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_2.3/xcode_2.3_8m1780_oz693620813.dmg" rel="nofollow noreferrer">2.3</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_tools_2.2.1/xcode_2.2.1_8g1165_018213632.dmg" rel="nofollow noreferrer">2.2.1</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Developer_Tools/xcode_v1.5/xcode_tools_1.5_cd.dmg.bin" rel="nofollow noreferrer">1.5</a></li> <li><a href="http://developer.apple.com/devcenter/download.action?path=/Mac_OS_X/Mac_OS_X_10.3_Build_7B85/7B85_Xcode_CD.dmg" rel="nofollow noreferrer">1.0</a></li> </ul>
{ "question_id": 10335747, "question_date": "2012-04-26T14:41:18.723Z", "question_score": 980, "tags": "xcode|dmg", "answer_id": 10335943, "answer_date": "2012-04-26T14:52:40.777Z", "answer_score": 5666 }
Please answer the following Stack Overflow question: Title: Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists <p>I am still getting this error message, when I try to move my project tree on to git repo.</p> <p>I checked the permissions of my directory with this project and these are set on 777. In terminal in the directory with <code>my_project</code> I set:</p> <p><code>git init</code></p> <p>and then if I try</p> <p><code>git add .</code></p> <p>or</p> <p><code>git commit -m &quot;first upload&quot;</code></p> <p>so I'll get the error</p> <pre><code>fatal: Unable to create '/path/my_proj/.git/index.lock': File exists. If no other git process is currently running, this probably means a git process crashed in this repository earlier. Make sure no other git process is running and remove the file manually to continue. </code></pre> <p>I tried also create a new repo and there to commit it, but unfortunately still the same error message.</p> <p>What is the cause of problem?</p>
<p>Try</p> <pre><code>rm -f ./.git/index.lock </code></pre> <p>In your repository directory. The error message is rather explicit as to what causes it typically, so if you have no other git processes running (which is the normal case), go ahead and delete that file.</p>
{ "question_id": 7860751, "question_date": "2011-10-22T16:03:54.703Z", "question_score": 980, "tags": "git", "answer_id": 7860765, "answer_date": "2011-10-22T16:06:16.910Z", "answer_score": 2091 }
Please answer the following Stack Overflow question: Title: How can I exclude directories from grep -R? <p>I want to traverse all subdirectories, except the "node_modules" directory.</p>
<p><strong>SOLUTION 1 (combine <code>find</code> and <code>grep</code>)</strong></p> <p>The purpose of this solution is not to deal with <code>grep</code> performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.</p> <p>Use <strong><code>find</code></strong>, for excluding directories foo and bar :</p> <pre><code>find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name &quot;*.sh&quot; -print </code></pre> <p>Then combine <strong><code>find</code></strong> and the non-recursive use of <strong><code>grep</code></strong>, as a portable solution :</p> <pre><code>find /dir \( -name node_modules -prune \) -o -name &quot;*.sh&quot; -exec grep --color -Hn &quot;your text to find&quot; {} 2&gt;/dev/null \; </code></pre> <p><strong>SOLUTION 2 (using the <code>--exclude-dir</code> option of <code>grep</code>):</strong></p> <p>You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.</p> <pre><code>grep -R --exclude-dir=node_modules 'some pattern' /path/to/search </code></pre> <p>To exclude multiple directories, use <code>--exclude-dir</code> as:</p> <p><code>--exclude-dir={node_modules,dir1,dir2,dir3}</code></p> <p><strong>SOLUTION 3 (Ag)</strong></p> <p>If you frequently search through code, <a href="https://github.com/ggreer/the_silver_searcher" rel="noreferrer">Ag (The Silver Searcher)</a> is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in <code>.gitignore</code>, so you don't have to keep passing the same cumbersome exclude options to <code>grep</code> or <code>find</code>.</p>
{ "question_id": 6565471, "question_date": "2011-07-03T20:48:43.077Z", "question_score": 980, "tags": "linux|unix|grep", "answer_id": 6565519, "answer_date": "2011-07-03T20:59:11.587Z", "answer_score": 593 }
Please answer the following Stack Overflow question: Title: mkdir -p functionality in Python <p>Is there a way to get functionality similar to <code>mkdir -p</code> on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?</p>
<p>For Python ≥ 3.5, use <a href="https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir" rel="noreferrer"><code>pathlib.Path.mkdir</code></a>:</p> <pre><code>import pathlib pathlib.Path(&quot;/tmp/path/to/desired/directory&quot;).mkdir(parents=True, exist_ok=True) </code></pre> <p>The <code>exist_ok</code> parameter was added in Python 3.5.</p> <hr /> <p>For Python ≥ 3.2, <a href="https://docs.python.org/library/os.html#os.makedirs" rel="noreferrer"><code>os.makedirs</code></a> has an <a href="https://docs.python.org/3/library/os.html?highlight=exist_ok#os.makedirs" rel="noreferrer">optional third argument <code>exist_ok</code></a> that, when <code>True</code>, enables the <code>mkdir -p</code> functionality—<em>unless</em> <code>mode</code> is provided and the existing directory has different permissions than the intended ones; in that case, <code>OSError</code> is raised as previously:</p> <pre><code>import os os.makedirs(&quot;/tmp/path/to/desired/directory&quot;, exist_ok=True) </code></pre> <hr /> <p>For even older versions of Python, you can use <code>os.makedirs</code> and ignore the error:</p> <pre><code>import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python ≥ 2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass # possibly handle other errno cases here, otherwise finally: else: raise </code></pre>
{ "question_id": 600268, "question_date": "2009-03-01T18:49:39.313Z", "question_score": 980, "tags": "python|path|directory-structure|mkdir", "answer_id": 600612, "answer_date": "2009-03-01T21:51:46.710Z", "answer_score": 1351 }
Please answer the following Stack Overflow question: Title: pip install from git repo branch <p>Trying to <code>pip</code> install a repo's specific branch. Google tells me to</p> <pre><code>pip install https://github.com/user/repo.git@branch </code></pre> <p>The branch's name is <code>issue/34/oscar-0.6</code> so I did <code>pip install https://github.com/tangentlabs/django-oscar-paypal.git@/issue/34/oscar-0.6</code> but its returning a 404.</p> <p>How do I install this branch?</p>
<p>Prepend the url prefix <code>git+</code> (See <a href="https://pip.pypa.io/en/stable/topics/vcs-support/" rel="noreferrer">VCS Support</a>):</p> <pre><code>pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6 </code></pre> <p>And specify the branch name without the leading <code>/</code>.</p>
{ "question_id": 20101834, "question_date": "2013-11-20T16:46:42.983Z", "question_score": 979, "tags": "python|git|pip", "answer_id": 20101940, "answer_date": "2013-11-20T16:51:32.700Z", "answer_score": 1286 }
Please answer the following Stack Overflow question: Title: Count the number of set bits in a 32-bit integer <p>8 bits representing the number 7 look like this:</p> <pre><code>00000111 </code></pre> <p>Three bits are set.</p> <p>What are the algorithms to determine the number of set bits in a 32-bit integer?</p>
<p>This is known as the '<a href="https://en.wikipedia.org/wiki/Hamming_weight" rel="noreferrer">Hamming Weight</a>', 'popcount' or 'sideways addition'.</p> <p>Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. Instructions like x86's <a href="https://www.felixcloutier.com/x86/popcnt" rel="noreferrer"><code>popcnt</code></a> (on CPUs where it's supported) will almost certainly be fastest for a single integer. Some other architectures may have a slow instruction implemented with a microcoded loop that tests a bit per cycle (<em>citation needed</em> - hardware popcount is normally fast if it exists at all.).</p> <p>The 'best' algorithm really depends on which CPU you are on and what your usage pattern is.</p> <p>Your compiler may know how to do something that's good for the specific CPU you're compiling for, e.g. <a href="https://en.cppreference.com/w/cpp/numeric/popcount" rel="noreferrer">C++20 <code>std::popcount()</code></a>, or C++ <a href="https://en.cppreference.com/w/cpp/utility/bitset/count" rel="noreferrer"><code>std::bitset&lt;32&gt;::count()</code></a>, as a portable way to access builtin / intrinsic functions (see <a href="https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109069#109069">another answer</a> on this question). But your compiler's choice of fallback for target CPUs that don't have hardware popcnt might not be optimal for your use-case. Or your language (e.g. C) might not expose any portable function that could use a CPU-specific popcount when there is one.</p> <hr /> <h3>Portable algorithms that don't need (or benefit from) any HW support</h3> <p>A pre-populated table lookup method can be very fast if your CPU has a large cache and you are doing lots of these operations in a tight loop. However it can suffer because of the expense of a 'cache miss', where the CPU has to fetch some of the table from main memory. (Look up each byte separately to keep the table small.) If you want popcount for a contiguous range of numbers, only the low byte is changing for groups of 256 numbers, <a href="https://stackoverflow.com/questions/66520106/count-integers-in-1-n-with-k-zero-bits-below-the-leading-1-popcount-for-a-c/66532113#66532113">making this very good</a>.</p> <p>If you know that your bytes will be mostly 0's or mostly 1's then there are efficient algorithms for these scenarios, e.g. clearing the lowest set with a bithack in a loop until it becomes zero.</p> <p>I believe a very good general purpose algorithm is the following, known as 'parallel' or 'variable-precision SWAR algorithm'. I have expressed this in a C-like pseudo language, you may need to adjust it to work for a particular language (e.g. using uint32_t for C++ and &gt;&gt;&gt; in Java):</p> <p>GCC10 and clang 10.0 can recognize this pattern / idiom and compile it to a hardware popcnt or equivalent instruction when available, giving you the best of both worlds. (<a href="https://godbolt.org/z/qGdh1dvKK" rel="noreferrer">https://godbolt.org/z/qGdh1dvKK</a>)</p> <pre class="lang-c prettyprint-override"><code>int numberOfSetBits(uint32_t i) { // Java: use int, and use &gt;&gt;&gt; instead of &gt;&gt;. Or use Integer.bitCount() // C or C++: use uint32_t i = i - ((i &gt;&gt; 1) &amp; 0x55555555); // add pairs of bits i = (i &amp; 0x33333333) + ((i &gt;&gt; 2) &amp; 0x33333333); // quads i = (i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F; // groups of 8 return (i * 0x01010101) &gt;&gt; 24; // horizontal sum of bytes } </code></pre> <p>For JavaScript: <a href="https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/109025#comment103845611_109025">coerce to integer</a> with <code>|0</code> for performance: change the first line to <code>i = (i|0) - ((i &gt;&gt; 1) &amp; 0x55555555);</code></p> <p>This has the best worst-case behaviour of any of the algorithms discussed, so will efficiently deal with any usage pattern or values you throw at it. (Its performance is not data-dependent on normal CPUs where all integer operations including multiply are constant-time. It doesn't get any faster with &quot;simple&quot; inputs, but it's still pretty decent.)</p> <p>References:</p> <ul> <li><a href="https://graphics.stanford.edu/%7Eseander/bithacks.html#CountBitsSetParallel" rel="noreferrer">https://graphics.stanford.edu/~seander/bithacks.html</a></li> <li><a href="https://en.wikipedia.org/wiki/Hamming_weight" rel="noreferrer">https://en.wikipedia.org/wiki/Hamming_weight</a></li> <li><a href="http://gurmeet.net/puzzles/fast-bit-counting-routines/" rel="noreferrer">http://gurmeet.net/puzzles/fast-bit-counting-routines/</a></li> <li><a href="http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)" rel="noreferrer">http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)</a></li> </ul> <hr /> <h3>How this SWAR bithack works:</h3> <pre><code>i = i - ((i &gt;&gt; 1) &amp; 0x55555555); </code></pre> <p>The first step is an optimized version of masking to isolate the odd / even bits, shifting to line them up, and adding. This effectively does 16 separate additions in 2-bit accumulators (<a href="https://en.wikipedia.org/wiki/SWAR" rel="noreferrer">SWAR = SIMD Within A Register</a>). Like <code>(i &amp; 0x55555555) + ((i&gt;&gt;1) &amp; 0x55555555)</code>.</p> <p>The next step takes the odd/even eight of those 16x 2-bit accumulators and adds again, producing 8x 4-bit sums. The <code>i - ...</code> optimization isn't possible this time so it does just mask before / after shifting. Using the same <code>0x33...</code> constant both times instead of <code>0xccc...</code> before shifting is a good thing when compiling for ISAs that need to construct 32-bit constants in registers separately.</p> <p>The final shift-and-add step of <code>(i + (i &gt;&gt; 4)) &amp; 0x0F0F0F0F</code> widens to 4x 8-bit accumulators. It masks <em>after</em> adding instead of before, because the maximum value in any 4-bit accumulator is <code>4</code>, if all 4 bits of the corresponding input bits were set. 4+4 = 8 which still fits in 4 bits, so carry between nibble elements is impossible in <code>i + (i &gt;&gt; 4)</code>.</p> <p>So far this is just fairly normal SIMD using SWAR techniques with a few clever optimizations. Continuing on with the same pattern for 2 more steps can widen to 2x 16-bit then 1x 32-bit counts. But there is a more efficient way on machines with fast hardware multiply:</p> <p>Once we have few enough &quot;elements&quot;, <strong>a multiply with a magic constant can sum all the elements into the top element</strong>. In this case byte elements. Multiply is done by left-shifting and adding, so <strong>a multiply of <code>x * 0x01010101</code> results in <code>x + (x&lt;&lt;8) + (x&lt;&lt;16) + (x&lt;&lt;24)</code>.</strong> Our 8-bit elements are wide enough (and holding small enough counts) that this doesn't produce carry <em>into</em> that top 8 bits.</p> <p><strong>A 64-bit version of this</strong> can do 8x 8-bit elements in a 64-bit integer with a 0x0101010101010101 multiplier, and extract the high byte with <code>&gt;&gt;56</code>. So it doesn't take any extra steps, just wider constants. This is what GCC uses for <code>__builtin_popcountll</code> on x86 systems when the hardware <code>popcnt</code> instruction isn't enabled. If you can use builtins or intrinsics for this, do so to give the compiler a chance to do target-specific optimizations.</p> <hr /> <h3>With full SIMD for wider vectors (e.g. counting a whole array)</h3> <p>This bitwise-SWAR algorithm could parallelize to be done in multiple vector elements at once, instead of in a single integer register, for a speedup on CPUs with SIMD but no usable popcount instruction. (e.g. x86-64 code that has to run on any CPU, not just Nehalem or later.)</p> <p>However, the best way to use vector instructions for popcount is usually by using a variable-shuffle to do a table-lookup for 4 bits at a time of each byte in parallel. (The 4 bits index a 16 entry table held in a vector register).</p> <p>On Intel CPUs, the hardware 64bit popcnt instruction can outperform an <a href="http://wm.ite.pl/articles/sse-popcount.html" rel="noreferrer">SSSE3 <code>PSHUFB</code> bit-parallel implementation</a> by about a factor of 2, but only <a href="http://danluu.com/assembly-intrinsics/" rel="noreferrer">if your compiler gets it just right</a>. Otherwise SSE can come out significantly ahead. Newer compiler versions are aware of the <a href="https://stackoverflow.com/a/25089720/224132">popcnt false dependency</a> <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011" rel="noreferrer">problem on Intel</a>.</p> <ul> <li><a href="https://github.com/WojciechMula/sse-popcount" rel="noreferrer">https://github.com/WojciechMula/sse-popcount</a> state-of-the-art x86 SIMD popcount for SSSE3, AVX2, AVX512BW, AVX512VBMI, or AVX512 VPOPCNT. Using Harley-Seal across vectors to defer popcount within an element. (Also ARM NEON)</li> <li><a href="https://stackoverflow.com/questions/50081465/counting-1-bits-population-count-on-large-data-using-avx-512-or-avx-2">Counting 1 bits (population count) on large data using AVX-512 or AVX-2</a></li> <li>related: <a href="https://github.com/mklarqvist/positional-popcount" rel="noreferrer">https://github.com/mklarqvist/positional-popcount</a> - separate counts for each bit-position of multiple 8, 16, 32, or 64-bit integers. (Again, x86 SIMD including AVX-512 which is really good at this, with <code>vpternlogd</code> making Harley-Seal <em>very</em> good.)</li> </ul>
{ "question_id": 109023, "question_date": "2008-09-20T19:04:38.837Z", "question_score": 979, "tags": "algorithm|binary|bit-manipulation|hammingweight|iec10967", "answer_id": 109025, "answer_date": "2008-09-20T19:05:22.550Z", "answer_score": 964 }
Please answer the following Stack Overflow question: Title: How to POST JSON data with Python Requests? <p>I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request".</p> <p>Here is my client code:</p> <pre><code>data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} data_json = simplejson.dumps(data) payload = {'json_payload': data_json} r = requests.post("http://localhost:8080", data=payload) </code></pre> <p>Here is the server code.</p> <pre><code>class Root(object): def __init__(self, content): self.content = content print self.content # this works exposed = True def GET(self): cherrypy.response.headers['Content-Type'] = 'application/json' return simplejson.dumps(self.content) def POST(self): self.content = simplejson.loads(cherrypy.request.body.read()) </code></pre> <p>Any ideas?</p>
<p>Starting with Requests version 2.4.2, you can use the <a href="https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests" rel="noreferrer"><code>json=</code> parameter</a> (which takes a dictionary) instead of <code>data=</code> (which takes a string) in the call:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.post('http://httpbin.org/post', json={&quot;key&quot;: &quot;value&quot;}) &gt;&gt;&gt; r.status_code 200 &gt;&gt;&gt; r.json() {'args': {}, 'data': '{&quot;key&quot;: &quot;value&quot;}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.4.3 CPython/3.4.0', 'X-Request-Id': 'xx-xx-xx'}, 'json': {'key': 'value'}, 'origin': 'x.x.x.x', 'url': 'http://httpbin.org/post'} </code></pre>
{ "question_id": 9733638, "question_date": "2012-03-16T07:46:49.997Z", "question_score": 978, "tags": "python|json|python-requests|cherrypy", "answer_id": 26344315, "answer_date": "2014-10-13T16:08:06.177Z", "answer_score": 1602 }
Please answer the following Stack Overflow question: Title: How to get an absolute file path in Python <p>Given a path such as <code>&quot;mydir/myfile.txt&quot;</code>, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:</p> <pre><code>&quot;C:/example/cwd/mydir/myfile.txt&quot; </code></pre>
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' </code></pre> <p>Also works if it is already an absolute path:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' </code></pre>
{ "question_id": 51520, "question_date": "2008-09-09T10:19:32.727Z", "question_score": 977, "tags": "python|path|relative-path|absolute-path", "answer_id": 51523, "answer_date": "2008-09-09T10:21:03.987Z", "answer_score": 1422 }
Please answer the following Stack Overflow question: Title: .NET String.Format() to add commas in thousands place for a number <p>I want to add a comma in the thousands place for a number.</p> <p>Would <code>String.Format()</code> be the correct path to take? What format would I use?</p>
<pre><code>String.Format("{0:n}", 1234); // Output: 1,234.00 String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876 </code></pre>
{ "question_id": 105770, "question_date": "2008-09-19T21:26:21.643Z", "question_score": 977, "tags": "c#|.net|string|format", "answer_id": 105793, "answer_date": "2008-09-19T21:29:06.970Z", "answer_score": 1436 }
Please answer the following Stack Overflow question: Title: Which status code should I use for failed validations or invalid duplicates? <p>I am building an application with a REST-based API and have come to the point where I am specifying status codes for each requests.</p> <p>What status code should i send for requests failing validation or where a request is trying to add a duplicate in my database?</p> <p>I've looked through <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html</a> but none of them seems right.</p> <p>Is there a common practice when sending status codes?</p>
<p>For input validation failure: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1" rel="noreferrer">400 Bad Request</a> + your optional description. This is suggested in the book &quot;<a href="https://books.google.com/books?isbn=0596554605" rel="noreferrer">RESTful Web Services</a>&quot;. For double submit: <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10" rel="noreferrer">409 Conflict</a></p> <hr /> <p><strong>Update June 2014</strong></p> <p>The relevant specification used to be <a href="https://www.ietf.org/rfc/rfc2616.txt" rel="noreferrer">RFC2616</a>, which gave the use of 400 (Bad Request) rather narrowly as</p> <blockquote> <p>The request could not be understood by the server due to malformed syntax</p> </blockquote> <p>So it <em>might</em> have been argued that it was inappropriate for semantic errors. But not any more; since June 2014 the relevant standard <a href="https://www.rfc-editor.org/rfc/rfc7231" rel="noreferrer">RFC 7231</a>, which supersedes the previous RFC2616, gives the use of <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1" rel="noreferrer">400 (Bad Request)</a> more broadly as</p> <blockquote> <p>the server cannot or will not process the request due to something that is perceived to be a client error</p> </blockquote>
{ "question_id": 3290182, "question_date": "2010-07-20T13:03:07.120Z", "question_score": 977, "tags": "http|rest|http-status-codes", "answer_id": 3290198, "answer_date": "2010-07-20T13:05:04.603Z", "answer_score": 925 }
Please answer the following Stack Overflow question: Title: decimal vs double! - Which one should I use and when? <p>I keep seeing people using doubles in C#. I know I read somewhere that doubles sometimes lose precision. My question is when should a use a double and when should I use a decimal type? Which type is suitable for money computations? (ie. greater than $100 million)</p>
<p>For money, <strong>always</strong> decimal. It's why it was created.</p> <p>If numbers must add up correctly or balance, use decimal. This includes any financial storage or calculations, scores, or other numbers that people might do by hand.</p> <p>If the exact value of numbers is not important, use double for speed. This includes graphics, physics or other physical sciences computations where there is already a "number of significant digits".</p>
{ "question_id": 1165761, "question_date": "2009-07-22T14:37:54.860Z", "question_score": 977, "tags": "c#|double|decimal|precision|currency", "answer_id": 1165788, "answer_date": "2009-07-22T14:42:15.260Z", "answer_score": 1167 }
Please answer the following Stack Overflow question: Title: DateTime vs DateTimeOffset <p>What is the difference between a <code>DateTime</code> and a <code>DateTimeOffset</code> and when should one be used?</p> <hr /> <p>Currently, we have a standard way of dealing with .NET <code>DateTime</code>s in a TimeZone-aware way: Whenever we produce a <code>DateTime</code> we do it in UTC (e.g. using <code>DateTime.UtcNow</code>), and whenever we display one, we convert back from UTC to the user's local time.</p> <p>That works fine, but I've been reading about <code>DateTimeOffset</code> and how it captures the local and UTC time in the object itself.</p>
<p><code>DateTimeOffset</code> is a representation of <em>instantaneous time</em> (also known as <em>absolute time</em>). By that, I mean a moment in time that is universal for everyone (not accounting for <a href="https://en.wikipedia.org/wiki/Leap_second" rel="noreferrer">leap seconds</a>, or the relativistic effects of <a href="https://en.wikipedia.org/wiki/Time_dilation" rel="noreferrer">time dilation</a>). Another way to represent instantaneous time is with a <code>DateTime</code> where <code>.Kind</code> is <code>DateTimeKind.Utc</code>.</p> <p>This is distinct from <em>calendar time</em> (also known as <em>civil time</em>), which is a position on someone's calendar, and there are many different calendars all over the globe. We call these calendars <em>time zones</em>. Calendar time is represented by a <code>DateTime</code> where <code>.Kind</code> is <code>DateTimeKind.Unspecified</code>, or <code>DateTimeKind.Local</code>. And <code>.Local</code> is only meaningful in scenarios where you have an implied understanding of where the computer that is using the result is positioned. (For example, a user's workstation)</p> <p>So then, why <code>DateTimeOffset</code> instead of a UTC <code>DateTime</code>? <strong>It's all about perspective.</strong> Let's use an analogy - we'll pretend to be photographers.</p> <p>Imagine you are standing on a calendar timeline, pointing a camera at a person on the instantaneous timeline laid out in front of you. You line up your camera according to the rules of your timezone - which change periodically due to daylight saving time, or due to other changes to the legal definition of your time zone. (You don't have a steady hand, so your camera is shaky.) </p> <p>The person standing in the photo would see the angle at which your camera came from. If others were taking pictures, they could be from different angles. This is what the <code>Offset</code> part of the <code>DateTimeOffset</code> represents.</p> <p>So if you label your camera "Eastern Time", sometimes you are pointing from -5, and sometimes you are pointing from -4. There are cameras all over the world, all labeled different things, and all pointing at the same instantaneous timeline from different angles. Some of them are right next to (or on top of) each other, so just knowing the offset isn't enough to determine which timezone the time is related to.</p> <p>And what about UTC? Well, it's the one camera out there that is guaranteed to have a steady hand. It's on a tripod, firmly anchored into the ground. It's not going anywhere. We call its angle of perspective the zero offset.</p> <p><img src="https://i.stack.imgur.com/QE5xq.png" alt="Instantaneous Time vs Calendar Time Visualization"></p> <p>So - what does this analogy tell us? It provides some intuitive guidelines-</p> <ul> <li><p>If you are representing time relative to some place in particular, represent it in calendar time with a <code>DateTime</code>. Just be sure you don't ever confuse one calendar with another. <code>Unspecified</code> should be your assumption. <code>Local</code> is only useful coming from <code>DateTime.Now</code>. For example, I might get <code>DateTime.Now</code> and save it in a database - but when I retrieve it, I have to assume that it is <code>Unspecified</code>. I can't rely that my local calendar is the same calendar that it was originally taken from.</p></li> <li><p>If you must always be certain of the moment, make sure you are representing instantaneous time. Use <code>DateTimeOffset</code> to enforce it, or use UTC <code>DateTime</code> by convention.</p></li> <li><p>If you need to track a moment of instantaneous time, but you want to also know "What time did the user think it was on their local calendar?" - then you <em>must</em> use a <code>DateTimeOffset</code>. This is very important for timekeeping systems, for example - both for technical and legal concerns.</p></li> <li><p>If you ever need to modify a previously recorded <code>DateTimeOffset</code> - you don't have enough information in the offset alone to ensure that the new offset is still relevant for the user. You must <em>also</em> store a timezone identifier (think - I need the name of that camera so I can take a new picture even if the position has changed).</p> <p>It should also be pointed out that <a href="http://nodatime.org" rel="noreferrer">Noda Time</a> has a representation called <code>ZonedDateTime</code> for this, while the .Net base class library does not have anything similar. You would need to store both a <code>DateTimeOffset</code> and a <code>TimeZoneInfo.Id</code> value.</p></li> <li><p>Occasionally, you will want to represent a calendar time that is local to "whomever is looking at it". For example, when defining what <em>today</em> means. Today is always midnight to midnight, but these represent a near-infinite number of overlapping ranges on the instantaneous timeline. (In practice we have a finite number of timezones, but you can express offsets down to the tick) So in these situations, make sure you understand how to either limit the "who's asking?" question down to a single time zone, or deal with translating them back to instantaneous time as appropriate.</p></li> </ul> <p>Here are a few other little bits about <code>DateTimeOffset</code> that back up this analogy, and some tips for keeping it straight:</p> <ul> <li><p>If you compare two <code>DateTimeOffset</code> values, they are first normalized to zero offset before comparing. In other words, <code>2012-01-01T00:00:00+00:00</code> and <code>2012-01-01T02:00:00+02:00</code> refer to the same instantaneous moment, and are therefore equivalent.</p></li> <li><p>If you are doing any unit testing and need to be certain of the offset, test <em>both</em> the <code>DateTimeOffset</code> value, and the <code>.Offset</code> property separately.</p></li> <li><p>There is a one-way implicit conversion built in to the .Net framework that lets you pass a <code>DateTime</code> into any <code>DateTimeOffset</code> parameter or variable. When doing so, <strong>the <code>.Kind</code> matters</strong>. If you pass a UTC kind, it will carry in with a zero offset, but if you pass either <code>.Local</code> or <code>.Unspecified</code>, it will assume to be <strong>local</strong>. The framework is basically saying, "Well, you asked me to convert calendar time to instantaneous time, but I have no idea where this came from, so I'm just going to use the local calendar." This is a huge gotcha if you load up an unspecified <code>DateTime</code> on a computer with a different timezone. (IMHO - that should throw an exception - but it doesn't.)</p></li> </ul> <p><strong>Shameless Plug:</strong></p> <p>Many people have shared with me that they find this analogy extremely valuable, so I included it in my Pluralsight course, <a href="http://www.pluralsight.com/courses/date-time-fundamentals" rel="noreferrer">Date and Time Fundamentals</a>. You'll find a step-by-step walkthrough of the camera analogy in the second module, "Context Matters", in the clip titled "Calendar Time vs. Instantaneous Time".</p>
{ "question_id": 4331189, "question_date": "2010-12-02T02:39:34.567Z", "question_score": 977, "tags": "c#|.net|datetime|timezone|datetimeoffset", "answer_id": 14268167, "answer_date": "2013-01-10T22:09:06.603Z", "answer_score": 1544 }