input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: jQuery document.createElement equivalent?
<p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p>
<pre><code>var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
</code></pre>
<p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p>
<pre><code>var odv = $.create("div");
$.append(odv);
// And many more
</code></pre>
<p>But I'm not sure if this is any better.</p> | <p>Here's your example in the "one" line.</p>
<pre><code>this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
</code></pre>
<hr>
<p><em>Update</em>: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about <code>$("<div>")</code> vs <code>$("<div></div>")</code> vs <code>$(document.createElement('div'))</code> as a way of creating new elements, and which is "best".</p>
<p>I put together <a href="http://jsbin.com/elula3" rel="noreferrer">a small benchmark</a>, and here are roughly the results of repeating the above options 100,000 times:</p>
<p><strong>jQuery 1.4, 1.5, 1.6</strong></p>
<pre><code> Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
</code></pre>
<p><strong>jQuery 1.3</strong></p>
<pre><code> Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
</code></pre>
<p><strong>jQuery 1.2</strong></p>
<pre><code> Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
</code></pre>
<p>I think it's no big surprise, but <code>document.createElement</code> is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds <em>per thousand elements</em>. </p>
<hr>
<p><strong>Update 2</strong></p>
<p>Updated for <strong>jQuery 1.7.2</strong> and put the benchmark on <code>JSBen.ch</code> which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!</p>
<p><a href="http://jsben.ch/#/ARUtz" rel="noreferrer">http://jsben.ch/#/ARUtz</a></p> | {
"question_id": 268490,
"question_date": "2008-11-06T12:26:31.993Z",
"question_score": 1335,
"tags": "javascript|jquery|html|dom|dhtml",
"answer_id": 268520,
"answer_date": "2008-11-06T12:34:58.217Z",
"answer_score": 1355
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of the "role" attribute in HTML?
<p>I keep seeing role attributes in some people's work. I use it too, but I'm not sure about its effect.</p>
<p>For example:</p>
<pre><code><header id="header" role="banner">
Header stuff in here
</header>
</code></pre>
<p>Or:</p>
<pre><code><section id="facebook" role="contentinfo">
Facebook stuff in here
</section>
</code></pre>
<p>Or:</p>
<pre><code><section id="main" role="main">
Main content stuff in here
</section>
</code></pre>
<hr>
<p>Is this role attribute necessary?</p>
<p>Is this attribute better for semantics?</p>
<p>Does it improve SEO?</p>
<p>A list of roles can be found <a href="https://www.w3.org/TR/xhtml-role/" rel="noreferrer">here</a>, but I see some people make up their own. Is that allowed or a correct use of the role attribute?</p>
<p>Any thoughts on this?</p> | <p>Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.</p>
<p><a href="http://www.w3.org/TR/wai-aria/" rel="noreferrer">http://www.w3.org/TR/wai-aria/</a></p>
<p>While the <a href="https://www.w3.org/TR/using-aria/#firstrule" rel="noreferrer">First Rule of Aria</a> states:</p>
<blockquote>
<p>If you can use a native HTML element [HTML51] or attribute with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so.</p>
</blockquote>
<p>there are a few primary reasons to use roles in addition to your native semantic element.</p>
<p><strong>Reason #1.</strong> Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.</p>
<p>In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.</p>
<pre><code><a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->
</code></pre>
<p>Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.</p>
<pre><code>[role="button"] {
/* style these as buttons w/o relying on a .button class */
}
</code></pre>
<p>[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]</p>
<p><strong>Reason #2.</strong> Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.</p>
<p>For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <code><main></code>.</p>
<pre><code><main role="main">…</main>
</code></pre>
<p>This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.</p>
<p><strong>Reason #3.</strong>
Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.</p>
<p><strong>Note/Reply</strong></p>
<p>You also wrote:</p>
<blockquote>
<p>I see some people make up their own. Is that allowed or a correct use of the role attribute?</p>
</blockquote>
<p>That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.</p>
<pre><code><span role="foo link note bar">...</a>
</code></pre>
<p>Out of the list, only <code>link</code> and <code>note</code> are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)</p> | {
"question_id": 10403138,
"question_date": "2012-05-01T10:11:45.550Z",
"question_score": 1334,
"tags": "html|optimization|seo|roles",
"answer_id": 18664038,
"answer_date": "2013-09-06T18:12:29.183Z",
"answer_score": 1141
} |
Please answer the following Stack Overflow question:
Title: In Python, how do I determine if an object is iterable?
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p>
<pre><code>hasattr(myObj, '__iter__')
</code></pre>
<p>But I am not sure how fool-proof this is.</p> | <ol>
<li><p>Checking for <code>__iter__</code> works on sequence types, but it would fail on e.g. strings <strong>in Python 2</strong>. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):</p>
<pre><code> try:
some_object_iterator = iter(some_object)
except TypeError as te:
print(some_object, 'is not iterable')
</code></pre>
</li>
</ol>
<p>The <code>iter</code> built-in checks for the <code>__iter__</code> method or in the case of strings the <code>__getitem__</code> method.</p>
<ol start="2">
<li>Another general pythonic approach is to assume an iterable, then fail gracefully if it does not work on the given object. The Python glossary:</li>
</ol>
<blockquote>
<p>Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a <strong>duck</strong> and quacks like a <strong>duck</strong>, it must be a <strong>duck</strong>.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). <strong>Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.</strong></p>
</blockquote>
<blockquote>
<p>...</p>
</blockquote>
<blockquote>
<pre><code>try:
_ = (e for e in my_object)
except TypeError:
print my_object, 'is not iterable'
</code></pre>
</blockquote>
<ol start="3">
<li><p>The <a href="https://docs.python.org/3/library/collections.abc.html" rel="noreferrer"><code>collections</code></a> module provides some abstract base classes, which allow to ask classes or instances if they provide particular functionality, for example:</p>
<pre><code> from collections.abc import Iterable
if isinstance(e, Iterable):
# e is iterable
</code></pre>
</li>
</ol>
<p>However, this does not check for classes that are iterable through <code>__getitem__</code>.</p> | {
"question_id": 1952464,
"question_date": "2009-12-23T12:13:55.790Z",
"question_score": 1333,
"tags": "python|iterable",
"answer_id": 1952481,
"answer_date": "2009-12-23T12:16:43.617Z",
"answer_score": 976
} |
Please answer the following Stack Overflow question:
Title: What are the differences between NP, NP-Complete and NP-Hard?
<p>What are the differences between <strong>NP</strong>, <strong>NP-Complete</strong> and <strong>NP-Hard</strong>?</p>
<p>I am aware of many resources all over the web. I'd like to read your explanations, and the reason is they might be different from what's out there, or there is something that I'm not aware of.</p> | <p>I assume that you are looking for intuitive definitions, since the technical definitions require quite some time to understand. First of all, let's remember a preliminary needed concept to understand those definitions.</p>
<ul>
<li><strong>Decision problem</strong>: A problem with a <strong>yes</strong> or <strong>no</strong> answer.</li>
</ul>
<hr>
<p>Now, let us define those <em>complexity classes</em>.</p>
<h1>P</h1>
<p><em>P is a complexity class that represents the set of all decision problems that can be solved in polynomial time</em>.</p>
<p>That is, given an instance of the problem, the answer yes or no can be decided in polynomial time.</p>
<p><strong>Example</strong></p>
<p>Given a connected graph <code>G</code>, can its vertices be coloured using two colours so that no edge is monochromatic?</p>
<p>Algorithm: start with an arbitrary vertex, color it red and all of its neighbours blue and continue. Stop when you run out of vertices or you are forced to make an edge have both of its endpoints be the same color.</p>
<hr>
<h1>NP</h1>
<p><em>NP is a complexity class that represents the set of all decision problems for which the instances where the answer is "yes" have proofs that can be verified in polynomial time.</em></p>
<p>This means that if someone gives us an instance of the problem and a certificate (sometimes called a witness) to the answer being yes, we can check that it is correct in polynomial time.</p>
<p><strong>Example</strong></p>
<p><em>Integer factorisation</em> is in NP. This is the problem that given integers <code>n</code> and <code>m</code>, is there an integer <code>f</code> with <code>1 < f < m</code>, such that <code>f</code> divides <code>n</code> (<code>f</code> is a small factor of <code>n</code>)? </p>
<p>This is a decision problem because the answers are yes or no. If someone hands us an instance of the problem (so they hand us integers <code>n</code> and <code>m</code>) and an integer <code>f</code> with <code>1 < f < m</code>, and claim that <code>f</code> is a factor of <code>n</code> (the certificate), we can check the answer in <em>polynomial time</em> by performing the division <code>n / f</code>.</p>
<hr>
<h1>NP-Complete</h1>
<p><em>NP-Complete is a complexity class which represents the set of all problems <code>X</code> in NP for which it is possible to reduce any other NP problem <code>Y</code> to <code>X</code> in polynomial time.</em></p>
<p>Intuitively this means that we can solve <code>Y</code> quickly if we know how to solve <code>X</code> quickly. Precisely, <code>Y</code> is reducible to <code>X</code>, if there is a polynomial time algorithm <code>f</code> to transform instances <code>y</code> of <code>Y</code> to instances <code>x = f(y)</code> of <code>X</code> in polynomial time, with the property that the answer to <code>y</code> is yes, if and only if the answer to <code>f(y)</code> is yes.</p>
<p><strong>Example</strong> </p>
<p><code>3-SAT</code>. This is the problem wherein we are given a conjunction (ANDs) of 3-clause disjunctions (ORs), statements of the form</p>
<pre><code>(x_v11 OR x_v21 OR x_v31) AND
(x_v12 OR x_v22 OR x_v32) AND
... AND
(x_v1n OR x_v2n OR x_v3n)
</code></pre>
<p>where each <code>x_vij</code> is a boolean variable or the negation of a variable from a finite predefined list <code>(x_1, x_2, ... x_n)</code>. </p>
<p>It can be shown that <em>every NP problem can be reduced to 3-SAT</em>. The proof of this is technical and requires use of the technical definition of NP (<em>based on non-deterministic Turing machines</em>). This is known as <em>Cook's theorem</em>.</p>
<p>What makes NP-complete problems important is that if a deterministic polynomial time algorithm can be found to solve one of them, every NP problem is solvable in polynomial time (one problem to rule them all).</p>
<hr>
<h1>NP-hard</h1>
<p>Intuitively, these are the problems that are <em>at least as hard as the NP-complete problems</em>. Note that NP-hard problems <em>do not have to be in NP</em>, and <em>they do not have to be decision problems</em>. </p>
<p>The precise definition here is that <em>a problem <code>X</code> is NP-hard, if there is an NP-complete problem <code>Y</code>, such that <code>Y</code> is reducible to <code>X</code> in polynomial time</em>.</p>
<p>But since any NP-complete problem can be reduced to any other NP-complete problem in polynomial time, all NP-complete problems can be reduced to any NP-hard problem in polynomial time. Then, if there is a solution to one NP-hard problem in polynomial time, there is a solution to all NP problems in polynomial time.</p>
<p><strong>Example</strong></p>
<p>The <a href="https://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">halting problem</a> is an NP-hard problem. This is the problem that given a program <code>P</code> and input <code>I</code>, will it halt? This is a decision problem but it is not in NP. It is clear that any NP-complete problem can be reduced to this one. As another example, any NP-complete problem is NP-hard.</p>
<p>My favorite NP-complete problem is the <a href="http://web.mat.bham.ac.uk/R.W.Kaye/minesw/ordmsw.htm" rel="noreferrer">Minesweeper problem</a>.</p>
<hr>
<h1>P = NP</h1>
<p>This one is the most famous problem in computer science, and one of the most important outstanding questions in the mathematical sciences. In fact, the <a href="http://www.claymath.org/millennium-problems/p-vs-np-problem" rel="noreferrer">Clay Institute</a> is offering one million dollars for a solution to the problem (Stephen Cook's <a href="http://www.claymath.org/sites/default/files/pvsnp.pdf" rel="noreferrer">writeup</a> on the Clay website is quite good). </p>
<p>It's clear that P is a subset of NP. The open question is whether or not NP problems have deterministic polynomial time solutions. It is largely believed that they do not. Here is an outstanding recent article on the latest (and the importance) of the P = NP problem: <a href="http://cacm.acm.org/magazines/2009/9/38904-the-status-of-the-p-versus-np-problem/fulltext" rel="noreferrer">The Status of the P versus NP problem</a>. </p>
<p>The best book on the subject is <a href="https://rads.stackoverflow.com/amzn/click/com/0716710455" rel="noreferrer" rel="nofollow noreferrer">Computers and Intractability</a> by Garey and Johnson. </p> | {
"question_id": 1857244,
"question_date": "2009-12-07T01:11:36.183Z",
"question_score": 1333,
"tags": "computer-science|complexity-theory|np|np-complete|np-hard",
"answer_id": 1857342,
"answer_date": "2009-12-07T01:46:59.497Z",
"answer_score": 1709
} |
Please answer the following Stack Overflow question:
Title: Altering a column: null to not null
<p>I have a table that has several nullable integer columns. This is undesirable for several reasons, so I am looking to update all nulls to 0 and then set these columns to <code>NOT NULL</code>. Aside from changing nulls to <code>0</code>, data must be preserved.</p>
<p>I am looking for the <em>specific SQL syntax</em> to alter a column (call it <code>ColumnA</code>) to "<code>not null</code>". Assume the data has been updated to not contain nulls.</p>
<p>Using <em>SQL server 2000</em>.</p> | <p>First, make all current <code>NULL</code> values disappear:</p>
<pre><code>UPDATE [Table] SET [Column]=0 WHERE [Column] IS NULL
</code></pre>
<p>Then, update the table definition to disallow "NULLs":</p>
<pre><code>ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
</code></pre> | {
"question_id": 689746,
"question_date": "2009-03-27T13:24:29.177Z",
"question_score": 1332,
"tags": "sql-server|tsql|null|alter-table|alter-column",
"answer_id": 689766,
"answer_date": "2009-03-27T13:30:09.223Z",
"answer_score": 2156
} |
Please answer the following Stack Overflow question:
Title: How to pass props to {this.props.children}
<p>I'm trying to find the proper way to define some components which could be used in a generic way:</p>
<pre><code><Parent>
<Child value="1">
<Child value="2">
</Parent>
</code></pre>
<p>There is a logic going on for rendering between parent and children components of course, you can imagine <code><select></code> and <code><option></code> as an example of this logic.</p>
<p>This is a dummy implementation for the purpose of the question:</p>
<pre><code>var Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
var Child = React.createClass({
onClick: function() {
this.props.doSomething(this.props.value); // doSomething is undefined
},
render: function() {
return (<div onClick={this.onClick}></div>);
}
});
</code></pre>
<p>The question is whenever you use <code>{this.props.children}</code> to define a wrapper component, how do you pass down some property to all its children?</p> | <h2>Cloning children with new props</h2>
<p>You can use <a href="https://reactjs.org/docs/react-api.html#reactchildren" rel="nofollow noreferrer"><code>React.Children</code></a> to iterate over the children, and then clone each element with new props (shallow merged) using <a href="https://reactjs.org/docs/react-api.html#cloneelement" rel="nofollow noreferrer"><code>React.cloneElement</code></a>.</p>
<p>See the code comment why I don't recommend this approach.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Child = ({ childName, sayHello }) => (
<button onClick={() => sayHello(childName)}>{childName}</button>
);
function Parent({ children }) {
// We clone and pass this `sayHello` function
// into the child elements.
function sayHello(childName) {
console.log(`Hello from ${childName} the child`);
}
const childrenWithProps = React.Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a
// typescript error too.
if (React.isValidElement(child)) {
return React.cloneElement(child, { sayHello });
}
return child;
});
return <div>{childrenWithProps}</div>
}
function App() {
// This approach is less type-safe and Typescript friendly since it
// looks like you're trying to render `Child` with `sayHello` missing.
// It's also confusing to readers of this code.
return (
<Parent>
<Child childName="Billy" />
<Child childName="Bob" />
</Parent>
);
}
ReactDOM.render(<App />, document.getElementById("container"));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="container"></div></code></pre>
</div>
</div>
</p>
<h2>Calling children as a function</h2>
<p>Alternatively, you can pass props to children via <a href="https://reactjs.org/docs/render-props.html" rel="nofollow noreferrer">render props</a>. In this approach, the children (which can be <code>children</code> or any other prop name) is a function which can accept any arguments you want to pass and returns the actual children:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Child = ({ childName, sayHello }) => (
<button onClick={() => sayHello(childName)}>{childName}</button>
);
function Parent({ children }) {
function sayHello(childName) {
console.log(`Hello from ${childName} the child`);
}
// `children` of this component must be a function
// which returns the actual children. We can pass
// it args to then pass into them as props (in this
// case we pass `sayHello`).
return <div>{children(sayHello)}</div>
}
function App() {
// sayHello is the arg we passed in Parent, which
// we now pass through to Child.
return (
<Parent>
{(sayHello) => (
<React.Fragment>
<Child childName="Billy" sayHello={sayHello} />
<Child childName="Bob" sayHello={sayHello} />
</React.Fragment>
)}
</Parent>
);
}
ReactDOM.render(<App />, document.getElementById("container"));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="container"></div></code></pre>
</div>
</div>
</p> | {
"question_id": 32370994,
"question_date": "2015-09-03T08:47:25.273Z",
"question_score": 1331,
"tags": "javascript|reactjs",
"answer_id": 32371612,
"answer_date": "2015-09-03T09:17:38.250Z",
"answer_score": 1382
} |
Please answer the following Stack Overflow question:
Title: What does "static" mean in C?
<p>I've seen the word <code>static</code> used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)? </p> | <ol>
<li>A static variable inside a function keeps its value between invocations.</li>
<li>A static global variable or a function is "seen" only in the file it's declared in</li>
</ol>
<p>(1) is the more foreign topic if you're a newbie, so here's an example:</p>
<pre><code>#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
</code></pre>
<p>This prints:</p>
<pre><code>a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
</code></pre>
<p>This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.</p>
<p>(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made <code>static</code>, so that the user won't be able to access them. This is encapsulation, a good practice.</p>
<p>Quoting <a href="http://en.wikipedia.org/wiki/Static_variable" rel="noreferrer">Wikipedia</a>:</p>
<blockquote>
<p>In the C programming language, static
is used with global variables and
functions to set their scope to the
containing file. In local variables,
static is used to store the variable
in the statically allocated memory
instead of the automatically allocated
memory. While the language does not
dictate the implementation of either
type of memory, statically allocated
memory is typically reserved in data
segment of the program at compile
time, while the automatically
allocated memory is normally
implemented as a transient call stack.</p>
</blockquote>
<p>And to answer your second question, it's not like in C#.</p>
<p>In C++, however, <code>static</code> is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.</p> | {
"question_id": 572547,
"question_date": "2009-02-21T06:47:52.017Z",
"question_score": 1330,
"tags": "c|syntax|static",
"answer_id": 572550,
"answer_date": "2009-02-21T06:51:55.270Z",
"answer_score": 1757
} |
Please answer the following Stack Overflow question:
Title: Vertical rulers in Visual Studio Code
<h3>Rendering More than One Ruler in VS Code</h3>
<hr />
<p>VS Code's default configuration for a ruler is demonstrated below.</p>
<pre><code> "editor.ruler": 80
</code></pre>
<p>The issue I am having with the default VS Code configuration <em>(as shown above)</em> is that it only renders a single ruler. In the <strong>Sublime Text Editor</strong> I can render as many rulers as I like using the following Sublime configuration.</p>
<pre><code> "rulers": [72, 80, 100, 120]
</code></pre>
<p>Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in <strong>VS Code</strong>?</p> | <p>Visual Studio Code 0.10.10 introduced this feature. To configure it, go to menu <em>File</em> → <em>Preferences</em> → <em>Settings</em> and add this to to your user or workspace settings:</p>
<pre class="lang-json prettyprint-override"><code>"editor.rulers": [80,120]
</code></pre>
<p>The color of the rulers can be customized like this:</p>
<pre class="lang-json prettyprint-override"><code>"workbench.colorCustomizations": {
"editorRuler.foreground": "#ff4081"
}
</code></pre> | {
"question_id": 29968499,
"question_date": "2015-04-30T13:03:08.170Z",
"question_score": 1329,
"tags": "visual-studio-code|configuration",
"answer_id": 29972073,
"answer_date": "2015-04-30T15:39:58.600Z",
"answer_score": 2197
} |
Please answer the following Stack Overflow question:
Title: How do I set/unset a cookie with jQuery?
<p>How do I set and unset a cookie using jQuery, for example create a cookie named <code>test</code> and set the value to <code>1</code>?</p> | <p><strong>Update April 2019</strong></p>
<p>jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.</p>
<p>Go to <a href="https://github.com/js-cookie/js-cookie" rel="noreferrer">https://github.com/js-cookie/js-cookie</a> instead, and use the library there that doesn't depend on jQuery.</p>
<p>Basic examples:</p>
<pre><code>// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'
</code></pre>
<p>See the docs on github for details.</p>
<hr />
<p><strong>Before April 2019 (old)</strong></p>
<p>See the plugin:</p>
<p><a href="https://github.com/carhartl/jquery-cookie" rel="noreferrer">https://github.com/carhartl/jquery-cookie</a></p>
<p>You can then do:</p>
<pre><code>$.cookie("test", 1);
</code></pre>
<p>To delete:</p>
<pre><code>$.removeCookie("test");
</code></pre>
<p>Additionally, to set a timeout of a certain number of days (10 here) on the cookie:</p>
<pre><code>$.cookie("test", 1, { expires : 10 });
</code></pre>
<p>If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.</p>
<p>To cover all the options:</p>
<pre><code>$.cookie("test", 1, {
expires : 10, // Expires in 10 days
path : '/', // The value of the path attribute of the cookie
// (Default: path of page that created the cookie).
domain : 'jquery.com', // The value of the domain attribute of the cookie
// (Default: domain of page that created the cookie).
secure : true // If set to true the secure attribute of the cookie
// will be set and the cookie transmission will
// require a secure protocol (defaults to false).
});
</code></pre>
<p>To read back the value of the cookie:</p>
<pre><code>var cookieValue = $.cookie("test");
</code></pre>
<p><strong>UPDATE (April 2015):</strong></p>
<p>As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (<a href="https://github.com/js-cookie/js-cookie" rel="noreferrer">https://github.com/js-cookie/js-cookie</a>) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.</p> | {
"question_id": 1458724,
"question_date": "2009-09-22T08:09:50.670Z",
"question_score": 1327,
"tags": "javascript|jquery|dom|cookies",
"answer_id": 1458728,
"answer_date": "2009-09-22T08:11:20.883Z",
"answer_score": 1862
} |
Please answer the following Stack Overflow question:
Title: SOAP vs REST (differences)
<p>I have read articles about the differences between SOAP and REST as a web service communication protocol, but I think that the biggest advantages for REST over SOAP are: </p>
<ol>
<li><p>REST is more dynamic, no need to create and update UDDI(Universal Description, Discovery, and Integration).</p></li>
<li><p>REST is not restricted to only XML format. RESTful web services can send plain text/JSON/XML.</p></li>
</ol>
<p>But SOAP is more standardized (E.g.: security).</p>
<p>So, am I correct in these points?</p> | <p>Unfortunately, there are a lot of misinformation and misconceptions around REST. Not only your question and the <a href="https://stackoverflow.com/a/19884368/282110">answer by @cmd</a> reflect those, but most of the questions and answers related to the subject on Stack Overflow.</p>
<p>SOAP and REST can't be compared directly, since the first is a protocol (or at least tries to be) and the second is an architectural style. This is probably one of the sources of confusion around it, since people tend to call REST any HTTP API that isn't SOAP.</p>
<p>Pushing things a little and trying to establish a comparison, the main difference between SOAP and REST is the degree of coupling between client and server implementations. A SOAP client works like a custom desktop application, tightly coupled to the server. There's a rigid contract between client and server, and everything is expected to break if either side changes anything. You need constant updates following any change, but it's easier to ascertain if the contract is being followed.</p>
<p>A REST client is more like a browser. It's a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. You don't violate the protocol standards by creating extra methods, you leverage on the standard methods and create the actions with them on your media type. If done right, there's less coupling, and changes can be dealt with more gracefully. A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. In SOAP, the client needs previous knowledge on everything it will be using, or it won't even begin the interaction. Additionally, a REST client can be extended by code-on-demand supplied by the server itself, the classical example being JavaScript code used to drive the interaction with another service on the client-side.</p>
<p>I think these are the crucial points to understand what REST is about, and how it differs from SOAP:</p>
<ul>
<li><p>REST is protocol independent. It's not coupled to HTTP. Pretty much like you can follow an ftp link on a website, a REST application can use any protocol for which there is a standardized URI scheme.</p></li>
<li><p>REST is not a mapping of CRUD to HTTP methods. Read <a href="https://stackoverflow.com/questions/19843480/s3-rest-api-and-post-method/19844272#19844272">this</a> answer for a detailed explanation on that.</p></li>
<li><p>REST is as standardized as the parts you're using. Security and authentication in HTTP are standardized, so that's what you use when doing REST over HTTP.</p></li>
<li><p>REST is not REST without <a href="https://stackoverflow.com/a/29586455/1202421">hypermedia</a> and <a href="http://en.wikipedia.org/wiki/HATEOAS" rel="noreferrer">HATEOAS</a>. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.</p></li>
<li><p>REST is the architectural style of the web itself. When you enter Stack Overflow, you know what a User, a Question and an Answer are, you know the media types, and the website provides you with the links to them. A REST API has to do the same. If we designed the web the way people think REST should be done, instead of having a home page with links to Questions and Answers, we'd have a static documentation explaining that in order to view a question, you have to take the URI <code>stackoverflow.com/questions/<id></code>, replace id with the Question.id and paste that on your browser. That's nonsense, but that's what many people think REST is.</p></li>
</ul>
<p>This last point can't be emphasized enough. If your clients are building URIs from templates in documentation and not getting links in the resource representations, that's not REST. Roy Fielding, the author of REST, made it clear on this blog post: <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven" rel="noreferrer">REST APIs must be hypertext-driven</a>. </p>
<p>With the above in mind, you'll realize that while REST might not be restricted to XML, to do it correctly with any other format you'll have to design and standardize some format for your links. Hyperlinks are standard in XML, but not in JSON. There are draft standards for JSON, like <a href="http://stateless.co/hal_specification.html" rel="noreferrer">HAL</a>.</p>
<p>Finally, REST isn't for everyone, and a proof of that is how most people solve their problems very well with the HTTP APIs they mistakenly called REST and never venture beyond that. REST is hard to do sometimes, especially in the beginning, but it pays over time with easier evolution on the server side, and client's resilience to changes. If you need something done quickly and easily, don't bother about getting REST right. It's probably not what you're looking for. If you need something that will have to stay online for years or even decades, then REST is for you.</p> | {
"question_id": 19884295,
"question_date": "2013-11-09T23:11:49.050Z",
"question_score": 1326,
"tags": "rest|web-services|http|soap|definition",
"answer_id": 19884975,
"answer_date": "2013-11-10T00:45:24.517Z",
"answer_score": 1834
} |
Please answer the following Stack Overflow question:
Title: How to extend an existing JavaScript array with another array, without creating a new array
<p>There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's <code>extend</code> method.</p>
<p>I want to achieve the following:</p>
<pre><code>>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]
</code></pre>
<p>I know there's a <code>a.concat(b)</code> method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when <code>a</code> is significantly larger than <code>b</code> (i.e. one that does not copy <code>a</code>).</p>
<p><sub><em><strong>Note:</strong> This is <strong>not a duplicate of <a href="https://stackoverflow.com/questions/351409/appending-to-array">How to append something to an array?</a></strong> -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.</em></sub></p> | <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" rel="noreferrer"><code>.push</code></a> method can take multiple arguments. You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator" rel="noreferrer">spread operator</a> to pass all the elements of the second array as arguments to <code>.push</code>:</p>
<pre><code>>>> a.push(...b)
</code></pre>
<p>If your browser does not support ECMAScript 6, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" rel="noreferrer"><code>.apply</code></a> instead:</p>
<pre><code>>>> a.push.apply(a, b)
</code></pre>
<p>Or perhaps, if you think it's clearer:</p>
<pre><code>>>> Array.prototype.push.apply(a,b)
</code></pre>
<p>Please note that all these solutions will fail with a stack overflow error if array <code>b</code> is too long (trouble starts at about 100,000 elements, depending on the browser).<br>
If you cannot guarantee that <code>b</code> is short enough, you should use a standard loop-based technique described in the other answer.</p> | {
"question_id": 1374126,
"question_date": "2009-09-03T15:27:30.933Z",
"question_score": 1326,
"tags": "javascript|arrays|concatenation",
"answer_id": 1374131,
"answer_date": "2009-09-03T15:27:55.563Z",
"answer_score": 1980
} |
Please answer the following Stack Overflow question:
Title: Multiline string literal in C#
<p>Is there an easy way to create a multiline string literal in C#?</p>
<p>Here's what I have now:</p>
<pre><code>string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
</code></pre>
<p>I know PHP has</p>
<pre><code><<<BLOCK
BLOCK;
</code></pre>
<p>Does C# have something similar?</p> | <p>You can use the <code>@</code> symbol in front of a <code>string</code> to form a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim" rel="noreferrer">verbatim string literal</a>:</p>
<pre><code>string query = @"SELECT foo, bar
FROM table
WHERE id = 42";
</code></pre>
<p>You also <a href="http://www.peachpit.com/articles/article.aspx?p=31938&seqNum=10" rel="noreferrer">do not have to escape special characters</a> when you use this method, except for double quotes as shown in Jon Skeet's answer.</p> | {
"question_id": 1100260,
"question_date": "2009-07-08T20:03:34.677Z",
"question_score": 1325,
"tags": "c#|string|shorthand",
"answer_id": 1100265,
"answer_date": "2009-07-08T20:04:47.937Z",
"answer_score": 1977
} |
Please answer the following Stack Overflow question:
Title: How do you use bcrypt for hashing passwords in PHP?
<p>Every now and then I hear the advice "Use bcrypt for storing passwords in PHP, bcrypt rules".</p>
<p>But what is <code>bcrypt</code>? PHP doesn't offer any such functions, Wikipedia babbles about a file-encryption utility and Web searches just reveal a few implementations of <a href="http://en.wikipedia.org/wiki/Blowfish_%28cipher%29" rel="noreferrer">Blowfish</a> in different languages. Now Blowfish is also available in PHP via <code>mcrypt</code>, but how does that help with storing passwords? Blowfish is a general purpose cipher, it works two ways. If it could be encrypted, it can be decrypted. Passwords need a one-way hashing function.</p>
<p>What is the explanation?</p> | <p><code>bcrypt</code> is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password <a href="https://en.wikipedia.org/wiki/Salt_%28cryptography%29" rel="noreferrer">salts</a> (<code>bcrypt</code> REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.</p>
<p><code>bcrypt</code> uses the <em>Eksblowfish</em> algorithm to hash passwords. While the encryption phase of <em>Eksblowfish</em> and <em>Blowfish</em> are exactly the same, the key schedule phase of <em>Eksblowfish</em> ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. <strong>Because of this key difference, <code>bcrypt</code> is a one-way hashing algorithm.</strong> You cannot retrieve the plain text password without already knowing the salt, rounds <strong>and key</strong> (password). [<a href="http://www.usenix.org/events/usenix99/provos/provos_html/node4.html" rel="noreferrer">Source</a>]</p>
<h1>How to use bcrypt:</h1>
<h2>Using PHP >= 5.5-DEV</h2>
<p>Password hashing functions <a href="http://php.net/password_hash" rel="noreferrer">have now been built directly into PHP >= 5.5</a>. You may now use <a href="http://php.net/password_hash" rel="noreferrer"><code>password_hash()</code></a> to create a <code>bcrypt</code> hash of any password:</p>
<pre><code><?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
// Usage 2:
$options = [
'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
</code></pre>
<p>To verify a user provided password against an existing hash, you may use the <a href="http://php.net/password_verify" rel="noreferrer"><code>password_verify()</code></a> as such:</p>
<pre><code><?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
</code></pre>
<h2>Using PHP >= 5.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)</h2>
<p>There is a <a href="https://github.com/ircmaxell/password_compat" rel="noreferrer">compatibility library</a> on <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a> created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).</p>
<h2>Using PHP < 5.3.7 <em>(DEPRECATED)</em></h2>
<p>You can use <code>crypt()</code> function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. <strong>If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library</strong>. This alternative is provided only for historical purposes.</p>
<pre><code>class Bcrypt{
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input){
$hash = crypt($input, $this->getSalt());
if (strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash){
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt(){
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count){
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input){
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (true);
return $output;
}
}
</code></pre>
<p>You can use this code like this:</p>
<pre><code>$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
</code></pre>
<p>Alternatively, you may also use the <a href="http://www.openwall.com/phpass/" rel="noreferrer">Portable PHP Hashing Framework</a>.</p> | {
"question_id": 4795385,
"question_date": "2011-01-25T15:34:04.780Z",
"question_score": 1325,
"tags": "php|passwords|cryptography|password-protection|bcrypt",
"answer_id": 6337021,
"answer_date": "2011-06-13T22:11:39.987Z",
"answer_score": 1107
} |
Please answer the following Stack Overflow question:
Title: Passing parameters to a Bash function
<p>I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the <em>command line</em>.</p>
<p>I would like to pass parameters within my script. I tried:</p>
<pre><code>myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
</code></pre>
<p>But the syntax is not correct. How can I pass a parameter to my function?</p> | <p>There are two typical ways of declaring a function. I prefer the second approach.</p>
<pre><code>function function_name {
command...
}
</code></pre>
<p>or</p>
<pre><code>function_name () {
command...
}
</code></pre>
<p>To call a function with arguments:</p>
<pre><code>function_name "$arg1" "$arg2"
</code></pre>
<p>The function refers to passed arguments by their position (not by name), that is <code>$1</code>, <code>$2</code>, and so forth. <strong><code>$0</code></strong> is the name of the script itself.</p>
<p>Example:</p>
<pre><code>function_name () {
echo "Parameter #1 is $1"
}
</code></pre>
<p>Also, you need to call your function <strong>after</strong> it is declared.</p>
<pre><code>#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
</code></pre>
<p><strong>Output:</strong></p>
<pre class="lang-none prettyprint-override"><code>./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
</code></pre>
<p><a href="http://tldp.org/LDP/abs/html/complexfunct.html" rel="noreferrer">Reference: Advanced Bash-Scripting Guide</a>.</p> | {
"question_id": 6212219,
"question_date": "2011-06-02T08:35:17.493Z",
"question_score": 1324,
"tags": "bash|function|parameters|arguments",
"answer_id": 6212408,
"answer_date": "2011-06-02T08:57:02.240Z",
"answer_score": 2067
} |
Please answer the following Stack Overflow question:
Title: Create a tag in a GitHub repository
<p>I have a repository in GitHub and I need to <strong>tag</strong> it.<br>
I tagged in a shell, but on <strong>GitHub</strong>, it is not showing up. </p>
<p>Do I have to do anything else?</p>
<p>The command I used in the shell is:</p>
<pre><code>git tag 2.0
</code></pre>
<p>And now when I type <code>git tag</code> it shows:</p>
<pre><code>2.0
</code></pre>
<p>So it seems like tags are present, correct?</p>
<p>The repository is: <a href="https://github.com/keevitaja/myseo-pyrocms" rel="noreferrer">https://github.com/keevitaja/myseo-pyrocms</a>.</p>
<p>How do I make this tag show up on GitHub? Where are my tags?</p> | <p>You can create tags for GitHub by either using:</p>
<ul>
<li>the Git command line, or</li>
<li>GitHub's web interface.</li>
</ul>
<h2>Creating tags from the command line</h2>
<p>To create a tag on your current branch, run this:</p>
<pre><code>git tag <tagname>
</code></pre>
<p>If you want to include a description with your tag, add <code>-a</code> to create an <a href="https://stackoverflow.com/questions/11514075/what-is-the-difference-between-an-annotated-and-unannotated-tag">annotated tag</a>:</p>
<pre><code>git tag <tagname> -a
</code></pre>
<p>This will create a <code>local</code> tag with the current state of the branch you are on. When pushing to your remote repo, tags are NOT included by default. You will need to explicitly say that you want to push your tags to your remote repo:</p>
<pre><code>git push origin --tags
</code></pre>
<p>From the <a href="https://www.kernel.org/pub/software/scm/git/docs/git-push.html" rel="noreferrer">official Linux Kernel Git documentation for <code>git push</code></a>:</p>
<blockquote>
<pre><code>--tags
</code></pre>
<p>All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.</p>
</blockquote>
<p>Or if you just want to push a single tag:</p>
<pre><code>git push origin <tag>
</code></pre>
<p>See also my answer to <a href="https://stackoverflow.com/questions/5195859/push-a-tag-to-a-remote-repository-using-git/23217431#23217431">How do you push a tag to a remote repository using Git?</a> for more details about that syntax above.</p>
<h2>Creating tags through GitHub's web interface</h2>
<p>You can find GitHub's instructions for this at their <a href="https://help.github.com/articles/creating-releases" rel="noreferrer">Creating Releases help page</a>. Here is a summary:</p>
<ol>
<li><p>Click the <strong>releases</strong> link on our repository page,</p>
<p><img src="https://i.stack.imgur.com/uHyjG.png" alt="Screenshot 1"></p></li>
<li><p>Click on <strong>Create a new release</strong> or <strong>Draft a new release</strong>,</p>
<p><img src="https://i.stack.imgur.com/MMAgk.png" alt="Screenshot 2"></p></li>
<li><p>Fill out the form fields, then click <strong>Publish release</strong> at the bottom,</p>
<p><img src="https://i.stack.imgur.com/KArgA.png" alt="Screenshot 3">
<img src="https://i.stack.imgur.com/QzIbj.png" alt="Screenshot 4"></p></li>
<li><p>After you create your tag on GitHub, you might want to fetch it into your local repository too:</p>
<pre><code>git fetch
</code></pre></li>
</ol>
<p>Now next time, you may want to create one more tag within the same release from website. For that follow these steps:</p>
<p>Go to release tab</p>
<ol>
<li><p>Click on edit button for the release</p></li>
<li><p>Provide name of the new tag ABC_DEF_V_5_3_T_2 and hit tab</p></li>
<li><p>After hitting tab, UI will show this message: Excellent! This tag will be created from the target when you publish this release. Also UI will provide an option to select the branch/commit</p></li>
<li><p>Select branch or commit</p></li>
<li><p>Check "This is a pre-release" checkbox for qa tag and uncheck it if the tag is created for Prod tag.</p></li>
<li><p>After that click on "Update Release"</p></li>
<li><p>This will create a new Tag within the existing Release.</p></li>
</ol> | {
"question_id": 18216991,
"question_date": "2013-08-13T18:56:52.580Z",
"question_score": 1324,
"tags": "git|github|git-tag",
"answer_id": 18223354,
"answer_date": "2013-08-14T04:42:11.233Z",
"answer_score": 2156
} |
Please answer the following Stack Overflow question:
Title: \d less efficient than [0-9]
<p>I made a comment yesterday on an answer where someone had used <code>[0123456789]</code> in a regex rather than <code>[0-9]</code> or <code>\d</code>. I said it was probably more efficient to use a range or digit specifier than a character set.</p>
<p>I decided to test that out today and found out to my surprise that (in the c# regex engine at least) <code>\d</code> appears to be less efficient than either of the other two which don't seem to differ much. Here is my test output over 10000 random strings of 1000 random characters with 5077 actually containing a digit:</p>
<pre><code>Regex \d took 00:00:00.2141226 result: 5077/10000
Regex [0-9] took 00:00:00.1357972 result: 5077/10000 63.42 % of first
Regex [0123456789] took 00:00:00.1388997 result: 5077/10000 64.87 % of first
</code></pre>
<p>It's a surprise to me for two reasons, that I would be interested if anyone can shed some light on:</p>
<ol>
<li>I would have thought the range would be implemented much more efficiently than the set.</li>
<li>I can't understand why <code>\d</code> is worse than <code>[0-9]</code>. Is there more to <code>\d</code> than simply shorthand for <code>[0-9]</code>?</li>
</ol>
<p>Here is the test code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace SO_RegexPerformance
{
class Program
{
static void Main(string[] args)
{
var rand = new Random(1234);
var strings = new List<string>();
//10K random strings
for (var i = 0; i < 10000; i++)
{
//generate random string
var sb = new StringBuilder();
for (var c = 0; c < 1000; c++)
{
//add a-z randomly
sb.Append((char)('a' + rand.Next(26)));
}
//in roughly 50% of them, put a digit
if (rand.Next(2) == 0)
{
//replace 1 char with a digit 0-9
sb[rand.Next(sb.Length)] = (char)('0' + rand.Next(10));
}
strings.Add(sb.ToString());
}
var baseTime = testPerfomance(strings, @"\d");
Console.WriteLine();
var testTime = testPerfomance(strings, "[0-9]");
Console.WriteLine(" {0:P2} of first", testTime.TotalMilliseconds / baseTime.TotalMilliseconds);
testTime = testPerfomance(strings, "[0123456789]");
Console.WriteLine(" {0:P2} of first", testTime.TotalMilliseconds / baseTime.TotalMilliseconds);
}
private static TimeSpan testPerfomance(List<string> strings, string regex)
{
var sw = new Stopwatch();
int successes = 0;
var rex = new Regex(regex);
sw.Start();
foreach (var str in strings)
{
if (rex.Match(str).Success)
{
successes++;
}
}
sw.Stop();
Console.Write("Regex {0,-12} took {1} result: {2}/{3}", regex, sw.Elapsed, successes, strings.Count);
return sw.Elapsed;
}
}
}
</code></pre> | <p><code>\d</code> checks all Unicode digits, while <code>[0-9]</code> is limited to these 10 characters. For example, <a href="http://en.wikipedia.org/wiki/Persian_language" rel="noreferrer">Persian</a> digits, <code>۱۲۳۴۵۶۷۸۹</code>, are an example of Unicode digits which are matched with <code>\d</code>, but not <code>[0-9]</code>.</p>
<p>You can generate a list of all such characters using the following code:</p>
<pre><code>var sb = new StringBuilder();
for(UInt16 i = 0; i < UInt16.MaxValue; i++)
{
string str = Convert.ToChar(i).ToString();
if (Regex.IsMatch(str, @"\d"))
sb.Append(str);
}
Console.WriteLine(sb.ToString());
</code></pre>
<p>Which generates:</p>
<blockquote>
<p>0123456789٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹߀߁߂߃߄߅߆߇߈߉०१२३४५६७८९০১২৩৪৫৬৭৮৯੦੧੨੩੪੫੬੭੮੯૦૧૨૩૪૫૬૭૮૯୦୧୨୩୪୫୬୭୮୯௦௧௨௩௪௫௬௭௮௯౦౧౨౩౪౫౬౭౮౯೦೧೨೩೪೫೬೭೮೯൦൧൨൩൪൫൬൭൮൯๐๑๒๓๔๕๖๗๘๙໐໑໒໓໔໕໖໗໘໙༠༡༢༣༤༥༦༧༨༩၀၁၂၃၄၅၆၇၈၉႐႑႒႓႔႕႖႗႘႙០១២៣៤៥៦៧៨៩᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙꘠꘡꘢꘣꘤꘥꘦꘧꘨꘩꣐꣑꣒꣓꣔꣕꣖꣗꣘꣙꤀꤁꤂꤃꤄꤅꤆꤇꤈꤉꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙0123456789</p>
</blockquote> | {
"question_id": 16621738,
"question_date": "2013-05-18T07:18:40.740Z",
"question_score": 1324,
"tags": "c#|regex|performance",
"answer_id": 16621778,
"answer_date": "2013-05-18T07:24:11.783Z",
"answer_score": 1639
} |
Please answer the following Stack Overflow question:
Title: Recommended way to embed PDF in HTML?
<p>What is the recommended way to embed PDF in HTML?</p>
<ul>
<li>iFrame? </li>
<li>Object? </li>
<li>Embed?</li>
</ul>
<p>What does Adobe say itself about it?</p>
<p>In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.</p> | <p>Probably the best approach is to use the <a href="https://mozilla.github.io/pdf.js/" rel="noreferrer">PDF.JS</a> library. It's a pure <a href="https://en.wikipedia.org/wiki/HTML5" rel="noreferrer">HTML5</a>/<a href="https://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> renderer for PDF documents without any third-party plugins.</p>
<p>Online demo:
<a href="https://mozilla.github.io/pdf.js/web/viewer.html" rel="noreferrer">https://mozilla.github.io/pdf.js/web/viewer.html</a></p>
<p>GitHub:
<a href="https://github.com/mozilla/pdf.js" rel="noreferrer">https://github.com/mozilla/pdf.js</a></p> | {
"question_id": 291813,
"question_date": "2008-11-14T23:55:13Z",
"question_score": 1323,
"tags": "html|pdf",
"answer_id": 291823,
"answer_date": "2008-11-15T00:01:51.410Z",
"answer_score": 594
} |
Please answer the following Stack Overflow question:
Title: How can I list the tables in a SQLite database file that was opened with ATTACH?
<p>What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the <code>ATTACH</code> command on the SQLite 3 command line tool?</p> | <p>The <code>.tables</code>, and <code>.schema</code> "helper" functions don't look into ATTACHed databases: they just query the <code>SQLITE_MASTER</code> table for the "main" database. Consequently, if you used</p>
<pre><code>ATTACH some_file.db AS my_db;
</code></pre>
<p>then you need to do</p>
<pre><code>SELECT name FROM my_db.sqlite_master WHERE type='table';
</code></pre>
<p>Note that temporary tables don't show up with <code>.tables</code> either: you have to list <code>sqlite_temp_master</code> for that:</p>
<pre><code>SELECT name FROM sqlite_temp_master WHERE type='table';
</code></pre> | {
"question_id": 82875,
"question_date": "2008-09-17T12:59:53.633Z",
"question_score": 1323,
"tags": "sql|database|sqlite|metadata",
"answer_id": 83195,
"answer_date": "2008-09-17T13:30:00.113Z",
"answer_score": 660
} |
Please answer the following Stack Overflow question:
Title: .gitignore exclude folder but include specific subfolder
<p>I have the folder <code>application/</code> which I add to the <code>.gitignore</code>. Inside the <code>application/</code> folder is the folder <code>application/language/gr</code>. How can I include this folder?</p>
<p>I've tried this</p>
<pre><code>application/
!application/language/gr/
</code></pre> | <p>If you exclude <code>application/</code>, then everything under it will always be excluded (even if some later negative exclusion pattern (“unignore”) might match something under <code>application/</code>).</p>
<p>To do what you want, you have to “unignore” every parent directory of anything that you want to “unignore”. Usually you end up writing rules for this situation in pairs: ignore everything in a directory, but not some certain subdirectory.</p>
<pre><code># you can skip this first one if it is not already excluded by prior patterns
!application/
application/*
!application/language/
application/language/*
!application/language/gr/
</code></pre>
<p><strong>Note</strong><br>
The trailing <code>/*</code> is significant: </p>
<ul>
<li>The pattern <code>dir/</code> excludes a directory named <code>dir</code> and (implicitly) everything under it.<br>
With <code>dir/</code>, Git will never look at anything under <code>dir</code>, and thus will never apply any of the “un-exclude” patterns to anything under <code>dir</code>.</li>
<li>The pattern <code>dir/*</code> says nothing about <code>dir</code> itself; it just excludes everything under <code>dir</code>.
With <code>dir/*</code>, Git will process the direct contents of <code>dir</code>, giving other patterns a chance to “un-exclude” some bit of the content (<code>!dir/sub/</code>). </li>
</ul> | {
"question_id": 5533050,
"question_date": "2011-04-03T22:48:48.040Z",
"question_score": 1323,
"tags": "git|gitignore",
"answer_id": 5534865,
"answer_date": "2011-04-04T05:22:35.837Z",
"answer_score": 2128
} |
Please answer the following Stack Overflow question:
Title: How can I declare and use Boolean variables in a shell script?
<p>I tried to declare a Boolean variable in a shell script using the following syntax:</p>
<pre><code>variable=$false
variable=$true
</code></pre>
<p>Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?</p>
<pre><code>if [ $variable ]
if [ !$variable ]
</code></pre> | <p><strong>Revised Answer (Feb 12, 2014)</strong></p>
<pre><code>the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
echo 'Be careful not to fall off!'
fi
</code></pre>
<hr>
<p><strong>Original Answer</strong></p>
<p>Caveats: <a href="https://stackoverflow.com/a/21210966/89391">https://stackoverflow.com/a/21210966/89391</a></p>
<pre><code>the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
echo 'Be careful not to fall off!'
fi
</code></pre>
<p>From: <a href="https://github.com/aperezdc/perezdecastro.org/blob/master/stash/using-boolean-variables-in-bash.markdown" rel="noreferrer">Using boolean variables in Bash</a></p>
<p><em>The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin <code>true</code> on Jun 2, 2010 only applies to the original answer, not the revised.</em></p> | {
"question_id": 2953646,
"question_date": "2010-06-01T21:54:53.247Z",
"question_score": 1321,
"tags": "bash|shell|scripting|boolean|sh",
"answer_id": 2953673,
"answer_date": "2010-06-01T21:58:55.187Z",
"answer_score": 1581
} |
Please answer the following Stack Overflow question:
Title: Difference between "wait()" vs "sleep()" in Java
<p>What is the difference between a <code>wait()</code> and <code>sleep()</code> in Threads?</p>
<p>Is my understanding that a <code>wait()</code>-ing Thread is still in running mode and uses CPU cycles but a <code>sleep()</code>-ing does not consume any CPU cycles correct?</p>
<p>Why do we have <em>both</em> <code>wait()</code> and <code>sleep()</code>?</p>
<p>How does their implementation vary at a lower level?</p> | <p>A <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#wait%28%29" rel="noreferrer"><code>wait</code></a> can be "woken up" by another thread calling <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notify%28%29" rel="noreferrer"><code>notify</code></a> on the monitor which is being waited on whereas a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#sleep%28long%29" rel="noreferrer"><code>sleep</code></a> cannot. Also a <code>wait</code> (and <code>notify</code>) must happen in a block <code>synchronized</code> on the monitor object whereas <code>sleep</code> does not:</p>
<pre><code>Object mon = ...;
synchronized (mon) {
mon.wait();
}
</code></pre>
<p>At this point the currently executing thread waits <em>and releases the monitor</em>. Another thread may do</p>
<pre><code>synchronized (mon) { mon.notify(); }
</code></pre>
<p>(on the same <code>mon</code> object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up. </p>
<p>You can also call <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notifyAll%28%29" rel="noreferrer"><code>notifyAll</code></a> if more than one thread is waiting on the monitor – this will wake <em>all of them up</em>. However, only one of the threads will be able to grab the monitor (remember that the <code>wait</code> is in a <code>synchronized</code> block) and carry on – the others will then be blocked until they can acquire the monitor's lock.</p>
<p>Another point is that you call <code>wait</code> on <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html" rel="noreferrer"><code>Object</code></a> itself (i.e. you wait on an object's monitor) whereas you call <code>sleep</code> on <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html" rel="noreferrer"><code>Thread</code></a>.</p>
<p>Yet another point is that you can get <em>spurious wakeups</em> from <code>wait</code> (i.e. the thread which is waiting resumes for no apparent reason). You should <strong>always <code>wait</code> whilst spinning on some condition</strong> as follows: </p>
<pre><code>synchronized {
while (!condition) { mon.wait(); }
}
</code></pre> | {
"question_id": 1036754,
"question_date": "2009-06-24T06:48:40.960Z",
"question_score": 1321,
"tags": "java|multithreading|wait|sleep|java-threads",
"answer_id": 1036763,
"answer_date": "2009-06-24T06:50:17.133Z",
"answer_score": 894
} |
Please answer the following Stack Overflow question:
Title: UTF-8 all the way through
<p>
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.</p>
<p>Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?</p>
<p>This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.</p> | <p><strong>Data Storage</strong>:</p>
<ul>
<li><p>Specify the <code>utf8mb4</code> character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use <code>utf8mb4</code> encoding if a <code>utf8mb4_*</code> collation is specified (without any explicit character set).</p>
</li>
<li><p>In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply <code>utf8</code>, which only supports a subset of Unicode characters. I wish I were kidding.</p>
</li>
</ul>
<p><strong>Data Access</strong>:</p>
<ul>
<li><p>In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to <code>utf8mb4</code>. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.</p>
</li>
<li><p>Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:</p>
<ul>
<li><p>If you're using the <a href="http://www.php.net/manual/en/book.pdo.php" rel="noreferrer">PDO</a> abstraction layer with PHP ≥ 5.3.6, you can specify <code>charset</code> in the <a href="http://php.net/manual/en/ref.pdo-mysql.connection.php" rel="noreferrer">DSN</a>:</p>
<pre><code> $dbh = new PDO('mysql:charset=utf8mb4');
</code></pre>
</li>
<li><p>If you're using <a href="http://www.php.net/manual/en/book.mysqli.php" rel="noreferrer">mysqli</a>, you can call <a href="http://php.net/manual/en/mysqli.set-charset.php" rel="noreferrer"><code>set_charset()</code></a>:</p>
<pre><code> $mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
</code></pre>
</li>
<li><p>If you're stuck with plain <a href="http://php.net/manual/en/book.mysql.php" rel="noreferrer">mysql</a> but happen to be running PHP ≥ 5.2.3, you can call <a href="http://php.net/manual/en/function.mysql-set-charset.php" rel="noreferrer"><code>mysql_set_charset</code></a>.</p>
</li>
</ul>
</li>
<li><p>If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: <a href="http://dev.mysql.com/doc/en/charset-connection.html" rel="noreferrer"><code>SET NAMES 'utf8mb4'</code></a>.</p>
</li>
<li><p>The same consideration regarding <code>utf8mb4</code>/<code>utf8</code> applies as above.</p>
</li>
</ul>
<p><strong>Output</strong>:</p>
<ul>
<li>UTF-8 should be set in the HTTP header, such as <code>Content-Type: text/html; charset=utf-8</code>. You can achieve that either by setting <a href="http://www.php.net/manual/en/ini.core.php#ini.default-charset" rel="noreferrer"><code>default_charset</code></a> in php.ini (preferred), or manually using <code>header()</code> function.</li>
<li>If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or <a href="https://stackoverflow.com/q/4696499">HTML metadata</a>).</li>
<li>When encoding the output using <code>json_encode()</code>, add <code>JSON_UNESCAPED_UNICODE</code> as a second parameter.</li>
</ul>
<p><strong>Input</strong>:</p>
<ul>
<li>Browsers will submit data in the character set specified for the document, hence nothing particular has to be done on the input.</li>
<li>In case you have doubts about request encoding (in case it could be tampered with), you may verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's <a href="http://php.net/manual/en/function.mb-check-encoding.php" rel="noreferrer"><code>mb_check_encoding()</code></a> does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.</li>
</ul>
<p><strong>Other Code Considerations</strong>:</p>
<ul>
<li><p>Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.</p>
</li>
<li><p>You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's <a href="http://www.php.net/manual/en/book.mbstring.php" rel="noreferrer"><code>mbstring</code></a> extension.</p>
</li>
<li><p><strong>PHP's built-in string operations are <em>not</em> by default UTF-8 safe.</strong> There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent <code>mbstring</code> function.</p>
</li>
<li><p>To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from <a href="http://www.utf8.com/" rel="noreferrer">utf8.com</a> for some good resources to learn everything you need to know.</p>
</li>
</ul> | {
"question_id": 279170,
"question_date": "2008-11-10T21:04:56.767Z",
"question_score": 1321,
"tags": "php|mysql|linux|apache|utf-8",
"answer_id": 279279,
"answer_date": "2008-11-10T21:43:05.257Z",
"answer_score": 1109
} |
Please answer the following Stack Overflow question:
Title: jQuery Get Selected Option From Dropdown
<p>Usually I use <code>$("#id").val()</code> to return the value of the selected option, but this time it doesn't work.
The selected tag has the id <code>aioConceptName</code></p>
<p><strong>html code</strong></p>
<pre><code><label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
</code></pre> | <p>For dropdown options you probably want something like this:</p>
<p><strong>For selected text</strong></p>
<pre><code>var conceptName = $('#aioConceptName').find(":selected").text();
</code></pre>
<p><strong>For selected value</strong></p>
<pre><code>var conceptName = $('#aioConceptName').find(":selected").val();
</code></pre>
<p>The reason <code>val()</code> doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the <code>:selected</code> property to the selected option which is a <em>child</em> of the dropdown.</p> | {
"question_id": 10659097,
"question_date": "2012-05-18T20:11:54.593Z",
"question_score": 1318,
"tags": "javascript|html|jquery|drop-down-menu",
"answer_id": 10659117,
"answer_date": "2012-05-18T20:14:40.857Z",
"answer_score": 2145
} |
Please answer the following Stack Overflow question:
Title: How to move a file in Python?
<p>How would I do the equivalent of <code>mv src/* dest/</code> in Python?</p>
<pre><code>>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destination_folder
</code></pre> | <p><a href="http://docs.python.org/library/os.html#os.rename" rel="noreferrer"><code>os.rename()</code></a>, <a href="https://docs.python.org/library/os.html#os.replace" rel="noreferrer"><code>os.replace()</code></a>, or <a href="http://docs.python.org/library/shutil.html#shutil.move" rel="noreferrer"><code>shutil.move()</code></a></p>
<p>All employ the same syntax:</p>
<pre><code>import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
</code></pre>
<p>Note that you must include the file name (<code>file.foo</code>) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.</p>
<p>Note also that in the first two cases the directory in which the new file is being created must already exist. On Windows, a file with that name must not exist or an exception will be raised, but <code>os.replace()</code> will silently replace a file even in that occurrence.</p>
<p>As has been noted in comments on other answers, <code>shutil.move</code> simply calls <code>os.rename</code> in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.</p> | {
"question_id": 8858008,
"question_date": "2012-01-13T22:17:58.720Z",
"question_score": 1317,
"tags": "python|file|file-handling|python-os",
"answer_id": 8858026,
"answer_date": "2012-01-13T22:19:58.390Z",
"answer_score": 1970
} |
Please answer the following Stack Overflow question:
Title: How to cherry-pick multiple commits
<p>I have two branches. Commit <code>a</code> is the head of one, while the other has <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> on top of <code>a</code>. I want to move <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> to first branch without commit <code>b</code>. Using cherry pick it is easy: checkout first branch cherry-pick one by one <code>c</code> to <code>f</code> and rebase second branch onto first. But is there any way to cherry-pick all <code>c</code>-<code>f</code> in one command?</p>
<p>Here is a visual description of the scenario (thanks <a href="/users/356895/JJD">JJD</a>):</p>
<p><img src="https://i.stack.imgur.com/7k9Ev.png" alt="enter image description here"></p> | <p>Git 1.7.2 introduced the ability to cherry pick a range of commits. From the <a href="https://raw.github.com/git/git/master/Documentation/RelNotes/1.7.2.txt" rel="noreferrer">release notes</a>:</p>
<blockquote>
<p><code>git cherry-pick</code> learned to pick a range of commits
(e.g. <code>cherry-pick A..B</code> and <code>cherry-pick --stdin</code>), so did <code>git revert</code>; these do not support the nicer sequencing control <code>rebase [-i]</code> has, though.</p>
</blockquote>
<p>To cherry-pick all the commits from commit <code>A</code> to commit <code>B</code> (where <code>A</code> is older than <code>B</code>), run:</p>
<pre><code>git cherry-pick A^..B
</code></pre>
<p>If you want to <em>ignore</em> A itself, run:</p>
<pre><code>git cherry-pick A..B
</code></pre>
<p>Notes from comments:</p>
<ul>
<li><code>A</code> should be older than <code>B</code>, or <code>A</code> should be from another branch.</li>
<li>On Windows, it should be <code>A^^..B</code> as the caret needs to be escaped, or it should be <code>"A^..B"</code> (double quotes).</li>
<li>In <code>zsh</code> shell, it should be <code>'A^..B'</code> (single quotes) as the caret is a special character.</li>
<li>For an exposition, see <a href="https://stackoverflow.com/a/69472178/4561887">the answer by Gabriel Staples</a>.</li>
</ul>
<p><em>(Credits to damian, J. B. Rainsberger, sschaef, Neptilo, Pete and TMin in the comments.)</em></p> | {
"question_id": 1670970,
"question_date": "2009-11-04T00:07:03.587Z",
"question_score": 1317,
"tags": "git|git-rebase|cherry-pick",
"answer_id": 3933416,
"answer_date": "2010-10-14T13:08:39.700Z",
"answer_score": 2019
} |
Please answer the following Stack Overflow question:
Title: How do I sort an NSMutableArray with custom objects in it?
<p>What I want to do seems pretty simple, but I can't find any answers on the web. I have an <code>NSMutableArray</code> of objects, and let's say they are 'Person' objects. I want to sort the <code>NSMutableArray</code> by Person.birthDate which is an <code>NSDate</code>.</p>
<p>I think it has something to do with this method:</p>
<pre><code>NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
</code></pre>
<p>In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?</p> | <h2>Compare method</h2>
<p>Either you implement a compare-method for your object:</p>
<pre><code>- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
</code></pre>
<h2>NSSortDescriptor (better)</h2>
<p>or usually even better:</p>
<pre><code>NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
</code></pre>
<p>You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html" rel="noreferrer">the documentation</a>.</p>
<h2>Blocks (shiny!)</h2>
<p>There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:</p>
<pre><code>NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
return [a.birthDate compare:b.birthDate];
}];
</code></pre>
<h1>Performance</h1>
<p>The <code>-compare:</code> and block-based methods will be quite a bit faster, in general, than using <code>NSSortDescriptor</code> as the latter relies on KVC. The primary advantage of the <code>NSSortDescriptor</code> method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an <code>NSTableView</code> by clicking on the header row.</p> | {
"question_id": 805547,
"question_date": "2009-04-30T06:10:56.923Z",
"question_score": 1314,
"tags": "ios|objective-c|sorting|cocoa-touch|nsmutablearray",
"answer_id": 805589,
"answer_date": "2009-04-30T06:25:03.067Z",
"answer_score": 2340
} |
Please answer the following Stack Overflow question:
Title: How do I get the full path of the current file's directory?
<p>How do I get the current file's directory path?
I tried:</p>
<pre><code>>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
</code></pre>
<p>But I want:</p>
<pre><code>'C:\\python27\\'
</code></pre> | <p>The special variable <a href="https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do"><code>__file__</code></a> contains the path to the current file. From that we can get the directory using either <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer"><code>pathlib</code></a> or the <a href="https://docs.python.org/3.8/library/os.path.html" rel="noreferrer"><code>os.path</code></a> module.</p>
<h2>Python 3</h2>
<p>For the directory of the script being run:</p>
<pre><code>import pathlib
pathlib.Path(__file__).parent.resolve()
</code></pre>
<p>For the current working directory:</p>
<pre><code>import pathlib
pathlib.Path().resolve()
</code></pre>
<h2>Python 2 and 3</h2>
<p>For the directory of the script being run:</p>
<pre><code>import os
os.path.dirname(os.path.abspath(__file__))
</code></pre>
<p>If you mean the current working directory:</p>
<pre><code>import os
os.path.abspath(os.getcwd())
</code></pre>
<p>Note that before and after <code>file</code> is two underscores, not just one.</p>
<p>Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), <code>__file__</code> may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.</p>
<h2>References</h2>
<ol>
<li><a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer">pathlib</a> in the python documentation.</li>
<li><a href="https://docs.python.org/2.7/library/os.path.html" rel="noreferrer">os.path - Python 2.7</a>, <a href="https://docs.python.org/3/library/os.path.html" rel="noreferrer">os.path - Python 3</a></li>
<li><a href="https://docs.python.org/2.7/library/os.html#os.getcwd" rel="noreferrer">os.getcwd - Python 2.7</a>, <a href="https://docs.python.org/3/library/os.html#os.getcwd" rel="noreferrer">os.getcwd - Python 3</a></li>
<li><a href="https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do">what does the __file__ variable mean/do?</a></li>
</ol> | {
"question_id": 3430372,
"question_date": "2010-08-07T12:17:52.110Z",
"question_score": 1312,
"tags": "python|directory",
"answer_id": 3430395,
"answer_date": "2010-08-07T12:24:25.913Z",
"answer_score": 2471
} |
Please answer the following Stack Overflow question:
Title: SQL Server - Best way to get identity of inserted row?
<p>What is the best way to get <code>IDENTITY</code> of inserted row?</p>
<p>I know about <code>@@IDENTITY</code> and <code>IDENT_CURRENT</code> and <code>SCOPE_IDENTITY</code> but don't understand the pros and cons attached to each.</p>
<p>Can someone please explain the differences and when I should be using each?</p> | <ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/ms187342.aspx" rel="noreferrer"><code>@@IDENTITY</code></a> returns the last identity value generated for any table in the current session, across all scopes. <strong>You need to be careful here</strong>, since it's across scopes. You could get a value from a trigger, instead of your current statement.</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/ms190315.aspx" rel="noreferrer"><code>SCOPE_IDENTITY()</code></a> returns the last identity value generated for any table in the current session and the current scope. <strong>Generally what you want to use</strong>.</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/ms175098.aspx" rel="noreferrer"><code>IDENT_CURRENT('tableName')</code></a> returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (<strong>very rare</strong>). Also, as @<a href="https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row#42665">Guy Starbuck</a> mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into."</p></li>
<li><p>The <a href="http://msdn.microsoft.com/en-us/library/ms177564.aspx" rel="noreferrer"><code>OUTPUT</code> clause</a> of the <code>INSERT</code> statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's <strong>more straightforward</strong> than the other functions above. However, it's a little <strong>more verbose</strong> (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the <strong>only guaranteed method</strong> for getting the identity (short of turning off parallelism). However, it is executed <em>before</em> triggers and cannot be used to return trigger-generated values.</p></li>
</ul> | {
"question_id": 42648,
"question_date": "2008-09-03T21:32:02.587Z",
"question_score": 1312,
"tags": "sql|sql-server|tsql",
"answer_id": 42655,
"answer_date": "2008-09-03T21:38:23.863Z",
"answer_score": 1646
} |
Please answer the following Stack Overflow question:
Title: How do I determine the size of my array in C?
<p>How do I determine the size of my array in C? </p>
<p>That is, the number of elements the array can hold?</p> | <p><strong>Executive summary:</strong></p>
<pre><code>int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
</code></pre>
<hr>
<p><strong>Full answer:</strong></p>
<p>To determine the size of your array in bytes, you can use the <code>sizeof</code>
operator:</p>
<pre><code>int a[17];
size_t n = sizeof(a);
</code></pre>
<p>On my computer, ints are 4 bytes long, so n is 68.</p>
<p>To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:</p>
<pre><code>int a[17];
size_t n = sizeof(a) / sizeof(int);
</code></pre>
<p>and get the proper answer (68 / 4 = 17), but if the type of
<code>a</code> changed you would have a nasty bug if you forgot to change
the <code>sizeof(int)</code> as well.</p>
<p>So the preferred divisor is <code>sizeof(a[0])</code> or the equivalent <code>sizeof(*a)</code>, the size of the first element of the array.</p>
<pre><code>int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
</code></pre>
<p>Another advantage is that you can now easily parameterize
the array name in a macro and get:</p>
<pre><code>#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
</code></pre> | {
"question_id": 37538,
"question_date": "2008-09-01T06:49:22.723Z",
"question_score": 1310,
"tags": "c|arrays|memory",
"answer_id": 37539,
"answer_date": "2008-09-01T06:49:44.203Z",
"answer_score": 1609
} |
Please answer the following Stack Overflow question:
Title: How do I terminate a script?
<p>How do I exit a script early, like the <code>die()</code> command in PHP?</p> | <pre><code>import sys
sys.exit()
</code></pre>
<p>details from the <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="noreferrer"><code>sys</code> module documentation</a>:</p>
<blockquote>
<p><code>sys.<strong>exit</strong>([<em>arg</em>])</code></p>
<p>Exit from Python. This is implemented by raising the
<a href="https://docs.python.org/2/library/exceptions.html#SystemExit" rel="noreferrer" title="SystemExit"><code>SystemExit</code></a> exception, so cleanup actions specified by finally clauses
of <a href="https://docs.python.org/2/reference/compound_stmts.html#try" rel="noreferrer" title="try"><code>try</code></a> statements are honored, and it is possible to intercept the
exit attempt at an outer level.</p>
<p>The optional argument <em>arg</em> can be an integer giving the exit status
(defaulting to zero), or another type of object. If it is an integer,
zero is considered “successful termination” and any nonzero value is
considered “abnormal termination” by shells and the like. Most systems
require it to be in the range 0-127, and produce undefined results
otherwise. Some systems have a convention for assigning specific
meanings to specific exit codes, but these are generally
underdeveloped; Unix programs generally use 2 for command line syntax
errors and 1 for all other kind of errors. If another type of object
is passed, None is equivalent to passing zero, and any other object is
printed to <a href="https://docs.python.org/2/library/sys.html#sys.stderr" rel="noreferrer" title="sys.stderr"><code>stderr</code></a> and results in an exit code of 1. In particular,
<code>sys.exit("some error message")</code> is a quick way to exit a program when
an error occurs.</p>
<p>Since <a href="https://docs.python.org/2/library/constants.html#exit" rel="noreferrer" title="exit"><code>exit()</code></a> ultimately “only” raises an exception, it will only exit
the process when called from the main thread, and the exception is not
intercepted.</p>
</blockquote>
<p>Note that this is the 'nice' way to exit. @<a href="https://stackoverflow.com/questions/73663/terminating-a-python-script#76374">glyphtwistedmatrix</a> below points out that if you want a 'hard exit', you can use <code>os._exit(*errorcode*)</code>, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it <em>does</em> kill the entire process, including all running threads, while <code>sys.exit()</code> (as it says in the docs) only exits if called from the main thread, with no other threads running.</p> | {
"question_id": 73663,
"question_date": "2008-09-16T15:35:55.637Z",
"question_score": 1310,
"tags": "python|termination",
"answer_id": 73673,
"answer_date": "2008-09-16T15:36:36.680Z",
"answer_score": 1694
} |
Please answer the following Stack Overflow question:
Title: How can I get the full object in Node.js's console.log(), rather than '[Object]'?
<p>I have this object:</p>
<pre><code>const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
</code></pre>
<p>But when I try to show it using <code>console.log(myObject)</code>, I receive this output:</p>
<pre><code>{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
</code></pre>
<p>How can I get the full object, including the content of property <code>f</code>?</p> | <p>You need to use <a href="http://nodejs.org/api/util.html#util_util_inspect_object_options" rel="noreferrer"><code>util.inspect()</code></a>:</p>
<pre><code>const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
</code></pre>
<p>Outputs</p>
<pre><code>{ a: 'a', b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }
</code></pre> | {
"question_id": 10729276,
"question_date": "2012-05-23T23:29:28.317Z",
"question_score": 1310,
"tags": "javascript|node.js|debugging|console.log",
"answer_id": 10729284,
"answer_date": "2012-05-23T23:30:34.900Z",
"answer_score": 2001
} |
Please answer the following Stack Overflow question:
Title: Which characters are valid in CSS class names/selectors?
<p>What characters/symbols are allowed within the <strong>CSS</strong> class selectors?<br>
I know that the following characters are <em>invalid</em>, but what characters are <em>valid</em>?</p>
<pre><code>~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
</code></pre> | <p>You can check directly at the <a href="http://www.w3.org/TR/CSS21/grammar.html#scanner" rel="noreferrer">CSS grammar</a>.</p>
<p><em>Basically</em><sup>1</sup>, a name must begin with an underscore (<code>_</code>), a hyphen (<code>-</code>), or a letter(<code>a</code>–<code>z</code>), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must<sup>2</sup> be a letter or underscore, and the name must be at least 2 characters long.</p>
<pre><code>-?[_a-zA-Z]+[_a-zA-Z0-9-]*
</code></pre>
<p>In short, the previous rule translates to the following, extracted from the <a href="https://www.w3.org/TR/CSS21/syndata.html#characters" rel="noreferrer">W3C spec.</a>:</p>
<blockquote>
<p>In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, or a hyphen followed by a digit.
Identifiers can also contain escaped characters and any ISO 10646
character as a numeric code (see next item). For instance, the
identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".</p>
</blockquote>
<p>Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in <code>-moz-opacity</code>.</p>
<p><sup>1</sup> It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).</p>
<p><sup>2</sup> Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. <code>--indent1</code>, is invalid. However, I'm pretty sure I've seen this in practice.</p> | {
"question_id": 448981,
"question_date": "2009-01-15T23:37:39.880Z",
"question_score": 1309,
"tags": "css|css-selectors",
"answer_id": 449000,
"answer_date": "2009-01-15T23:42:27.670Z",
"answer_score": 1102
} |
Please answer the following Stack Overflow question:
Title: Where and why do I have to put the "template" and "typename" keywords?
<p>In templates, where and why do I have to put <code>typename</code> and <code>template</code> on dependent names?<br>
What exactly are dependent names anyway? </p>
<p>I have the following code:</p>
<pre><code>template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> {
};
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion {
char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any U
};
template< > struct inUnion<T> {
};
};
</code></pre>
<p>The problem I have is in the <code>typedef Tail::inUnion<U> dummy</code> line. I'm fairly certain that <code>inUnion</code> is a dependent name, and VC++ is quite right in choking on it.<br>
I also know that I should be able to add <code>template</code> somewhere to tell the compiler that inUnion is a template-id. But where exactly? And should it then assume that inUnion is a class template, i.e. <code>inUnion<U></code> names a type and not a function?</p> | <p>(See <a href="https://stackoverflow.com/a/17579889/4561887">here also for my C++11 answer</a>)</p>
<p>In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:</p>
<pre><code>t * f;
</code></pre>
<p>How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what <code>t</code> means. If it's a type, then it will be a declaration of a pointer <code>f</code>. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):</p>
<blockquote>
<p>Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.</p>
</blockquote>
<p>How will the compiler find out what a name <code>t::x</code> refers to, if <code>t</code> refers to a template type parameter? <code>x</code> could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. <strong>If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a <em>dependent name</em> (it "depends" on the template parameters).</strong> </p>
<p>You might recommend to just wait till the user instantiates the template: </p>
<blockquote>
<p><em>Let's wait until the user instantiates the template, and then later find out the real meaning of <code>t::x * f;</code>.</em> </p>
</blockquote>
<p>This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place. </p>
<p>So there has to be a way to tell the compiler that certain names are types and that certain names aren't. </p>
<h2>The "typename" keyword</h2>
<p>The answer is: <em>We</em> decide how the compiler should parse this. If <code>t::x</code> is a dependent name, then we need to prefix it by <code>typename</code> to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):</p>
<blockquote>
<p>A name used in a template declaration or definition and that is dependent on a template-parameter is
assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified
by the keyword typename. </p>
</blockquote>
<p>There are many names for which <code>typename</code> is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with <code>T *f;</code>, when <code>T</code> is a type template parameter. But for <code>t::x * f;</code> to be a declaration, it must be written as <code>typename t::x *f;</code>. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:</p>
<pre><code>// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;
</code></pre>
<p><em>The syntax allows <code>typename</code> only before qualified names</em> - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.</p>
<p>A similar gotcha exists for names that denote templates, as hinted at by the introductory text.</p>
<h2>The "template" keyword</h2>
<p>Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example: </p>
<pre><code>boost::function< int() > f;
</code></pre>
<p>It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of <code>boost::function</code> and <code>f</code>:</p>
<pre><code>namespace boost { int function = 0; }
int main() {
int f = 0;
boost::function< int() > f;
}
</code></pre>
<p>That's actually a valid <em>expression</em>! It uses the less-than operator to compare <code>boost::function</code> against zero (<code>int()</code>), and then uses the greater-than operator to compare the resulting <code>bool</code> against <code>f</code>. However as you might well know, <code>boost::function</code> <a href="http://www.boost.org/doc/libs/1_54_0/doc/html/function.html" rel="noreferrer">in real life</a> is a template, so the compiler knows (14.2/3):</p>
<blockquote>
<p>After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is
always taken as the beginning of a template-argument-list and never as a name followed by the less-than
operator.</p>
</blockquote>
<p>Now we are back to the same problem as with <code>typename</code>. What if we can't know yet whether the name is a template when parsing the code? We will need to insert <code>template</code> immediately before the template name, as specified by <code>14.2/4</code>. This looks like:</p>
<pre><code>t::template f<int>(); // call a function template
</code></pre>
<p>Template names can not only occur after a <code>::</code> but also after a <code>-></code> or <code>.</code> in a class member access. You need to insert the keyword there too:</p>
<pre><code>this->template f<int>(); // call a function template
</code></pre>
<hr>
<h2>Dependencies</h2>
<p>For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.</p>
<p>In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to <em>depend</em> on template parameters.</p>
<p>The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:</p>
<ul>
<li>Dependent types (e.g: a type template parameter <code>T</code>)</li>
<li>Value-dependent expressions (e.g: a non-type template parameter <code>N</code>)</li>
<li>Type-dependent expressions (e.g: a cast to a type template parameter <code>(T)0</code>)</li>
</ul>
<p>Most of the rules are intuitive and are built up recursively: For example, a type constructed as <code>T[N]</code> is a dependent type if <code>N</code> is a value-dependent expression or <code>T</code> is a dependent type. The details of this can be read in section <code>(14.6.2/1</code>) for dependent types, <code>(14.6.2.2)</code> for type-dependent expressions and <code>(14.6.2.3)</code> for value-dependent expressions. </p>
<h3>Dependent names</h3>
<p>The Standard is a bit unclear about what <em>exactly</em> is a <em>dependent name</em>. On a simple read (you know, the principle of least surprise), all it defines as a <em>dependent name</em> is the special case for function names below. But since clearly <code>T::x</code> also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition). </p>
<p>To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:</p>
<blockquote>
<p>A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)</p>
</blockquote>
<p>An identifier is just a plain sequence of characters / digits, while the next two are the <code>operator +</code> and <code>operator type</code> form. The last form is <code>template-name <argument list></code>. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.</p>
<p>A value dependent expression <code>1 + N</code> is not a name, but <code>N</code> is. The subset of all dependent constructs that are names is called <em>dependent name</em>. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule. </p>
<h3>Dependent function names</h3>
<p>Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example <code>f((T)0)</code>, <code>f</code> is a dependent name. In the Standard, this is specified at <code>(14.6.2/1)</code>.</p>
<h2>Additional notes and examples</h2>
<p>In enough cases we need both of <code>typename</code> and <code>template</code>. Your code should look like the following</p>
<pre><code>template <typename T, typename Tail>
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
typedef typename Tail::template inUnion<U> dummy;
};
// ...
};
</code></pre>
<p>The keyword <code>template</code> doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example</p>
<pre><code>typename t::template iterator<int>::value_type v;
</code></pre>
<p>In some cases, the keywords are forbidden, as detailed below</p>
<ul>
<li><p>On the name of a dependent base class you are not allowed to write <code>typename</code>. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:</p>
<pre><code> template <typename T>
struct derive_from_Has_type : /* typename */ SomeBase<T>::type
{ };
</code></pre></li>
<li><p>In using-declarations it's not possible to use <code>template</code> after the last <code>::</code>, and the C++ committee <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#109" rel="noreferrer">said</a> not to work on a solution. </p>
<pre><code> template <typename T>
struct derive_from_Has_type : SomeBase<T> {
using SomeBase<T>::template type; // error
using typename SomeBase<T>::type; // typename *is* allowed
};
</code></pre></li>
</ul> | {
"question_id": 610245,
"question_date": "2009-03-04T11:56:16.583Z",
"question_score": 1309,
"tags": "c++|templates|typename|c++-faq|dependent-name",
"answer_id": 613132,
"answer_date": "2009-03-05T00:27:57.213Z",
"answer_score": 1352
} |
Please answer the following Stack Overflow question:
Title: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
<p>I have a JavaScript widget which provides standard extension points. One of them is the <code>beforecreate</code> function. It should return <code>false</code> to prevent an item from being created. </p>
<p>I've added an Ajax call into this function using jQuery:</p>
<pre><code>beforecreate: function (node, targetNode, type, to) {
jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
function (result) {
if (result.isOk == false)
alert(result.message);
});
}
</code></pre>
<p>But I want to prevent my widget from creating the item, so I should return <code>false</code> in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?</p> | <p>From the <a href="https://api.jquery.com/jquery.ajax/" rel="noreferrer">jQuery documentation</a>: you specify the <strong>asynchronous</strong> option to be <strong>false</strong> to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.</p>
<p>Here's what your code would look like if changed as suggested:</p>
<pre><code>beforecreate: function (node, targetNode, type, to) {
jQuery.ajax({
url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
success: function (result) {
if (result.isOk == false) alert(result.message);
},
async: false
});
}
</code></pre> | {
"question_id": 133310,
"question_date": "2008-09-25T13:26:54.193Z",
"question_score": 1306,
"tags": "javascript|jquery|ajax|asynchronous",
"answer_id": 133327,
"answer_date": "2008-09-25T13:30:37.290Z",
"answer_score": 1240
} |
Please answer the following Stack Overflow question:
Title: How can I do a line break (line continuation) in Python?
<p>Given:</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>How do I write the above in two lines?</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre> | <p>What is the line? You can just have arguments on the next line without any problems:</p>
<pre><code>a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
</code></pre>
<p>Otherwise you can do something like this:</p>
<pre><code>if (a == True and
b == False):
</code></pre>
<p>or with explicit line break:</p>
<pre><code>if a == True and \
b == False:
</code></pre>
<p>Check the <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">style guide</a> for more information.</p>
<p>Using parentheses, your example can be written over multiple lines:</p>
<pre><code>a = ('1' + '2' + '3' +
'4' + '5')
</code></pre>
<p>The same effect can be obtained using explicit line break:</p>
<pre><code>a = '1' + '2' + '3' + \
'4' + '5'
</code></pre>
<p>Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.</p> | {
"question_id": 53162,
"question_date": "2008-09-09T23:45:30.293Z",
"question_score": 1303,
"tags": "python|syntax|line-breaks|long-lines",
"answer_id": 53180,
"answer_date": "2008-09-09T23:52:05.643Z",
"answer_score": 1461
} |
Please answer the following Stack Overflow question:
Title: How do I access the $scope variable in browser's console using AngularJS?
<p>I would like to access my <code>$scope</code> variable in Chrome's JavaScript console. How do I do that?</p>
<p>I can neither see <code>$scope</code> nor the name of my module <code>myapp</code> in the console as variables.</p> | <p>Pick an element in the HTML panel of the developer tools and type this in the console:</p>
<pre><code>angular.element($0).scope()
</code></pre>
<p>In <a href="http://en.wikipedia.org/wiki/WebKit" rel="noreferrer">WebKit</a> and Firefox, <code>$0</code> is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console.</p>
<p>You can also target the scope by element ID, like so:</p>
<pre><code>angular.element(document.getElementById('yourElementId')).scope()
</code></pre>
<p><strong>Addons/Extensions</strong></p>
<p>There are some very useful Chrome extensions that you might want to check out:</p>
<ul>
<li><p><a href="https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk" rel="noreferrer">Batarang</a>. This has been around for a while.</p></li>
<li><p><a href="http://ng-inspector.org/" rel="noreferrer">ng-inspector</a>. This is the newest one, and as the name suggests, it allows you to inspect your application's scopes.</p></li>
</ul>
<p><strong>Playing with jsFiddle</strong></p>
<p>When working with jsfiddle you can open the fiddle in <em>show</em> mode by adding <code>/show</code> at the end of the URL. When running like this you have access to the <code>angular</code> global. You can try it here:</p>
<p><a href="http://jsfiddle.net/jaimem/Yatbt/show" rel="noreferrer">http://jsfiddle.net/jaimem/Yatbt/show</a></p>
<p><strong>jQuery Lite</strong></p>
<p>If you load jQuery before AngularJS, <code>angular.element</code> can be passed a jQuery selector. So you could inspect the scope of a controller with</p>
<pre><code>angular.element('[ng-controller=ctrl]').scope()
</code></pre>
<p>Of a button</p>
<pre><code> angular.element('button:eq(1)').scope()
</code></pre>
<p>... and so on.</p>
<p>You might actually want to use a global function to make it easier:</p>
<pre><code>window.SC = function(selector){
return angular.element(selector).scope();
};
</code></pre>
<p>Now you could do this</p>
<pre><code>SC('button:eq(10)')
SC('button:eq(10)').row // -> value of scope.row
</code></pre>
<p>Check here: <a href="http://jsfiddle.net/jaimem/DvRaR/1/show/" rel="noreferrer">http://jsfiddle.net/jaimem/DvRaR/1/show/</a></p> | {
"question_id": 13743058,
"question_date": "2012-12-06T11:52:41.037Z",
"question_score": 1303,
"tags": "angularjs|angularjs-scope|google-chrome-devtools",
"answer_id": 13744085,
"answer_date": "2012-12-06T12:56:21.127Z",
"answer_score": 1843
} |
Please answer the following Stack Overflow question:
Title: 'Must Override a Superclass Method' Errors after importing a project into Eclipse
<p>Anytime I have to re-import my projects into Eclipse (if I reinstalled Eclipse, or changed the location of the projects), <strong>almost all</strong> of my overridden methods are not formatted correctly, causing the error:</p>
<blockquote>
<p>The method must override a superclass method</p>
</blockquote>
<p>It may be noteworthy to mention this is with Android projects for whatever reason, the method argument values are not always populated, so I have to manually populate them myself. For instance:</p>
<pre><code>list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//These arguments have their correct names
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
}
});
</code></pre>
<p>will be initially populated like this:</p>
<pre><code>list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//This methods arguments were not automatically provided
public void onCreateContextMenu(ContextMenu arg1, View arg2,
ContextMenuInfo arg3) {
}
});
</code></pre>
<p>The odd thing is, if I remove my code, and have Eclipse automatically recreate the method, it uses the same argument names I already had, so I don't really know where the problem is, other then it auto-formatting the method for me.</p>
<p>This becomes quite a pain having to manually recreate ALL my overridden methods by hand. If anyone can explain why this happens or how to fix it. I would be very happy.</p>
<p>Maybe it is due to the way I am formatting the methods, which are inside an argument of another method?</p> | <p>Eclipse is defaulting to Java 1.5 and you have classes implementing interface methods (which in Java 1.6 can be annotated with <code>@Override</code>, but in Java 1.5 can only be applied to methods overriding a superclass method).</p>
<p>Go to your project/IDE preferences and set the Java compiler level to 1.6 and also make sure you select JRE 1.6 to execute your program from Eclipse.</p> | {
"question_id": 1678122,
"question_date": "2009-11-05T03:17:53.727Z",
"question_score": 1301,
"tags": "java|android|eclipse|overriding|superclass",
"answer_id": 1678170,
"answer_date": "2009-11-05T03:33:53.893Z",
"answer_score": 1453
} |
Please answer the following Stack Overflow question:
Title: How to escape single quotes within single quoted strings
<p>Let's say, you have a Bash <code>alias</code> like:</p>
<pre><code>alias rxvt='urxvt'
</code></pre>
<p>which works fine.</p>
<p>However:</p>
<pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111''
</code></pre>
<p>won't work, and neither will:</p>
<pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
</code></pre>
<p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p>
<pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
</code></pre>
<p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p> | <p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p>
<pre><code> alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234
</code></pre>
<p>Explanation of how <code>'"'"'</code> is interpreted as just <code>'</code>:</p>
<ol>
<li><code>'</code> End first quotation which uses single quotes.</li>
<li><code>"</code> Start second quotation, using double-quotes.</li>
<li><code>'</code> Quoted character.</li>
<li><code>"</code> End second quotation, using double-quotes.</li>
<li><code>'</code> Start third quotation, using single quotes.</li>
</ol>
<p>If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.</p> | {
"question_id": 1250079,
"question_date": "2009-08-08T22:50:10.983Z",
"question_score": 1299,
"tags": "bash|syntax|quoting",
"answer_id": 1250279,
"answer_date": "2009-08-09T00:52:37.837Z",
"answer_score": 1786
} |
Please answer the following Stack Overflow question:
Title: How can you speed up Eclipse?
<p><strong>How can you make the experience with Eclipse faster?</strong> </p>
<p>For instance: <em>I disable all the plugins I don't need (Mylyn, Subclipse, …).</em></p>
<p>Instead of using a plugin for <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>, I configure <a href="https://en.wikipedia.org/wiki/TortoiseHg" rel="noreferrer">TortoiseHG</a> as an external tool.</p> | <p>The three most influential factors for Eclipse speed are:</p>
<ul>
<li>Using the <strong>latest version of Eclipse</strong> (2020-06 as on 26 June 2020)<br />
Note that <a href="https://stackoverflow.com/users/822870/david-bala%C5%BEic">David Balažic</a>'s <a href="https://stackoverflow.com/questions/316265/how-can-you-speed-up-eclipse/316535#comment38657862_316535">comment</a> (July 2014) contradicts that criteria which was working six years ago:</li>
</ul>
<blockquote>
<p>The "same" workspace in Indigo (3.7.2) SR2 loads in 4 seconds, in Kepler SR2 (4.3.2) in 7 seconds and in Luna (4.4.0) in 10 seconds. All are Java EE bundles. Newer versions have more bundled plugins, but still the trend is obvious. (by "same" workspace I mean: same (additionally installed) plugins used, same projects checked out from version control).</p>
</blockquote>
<ul>
<li><p>Launching it with the <strong>latest JDK</strong> (Java 14 at the time of writing, which does not prevent you to compile in your Eclipse project with any other JDK you want: 1.4.2, 1.5, 1.6 older...)</p>
<pre><code> -vm jdk1.6.0_10\jre\bin\client\jvm.dll
</code></pre>
</li>
<li><p>Configuring the <strong>eclipse.ini</strong> (see <a href="https://stackoverflow.com/questions/142357/what-are-the-best-eclipse-34-jvm-settings#144349">this question for a complete eclipse.ini</a>)</p>
<pre><code> -Xms512m
-Xmx4096m
[...]
</code></pre>
</li>
</ul>
<p>The <code>Xmx</code> argument is the amount of memory Eclipse will get (in simple terms). With <code>-Xmx4g</code>, it gets 4 GB of RAM, etc.</p>
<hr />
<p>Note:</p>
<ol>
<li>Referring to the jvm.dll has advantages:</li>
</ol>
<ul>
<li>Splash screen coming up sooner.</li>
<li>Eclipse.exe in the process list instead of java.exe.</li>
<li>Firewalls: Eclipse wants access to the Internet instead of Java.</li>
<li>Window management branding issues, especially on Windows and Mac.</li>
</ul>
<hr />
<p>Dec. 2020, <a href="https://stackoverflow.com/users/679858/udo">Udo</a> conforms <a href="https://stackoverflow.com/questions/316265/how-can-you-speed-up-eclipse/316535#comment115827363_316535">in the comments</a></p>
<blockquote>
<p>From version 4.8 (Photon) an up there was a steady speed gain after each version.<br />
The main platform was optimized every release to load faster, enable more features for the dark theme and to add more features for newer Java versions for the Java development tools.<br />
Especially with-in the last 3 versions the startup time was increased a lot. There should be a significant increase in start-up time with the newest version of Eclipse 2020-12.</p>
<p>In my experience it started a lot faster with each new version.<br />
But: There are still plug-ins which do not follow the new way of using the Eclipse API and are therefore still slow to start.<br />
Since the change to Java 11 as the minimum runtime version starting from Eclipse version 2020-09 at least the core system uses the newer features of the JVM. It is up to the providers of the other plug-ins to upgrade to newer APIs and to use the full power of modern CPUs (e.g. concurrent programming model).</p>
</blockquote> | {
"question_id": 316265,
"question_date": "2008-11-25T03:18:56.627Z",
"question_score": 1298,
"tags": "eclipse|performance",
"answer_id": 316535,
"answer_date": "2008-11-25T06:56:25.470Z",
"answer_score": 456
} |
Please answer the following Stack Overflow question:
Title: How do I create a constant in Python?
<p>How do I declare a constant in Python?</p>
<p>In Java, we do:</p>
<pre class="lang-java prettyprint-override"><code>public static final String CONST_NAME = "Name";
</code></pre> | <p>You cannot declare a variable or value as constant in Python.</p>
<hr />
<p>To <em>indicate</em> to programmers that a variable is a constant, one usually writes it in upper case:</p>
<pre><code>CONST_NAME = "Name"
</code></pre>
<hr />
<p>To raise exceptions when constants are changed, see <a href="https://web.archive.org/web/20100523132518id_/http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991" rel="noreferrer">Constants in Python</a> by Alex Martelli. Note that this is not commonly used in practice.</p>
<hr />
<p>As of Python 3.8, there's a <a href="https://docs.python.org/3/library/typing.html#typing.Final" rel="noreferrer"><code>typing.Final</code></a> variable annotation that will tell static type checkers (like mypy) that your variable shouldn't be reassigned. This is the closest equivalent to Java's <code>final</code>. However, it <strong>does not actually prevent reassignment</strong>:</p>
<pre><code>from typing import Final
a: Final[int] = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2
</code></pre> | {
"question_id": 2682745,
"question_date": "2010-04-21T12:20:18.940Z",
"question_score": 1296,
"tags": "python|constants",
"answer_id": 2682752,
"answer_date": "2010-04-21T12:21:54.647Z",
"answer_score": 1256
} |
Please answer the following Stack Overflow question:
Title: Get the name of an object's type
<p>Is there a <strong>JavaScript</strong> equivalent of <strong>Java</strong>'s <code>class.getName()</code>?</p> | <blockquote>
<p>Is there a JavaScript equivalent of Java's <code>class.getName()</code>?</p>
</blockquote>
<p><em><strong>No</strong></em>.</p>
<p><strong>ES2015 Update</strong>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes" rel="noreferrer">the name of <code>class Foo {}</code> is <code>Foo.name</code></a>. The name of <code>thing</code>'s class, regardless of <code>thing</code>'s type, is <code>thing.constructor.name</code>. Builtin constructors in an ES2015 environment have the correct <code>name</code> property; for instance <code>(2).constructor.name</code> is <code>"Number"</code>.</p>
<hr />
<p>But here are various hacks that all fall down in one way or another:</p>
<p>Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)</p>
<pre><code>Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
</code></pre>
<p>Now, all of your objects will have the function, <code>getName()</code>, that will return the name of the constructor as a string. I have tested this in <code>FF3</code> and <code>IE7</code>, I can't speak for other implementations.</p>
<p>If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...</p>
<hr />
<p>I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...</p>
<h2>Using the <code>constructor</code> property...</h2>
<p>Every <code>object</code> has a value for its <code>constructor</code> property, but depending on how that <code>object</code> was constructed as well as what you want to do with that value, it may or may not be useful.</p>
<p>Generally speaking, you can use the <code>constructor</code> property to test the type of the object like so:</p>
<pre><code>var myArray = [1,2,3];
(myArray.constructor == Array); // true
</code></pre>
<p>So, that works well enough for most needs. That said...</p>
<h3>Caveats</h3>
<p><strong>Will not work <em>AT ALL</em> in many cases</strong></p>
<p>This pattern, though broken, is quite common:</p>
<pre><code>function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
</code></pre>
<p><code>Objects</code> constructed via <code>new Thingy</code> will have a <code>constructor</code> property that points to <code>Object</code>, not <code>Thingy</code>. So we fall right at the outset; you simply cannot trust <code>constructor</code> in a codebase that you don't control.</p>
<p><strong>Multiple Inheritance</strong></p>
<p>An example where it isn't as obvious is using multiple inheritance:</p>
<pre><code>function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
</code></pre>
<p>Things now don't work as you might expect them to:</p>
<pre><code>var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
</code></pre>
<p>So, you might get unexpected results if the <code>object</code> your testing has a different <code>object</code> set as its <code>prototype</code>. There are ways around this outside the scope of this discussion.</p>
<p>There are other uses for the <code>constructor</code> property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.</p>
<p><strong>Will not work cross-frame and cross-window</strong></p>
<p>Using <code>.constructor</code> for type checking will break when you want to check the type of objects coming from different <code>window</code> objects, say that of an iframe or a popup window. This is because there's a different version of each core type <code>constructor</code> in each `window', i.e.</p>
<pre><code>iframe.contentWindow.Array === Array // false
</code></pre>
<hr />
<h2>Using the <code>instanceof</code> operator...</h2>
<p>The <code>instanceof</code> operator is a clean way of testing <code>object</code> type as well, but has its own potential issues, just like the <code>constructor</code> property.</p>
<pre><code>var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
</code></pre>
<p>But <code>instanceof</code> fails to work for literal values (because literals are not <code>Objects</code>)</p>
<pre><code>3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
</code></pre>
<p>The literals need to be wrapped in an <code>Object</code> in order for <code>instanceof</code> to work, for example</p>
<pre><code>new Number(3) instanceof Number // true
</code></pre>
<p>The <code>.constructor</code> check works fine for literals because the <code>.</code> method invocation implicitly wraps the literals in their respective object type</p>
<pre><code>3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
</code></pre>
<p>Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)</p>
<h3>Will not work cross-frame and cross-window</h3>
<p><code>instanceof</code> also will not work across different windows, for the same reason as the <code>constructor</code> property check.</p>
<hr />
<h2>Using the <code>name</code> property of the <code>constructor</code> property...</h2>
<h3>Does not work <em>AT ALL</em> in many cases</h3>
<p>Again, see above; it's quite common for <code>constructor</code> to be utterly and completely wrong and useless.</p>
<h3>Does NOT work in <IE9</h3>
<p>Using <code>myObjectInstance.constructor.name</code> will give you a string containing the name of the <code>constructor</code> function used, but is subject to the caveats about the <code>constructor</code> property that were mentioned earlier.</p>
<p>For IE9 and above, you can <a href="http://matt.scharley.me/2012/03/monkey-patch-name-ie.html" rel="noreferrer">monkey-patch in support</a>:</p>
<pre><code>if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}
</code></pre>
<p><strong>Updated version</strong> from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by <a href="http://matt.scharley.me/2012/03/monkey-patch-name-ie.html#comment-551654096" rel="noreferrer">comments pointing out potential pitfalls</a> in the previous code.</p>
<pre><code>if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}
</code></pre>
<hr />
<h2>Using Object.prototype.toString</h2>
<p>It turns out, as <a href="http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/" rel="noreferrer">this post details</a>, you can use <code>Object.prototype.toString</code> - the low level and generic implementation of <code>toString</code> - to get the type for all built-in types</p>
<pre><code>Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
</code></pre>
<p>One could write a short helper function such as</p>
<pre><code>function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
</code></pre>
<p>to remove the cruft and get at just the type name</p>
<pre><code>type('abc') // String
</code></pre>
<p>However, it will return <code>Object</code> for all user-defined types.</p>
<hr />
<h2>Caveats for all...</h2>
<p>All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:</p>
<pre><code>// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
</code></pre>
<p>While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.</p>
<h3>NOTE:</h3>
<p>Discussion of the <code>typeof</code> operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an <code>object</code> is a given type, since it is very simplistic. Understanding where <code>typeof</code> is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)</p> | {
"question_id": 332422,
"question_date": "2008-12-01T22:06:15.680Z",
"question_score": 1296,
"tags": "javascript",
"answer_id": 332429,
"answer_date": "2008-12-01T22:09:09.807Z",
"answer_score": 1649
} |
Please answer the following Stack Overflow question:
Title: How can I merge two commits into one if I already started rebase?
<p>I am trying to merge 2 commits into 1, so I followed <a href="http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html" rel="noreferrer">“squashing commits with rebase” from git ready</a>.</p>
<p>I ran</p>
<pre><code>git rebase --interactive HEAD~2
</code></pre>
<p>In the resulting editor, I change <code>pick</code> to <code>squash</code> and then save-quit, but the rebase fails with the error</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote>
<p>Now that my work tree has reached this state, I’m having trouble recovering. </p>
<p>The command <code>git rebase --interactive HEAD~2</code> fails with:</p>
<blockquote>
<p>Interactive rebase already started</p>
</blockquote>
<p>and <code>git rebase --continue</code> fails with</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote> | <h3>Summary</h3>
<p>The error message</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote>
<p>means you likely attempted to “squash downward.” <strong>Git always squashes a newer commit into an older commit</strong> or “upward” as viewed on the interactive rebase todo list, that is into a commit on a previous line. Changing the command on your todo list’s very first line to <code>squash</code> will always produce this error as there is nothing for the first commit to squash into.</p>
<h3>The Fix</h3>
<p>First get back to where you started with</p>
<pre><code>$ git rebase --abort
</code></pre>
<p>Say your history is</p>
<pre><code>$ git log --pretty=oneline
a931ac7c808e2471b22b5bd20f0cad046b1c5d0d c
b76d157d507e819d7511132bdb5a80dd421d854f b
df239176e1a2ffac927d8b496ea00d5488481db5 a
</code></pre>
<p>That is, a was the first commit, then b, and finally c. After committing c we decide to squash b and c together:</p>
<p><em>(Note: Running <code>git log</code> pipes its output into a pager, <a href="https://www.gnu.org/software/less/" rel="noreferrer"><code>less</code></a> by default on most platforms. To quit the pager and return to your command prompt, press the <code>q</code> key.)</em></p>
<p>Running <code>git rebase --interactive HEAD~2</code> gives you an editor with</p>
<pre><code>pick b76d157 b
pick a931ac7 c
# Rebase df23917..a931ac7 onto df23917
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
</code></pre>
<p>(Notice that this todo list is in the reverse order as compared with the output of <code>git log</code>.)</p>
<p>Changing b’s <code>pick</code> to <code>squash</code> will result in the error you saw, but if instead you squash c into b (newer commit into the older or “squashing upward”) by changing the todo list to</p>
<pre><code>pick b76d157 b
squash a931ac7 c
</code></pre>
<p>and save-quitting your editor, you'll get another editor whose contents are</p>
<pre><code># This is a combination of 2 commits.
# The first commit's message is:
b
# This is the 2nd commit message:
c
</code></pre>
<p>When you save and quit, the contents of the edited file become commit message of the new combined commit:</p>
<pre><code>$ git log --pretty=oneline
18fd73d3ce748f2a58d1b566c03dd9dafe0b6b4f b and c
df239176e1a2ffac927d8b496ea00d5488481db5 a
</code></pre>
<h3>Note About Rewriting History</h3>
<p>Interactive rebase rewrites history. Attempting to push to a remote that contains the old history will fail because it is not a fast-forward.</p>
<p>If the branch you rebased is a topic or feature branch <em>in which you are working by yourself</em>, no big deal. Pushing to another repository will require the <code>--force</code> option, or alternatively you may be able, depending on the remote repository’s permissions, to first delete the old branch and then push the rebased version. Examples of those commands that will potentially destroy work is outside the scope of this answer.</p>
<p>Rewriting already-published history on a branch in which you are working with other people without <em>very</em> good reason such as leaking a password or other sensitive details forces work onto your collaborators and is antisocial and will annoy other developers. The <a href="https://git-scm.com/docs/git-rebase#_recovering_from_upstream_rebase" rel="noreferrer">“Recovering From an Upstream Rebase” section in the <code>git rebase</code> documentation</a> explains, with added emphasis.</p>
<blockquote>
<p>Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history. This section explains how to do the fix from the downstream’s point of view. <strong>The real fix, however, would be to avoid rebasing the upstream in the first place.</strong> …</p>
</blockquote> | {
"question_id": 2563632,
"question_date": "2010-04-01T20:56:53.747Z",
"question_score": 1295,
"tags": "git|git-merge",
"answer_id": 2568581,
"answer_date": "2010-04-02T19:04:45.223Z",
"answer_score": 1900
} |
Please answer the following Stack Overflow question:
Title: git: undo all working dir changes including new files
<p>How to delete all changes from working directory including new untracked files. I know that <code>git checkout -f</code> does that, but it doesn't delete new untracked files created since last commit.</p>
<p>Does anybody have an idea how to do that?</p> | <pre><code>git reset --hard # removes staged and working directory changes
## !! be very careful with these !!
## you may end up deleting what you don't want to
## read comments and manual.
git clean -f -d # remove untracked
git clean -f -x -d # CAUTION: as above but removes ignored files like config.
git clean -fxd :/ # CAUTION: as above, but cleans untracked and ignored files through the entire repo (without :/, the operation affects only the current directory)
</code></pre>
<p>To see what will be deleted before-hand, without actually deleting it, use the <code>-n</code> flag (this is basically a test-run). When you are ready to actually delete, then remove the <code>-n</code> flag:</p>
<p><code>git clean -nfd</code></p> | {
"question_id": 1090309,
"question_date": "2009-07-07T04:07:40.263Z",
"question_score": 1294,
"tags": "git",
"answer_id": 1090316,
"answer_date": "2009-07-07T04:09:19.090Z",
"answer_score": 1899
} |
Please answer the following Stack Overflow question:
Title: performSelector may cause a leak because its selector is unknown
<p>I'm getting the following warning by the ARC compiler:</p>
<pre><code>"performSelector may cause a leak because its selector is unknown".
</code></pre>
<p>Here's what I'm doing:</p>
<pre><code>[_controller performSelector:NSSelectorFromString(@"someMethod")];
</code></pre>
<p>Why do I get this warning? I understand the compiler can't check if the selector exists or not, but why would that cause a leak? And how can I change my code so that I don't get this warning anymore?</p> | <h2>Solution</h2>
<p>The compiler is warning about this for a reason. It's very rare that this warning should simply be ignored, and it's easy to work around. Here's how:</p>
<pre><code>if (!_controller) { return; }
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);
</code></pre>
<p>Or more tersely (though hard to read & without the guard):</p>
<pre><code>SEL selector = NSSelectorFromString(@"someMethod");
((void (*)(id, SEL))[_controller methodForSelector:selector])(_controller, selector);
</code></pre>
<h2>Explanation</h2>
<p>What's going on here is you're asking the controller for the C function pointer for the method corresponding to the controller. All <code>NSObject</code>s respond to <code>methodForSelector:</code>, but you can also use <code>class_getMethodImplementation</code> in the Objective-C runtime (useful if you only have a protocol reference, like <code>id<SomeProto></code>). These function pointers are called <code>IMP</code>s, and are simple <code>typedef</code>ed function pointers (<code>id (*IMP)(id, SEL, ...)</code>)<sup>1</sup>. This may be close to the actual method signature of the method, but will not always match exactly.</p>
<p>Once you have the <code>IMP</code>, you need to cast it to a function pointer that includes all of the details that ARC needs (including the two implicit hidden arguments <code>self</code> and <code>_cmd</code> of every Objective-C method call). This is handled in the third line (the <code>(void *)</code> on the right hand side simply tells the compiler that you know what you're doing and not to generate a warning since the pointer types don't match).</p>
<p>Finally, you call the function pointer<sup>2</sup>.</p>
<h2>Complex Example</h2>
<p>When the selector takes arguments or returns a value, you'll have to change things a bit:</p>
<pre><code>SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = _controller ?
func(_controller, selector, someRect, someView) : CGRectZero;
</code></pre>
<h2>Reasoning for Warning</h2>
<p>The reason for this warning is that with ARC, the runtime needs to know what to do with the result of the method you're calling. The result could be anything: <code>void</code>, <code>int</code>, <code>char</code>, <code>NSString *</code>, <code>id</code>, etc. ARC normally gets this information from the header of the object type you're working with.<sup>3</sup></p>
<p>There are really only 4 things that ARC would consider for the return value:<sup>4</sup></p>
<ol>
<li>Ignore non-object types (<code>void</code>, <code>int</code>, etc)</li>
<li>Retain object value, then release when it is no longer used (standard assumption)</li>
<li>Release new object values when no longer used (methods in the <code>init</code>/ <code>copy</code> family or attributed with <code>ns_returns_retained</code>)</li>
<li>Do nothing & assume returned object value will be valid in local scope (until inner most release pool is drained, attributed with <code>ns_returns_autoreleased</code>)</li>
</ol>
<p>The call to <code>methodForSelector:</code> assumes that the return value of the method it's calling is an object, but does not retain/release it. So you could end up creating a leak if your object is supposed to be released as in #3 above (that is, the method you're calling returns a new object).</p>
<p>For selectors you're trying to call that return <code>void</code> or other non-objects, you could enable compiler features to ignore the warning, but it may be dangerous. I've seen Clang go through a few iterations of how it handles return values that aren't assigned to local variables. There's no reason that with ARC enabled that it can't retain and release the object value that's returned from <code>methodForSelector:</code> even though you don't want to use it. From the compiler's perspective, it is an object after all. That means that if the method you're calling, <code>someMethod</code>, is returning a non object (including <code>void</code>), you could end up with a garbage pointer value being retained/released and crash.</p>
<h2>Additional Arguments</h2>
<p>One consideration is that this is the same warning will occur with <code>performSelector:withObject:</code> and you could run into similar problems with not declaring how that method consumes parameters. ARC allows for declaring <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html#consumed-parameters" rel="noreferrer">consumed parameters</a>, and if the method consumes the parameter, you'll probably eventually send a message to a zombie and crash. There are ways to work around this with bridged casting, but really it'd be better to simply use the <code>IMP</code> and function pointer methodology above. Since consumed parameters are rarely an issue, this isn't likely to come up.</p>
<h2>Static Selectors</h2>
<p>Interestingly, the compiler will not complain about selectors declared statically:</p>
<pre><code>[_controller performSelector:@selector(someMethod)];
</code></pre>
<p>The reason for this is because the compiler actually is able to record all of the information about the selector and the object during compilation. It doesn't need to make any assumptions about anything. (I checked this a year a so ago by looking at the source, but don't have a reference right now.)</p>
<h2>Suppression</h2>
<p>In trying to think of a situation where suppression of this warning would be necessary and good code design, I'm coming up blank. Someone please share if they have had an experience where silencing this warning was necessary (and the above doesn't handle things properly).</p>
<h2>More</h2>
<p>It's possible to build up an <code>NSMethodInvocation</code> to handle this as well, but doing so requires a lot more typing and is also slower, so there's little reason to do it.</p>
<h2>History</h2>
<p>When the <code>performSelector:</code> family of methods was first added to Objective-C, ARC did not exist. While creating ARC, Apple decided that a warning should be generated for these methods as a way of guiding developers toward using other means to explicitly define how memory should be handled when sending arbitrary messages via a named selector. In Objective-C, developers are able to do this by using C style casts on raw function pointers.</p>
<p>With the introduction of Swift, Apple <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_38" rel="noreferrer">has documented</a> the <code>performSelector:</code> family of methods as "inherently unsafe" and they are not available to Swift.</p>
<p>Over time, we have seen this progression:</p>
<ol>
<li>Early versions of Objective-C allow <code>performSelector:</code> (manual memory management)</li>
<li>Objective-C with ARC warns for use of <code>performSelector:</code></li>
<li>Swift does not have access to <code>performSelector:</code> and documents these methods as "inherently unsafe"</li>
</ol>
<p>The idea of sending messages based on a named selector is not, however, an "inherently unsafe" feature. This idea has been used successfully for a long time in Objective-C as well as many other programming languages.</p>
<hr>
<p><sup>1</sup> All Objective-C methods have two hidden arguments, <code>self</code> and <code>_cmd</code> that are implicitly added when you call a method.</p>
<p><sup>2</sup> Calling a <code>NULL</code> function is not safe in C. The guard used to check for the presence of the controller ensures that we have an object. We therefore know we'll get an <code>IMP</code> from <code>methodForSelector:</code> (though it may be <code>_objc_msgForward</code>, entry into the message forwarding system). Basically, with the guard in place, we know we have a function to call.</p>
<p><sup>3</sup> Actually, it's possible for it to get the wrong info if declare you objects as <code>id</code> and you're not importing all headers. You could end up with crashes in code that the compiler thinks is fine. This is very rare, but could happen. Usually you'll just get a warning that it doesn't know which of two method signatures to choose from.</p>
<p><sup>4</sup> See the ARC reference on <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html#retained-return-values" rel="noreferrer">retained return values</a> and <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html#unretained-return-values" rel="noreferrer">unretained return values</a> for more details.</p> | {
"question_id": 7017281,
"question_date": "2011-08-10T20:23:24.387Z",
"question_score": 1294,
"tags": "ios|objective-c|memory-leaks|automatic-ref-counting",
"answer_id": 20058585,
"answer_date": "2013-11-18T21:44:29.753Z",
"answer_score": 1239
} |
Please answer the following Stack Overflow question:
Title: Correct way to write line to file?
<p>How do I write a line to a file in modern Python? I heard that this is deprecated:</p>
<pre><code>print >>f, "hi there"
</code></pre>
<p>Also, does <code>"\n"</code> work on all platforms, or should I use <code>"\r\n"</code> on Windows?</p> | <p>This should be as simple as:</p>
<pre><code>with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')
</code></pre>
<p>From The Documentation:</p>
<blockquote>
<p>Do not use <code>os.linesep</code> as a line terminator when writing files opened in text mode (the default); use a single <code>'\n'</code> instead, on all platforms.</p>
</blockquote>
<p>Some useful reading:</p>
<ul>
<li><a href="http://docs.python.org/reference/compound_stmts.html#the-with-statement" rel="noreferrer">The <code>with</code> statement</a></li>
<li><a href="http://docs.python.org/library/functions.html?highlight=open#open" rel="noreferrer"><code>open()</code></a>
<ul>
<li><code>'a'</code> is for append, or use</li>
<li><code>'w'</code> to write with truncation</li>
</ul>
</li>
<li><a href="http://docs.python.org/library/os.html" rel="noreferrer"><code>os</code></a> (particularly <a href="http://docs.python.org/library/os.html?highlight=os.linesep#os.linesep" rel="noreferrer"><code>os.linesep</code></a>)</li>
</ul> | {
"question_id": 6159900,
"question_date": "2011-05-28T05:44:53.783Z",
"question_score": 1293,
"tags": "python|file-io",
"answer_id": 6160082,
"answer_date": "2011-05-28T06:36:52.757Z",
"answer_score": 1458
} |
Please answer the following Stack Overflow question:
Title: How can I grep recursively, but only in files with certain extensions?
<p>I'm working on a script to <a href="https://en.wikipedia.org/wiki/Grep" rel="noreferrer"><code>grep</code></a> certain directories:</p>
<pre><code>{ grep -r -i CP_Image ~/path1/;
grep -r -i CP_Image ~/path2/;
grep -r -i CP_Image ~/path3/;
grep -r -i CP_Image ~/path4/;
grep -r -i CP_Image ~/path5/; }
| mailx -s GREP [email protected]
</code></pre>
<p>How can I limit results only to extensions <strong><code>.h</code></strong> and <strong><code>.cpp</code></strong>?</p> | <p>Just use the <code>--include</code> parameter, like this:</p>
<pre><code>grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
</code></pre>
<p>That should do what you want.</p>
<p>To take the explanation from <a href="https://stackoverflow.com/questions/12516937/how-can-i-grep-recursively-but-only-in-files-with-certain-extensions/35280826#35280826">HoldOffHunger's answer</a> below:</p>
<ul>
<li><p><code>grep</code>: command</p>
</li>
<li><p><code>-r</code>: recursively</p>
</li>
<li><p><code>-i</code>: ignore-case</p>
</li>
<li><p><code>-n</code>: each output line is preceded by its relative line number in the file</p>
</li>
<li><p><code>--include \*.cpp</code>: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)</p>
</li>
<li><p><code>./</code>: Start at current directory.</p>
</li>
</ul> | {
"question_id": 12516937,
"question_date": "2012-09-20T16:30:34.553Z",
"question_score": 1292,
"tags": "grep",
"answer_id": 12517022,
"answer_date": "2012-09-20T16:35:49.843Z",
"answer_score": 1757
} |
Please answer the following Stack Overflow question:
Title: How to remove item from array by value?
<p>Is there a method to remove an item from a JavaScript array?</p>
<p>Given an array:</p>
<pre><code>var ary = ['three', 'seven', 'eleven'];
</code></pre>
<p>I would like to do something like:</p>
<pre><code>removeItem('seven', ary);
</code></pre>
<p>I've looked into <code>splice()</code> but that only removes by the position number, whereas I need something to remove an item by its value.</p> | <p>This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.</p>
<pre><code>Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var ary = ['three', 'seven', 'eleven'];
ary.remove('seven');
/* returned value: (Array)
three,eleven
*/
</code></pre>
<p>To make it a global-</p>
<pre><code>function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');
/* returned value: (Array)
three,eleven
*/
</code></pre>
<p>And to take care of IE8 and below-</p>
<pre><code>if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(what, i) {
i = i || 0;
var L = this.length;
while (i < L) {
if(this[i] === what) return i;
++i;
}
return -1;
};
}
</code></pre> | {
"question_id": 3954438,
"question_date": "2010-10-17T17:43:34.540Z",
"question_score": 1291,
"tags": "javascript|arrays",
"answer_id": 3955096,
"answer_date": "2010-10-17T20:16:30.760Z",
"answer_score": 554
} |
Please answer the following Stack Overflow question:
Title: Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?
<p>I'm trying to link a <code>UILabel</code> with an <code>IBOutlet</code> created in my class.</p>
<p>My application is crashing with the following error. </p>
<p>What does this mean? </p>
<p>How can I fix it?</p>
<blockquote>
<p>*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x6e36ae0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key XXX.'</p>
</blockquote> | <h2>Your view controller may have the wrong class in your xib.</h2>
<p>I downloaded your project. </p>
<p>The error you are getting is </p>
<blockquote>
<p>'NSUnknownKeyException', reason: '[<UIViewController 0x3927310> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key string.'</p>
</blockquote>
<p>It is caused by the <code>Second</code> view controller in <code>MainWindow.xib</code> having a class of <strong><code>UIViewController</code> instead of <code>SecondView</code></strong>. Changing to the correct class resolves the problem. </p>
<p>By the way, it is bad practice to have names like "string" in Objective-C. It invites a runtime naming collision. Avoid them even in once off practice apps. Naming collisions can be very hard to track down and you don't want to waste the time. </p>
<p>Another possible reason for this error: when copying & pasting elements from one controller into another, Xcode somehow keeps that link to the original controller, even after editing & relinking this element into the new controller.</p>
<p><strong>Another possible reason for this error:</strong></p>
<p>Bad Outlet.</p>
<p>You have either <em>removed</em> or <em>renamed</em> an outlet name in your <code>.h</code> file.</p>
<p>Remove it in <code>.xib</code> or <code>.storyboard</code> file's Connection Inspector.</p>
<p><strong>One more possible reason</strong> </p>
<p>(In my case) Extension of UIView with bindable properties and setting values for those bindable properties (i.e. shadow, corner radius etc.) then remove those properties from UIView extension (for some reason) but the following <code><userDefinedRuntimeAttributes></code> remained in xml (of <code>foo.storyboard</code>):</p>
<pre><code><userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="color" keyPath="shadowColor">
<color key="value" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="shadowOpacity">
<real key="value" value="50"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="point" keyPath="shadowOffset">
<point key="value" x="5" y="5"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="shadowRadius">
<real key="value" value="16"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="borderWidthValue">
<real key="value" value="0.0"/>
</userDefinedRuntimeAttribute>
</userDefinedRuntimeAttributes>
</code></pre>
<p><strong>Solution:</strong> Right click on <code>foo.storyboard</code> > Open as Source Code > search by keyPath (i.e. shadowRadius) > Delete the <code></userDefinedRuntimeAttributes></code> that causing the problem</p> | {
"question_id": 3088059,
"question_date": "2010-06-21T19:57:32.383Z",
"question_score": 1291,
"tags": "ios|macos|cocoa|cocoa-touch|interface-builder",
"answer_id": 3088280,
"answer_date": "2010-06-21T20:29:07.633Z",
"answer_score": 1055
} |
Please answer the following Stack Overflow question:
Title: Enumerations on PHP
<p>I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.</p>
<p>Constants do the trick, but there's the namespace collision problem and (or actually <em>because</em>) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.</p>
<p>Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?</p> | <p>Depending upon use case, I would normally use something <em>simple</em> like the following:</p>
<pre><code>abstract class DaysOfWeek
{
const Sunday = 0;
const Monday = 1;
// etc.
}
$today = DaysOfWeek::Sunday;
</code></pre>
<p>However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and <a href="https://stackoverflow.com/a/21536800/102937">a few other notes</a>, here's an expanded example which may better serve a much wider range of cases:</p>
<pre><code>abstract class BasicEnum {
private static $constCacheArray = NULL;
private static function getConstants() {
if (self::$constCacheArray == NULL) {
self::$constCacheArray = [];
}
$calledClass = get_called_class();
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}
public static function isValidName($name, $strict = false) {
$constants = self::getConstants();
if ($strict) {
return array_key_exists($name, $constants);
}
$keys = array_map('strtolower', array_keys($constants));
return in_array(strtolower($name), $keys);
}
public static function isValidValue($value, $strict = true) {
$values = array_values(self::getConstants());
return in_array($value, $values, $strict);
}
}
</code></pre>
<p>By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:</p>
<pre><code>abstract class DaysOfWeek extends BasicEnum {
const Sunday = 0;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;
const Thursday = 4;
const Friday = 5;
const Saturday = 6;
}
DaysOfWeek::isValidName('Humpday'); // false
DaysOfWeek::isValidName('Monday'); // true
DaysOfWeek::isValidName('monday'); // true
DaysOfWeek::isValidName('monday', $strict = true); // false
DaysOfWeek::isValidName(0); // false
DaysOfWeek::isValidValue(0); // true
DaysOfWeek::isValidValue(5); // true
DaysOfWeek::isValidValue(7); // false
DaysOfWeek::isValidValue('Friday'); // false
</code></pre>
<p>As a side note, any time I use reflection at least once <strong>on a static/const class where the data won't change</strong> (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).</p>
<p>Now that most people have <strong>finally</strong> upgraded to at least 5.3, and <code>SplEnum</code> is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum <em>instantiations</em> throughout your codebase. In the above example, <code>BasicEnum</code> and <code>DaysOfWeek</code> cannot be instantiated at all, nor should they be.</p> | {
"question_id": 254514,
"question_date": "2008-10-31T18:51:14.840Z",
"question_score": 1291,
"tags": "php|enumeration",
"answer_id": 254543,
"answer_date": "2008-10-31T18:59:44.807Z",
"answer_score": 1625
} |
Please answer the following Stack Overflow question:
Title: Difference between JOIN and INNER JOIN
<p>Both these joins will give me the same results:</p>
<pre><code>SELECT * FROM table JOIN otherTable ON table.ID = otherTable.FK
</code></pre>
<p>vs</p>
<pre><code>SELECT * FROM table INNER JOIN otherTable ON table.ID = otherTable.FK
</code></pre>
<p>Is there any difference between the statements in performance or otherwise? </p>
<p>Does it differ between different <strong>SQL</strong> implementations? </p> | <p>They are functionally equivalent, but <code>INNER JOIN</code> can be a bit clearer to read, especially if the query has other join types (i.e. <code>LEFT</code> or <code>RIGHT</code> or <code>CROSS</code>) included in it.</p> | {
"question_id": 565620,
"question_date": "2009-02-19T14:47:29.977Z",
"question_score": 1289,
"tags": "sql|sql-server|join|inner-join",
"answer_id": 565640,
"answer_date": "2009-02-19T14:50:21.047Z",
"answer_score": 1401
} |
Please answer the following Stack Overflow question:
Title: Get a list from Pandas DataFrame column headers
<p>I want to get a list of the column headers from a Pandas DataFrame. The DataFrame will come from user input, so I won't know how many columns there will be or what they will be called.</p>
<p>For example, if I'm given a DataFrame like this:</p>
<pre><code>>>> my_dataframe
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
3 3 4 7
4 6 7 7
5 4 8 3
6 8 2 8
7 9 9 10
8 6 6 4
9 10 10 7
</code></pre>
<p>I would get a list like this:</p>
<pre><code>>>> header_list
['y', 'gdp', 'cap']
</code></pre> | <p>You can get the values as a list by doing:</p>
<pre><code>list(my_dataframe.columns.values)
</code></pre>
<p>Also you can simply use (as shown in <a href="https://stackoverflow.com/a/19483602/4909087">Ed Chum's answer</a>):</p>
<pre><code>list(my_dataframe)
</code></pre> | {
"question_id": 19482970,
"question_date": "2013-10-20T21:18:37.957Z",
"question_score": 1286,
"tags": "python|pandas|dataframe",
"answer_id": 19483025,
"answer_date": "2013-10-20T21:23:07.363Z",
"answer_score": 1945
} |
Please answer the following Stack Overflow question:
Title: Why does comparing strings using either '==' or 'is' sometimes produce a different result?
<p>Two string variables are set to the same value. <code>s1 == s2</code> always returns <code>True</code>, but <code>s1 is s2</code> sometimes returns <code>False</code>.</p>
<p>If I open my Python interpreter and do the same <code>is</code> comparison, it succeeds:</p>
<pre><code>>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True
</code></pre>
<p>Why is this?</p> | <p><code>is</code> is identity testing, <code>==</code> is equality testing. what happens in your code would be emulated in the interpreter like this:</p>
<pre><code>>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False
</code></pre>
<p>so, no wonder they're not the same, right?</p>
<p>In other words: <code>a is b</code> is the equivalent of <code>id(a) == id(b)</code></p> | {
"question_id": 1504717,
"question_date": "2009-10-01T15:40:14.550Z",
"question_score": 1286,
"tags": "python|string|comparison|identity|equality",
"answer_id": 1504742,
"answer_date": "2009-10-01T15:45:20.020Z",
"answer_score": 1648
} |
Please answer the following Stack Overflow question:
Title: Access-Control-Allow-Origin Multiple Origin Domains?
<p>Is there a way to allow multiple cross-domains using the <code>Access-Control-Allow-Origin</code> header?</p>
<p>I'm aware of the <code>*</code>, but it is too open. I really want to allow just a couple domains.</p>
<p>As an example, something like this:</p>
<pre><code>Access-Control-Allow-Origin: http://domain1.example, http://domain2.example
</code></pre>
<p>I have tried the above code but it does not seem to work in Firefox.</p>
<p>Is it possible to specify multiple domains or am I stuck with just one?</p> | <p>Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you would like to allow, and if it matches, echo the value of the <code>Origin</code> header back to the client as the <code>Access-Control-Allow-Origin</code> header in the response.</p>
<p>With <code>.htaccess</code> you can do it like this:</p>
<pre><code># ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header merge Vary Origin
</IfModule>
</FilesMatch>
</code></pre> | {
"question_id": 1653308,
"question_date": "2009-10-31T03:27:44.493Z",
"question_score": 1286,
"tags": ".htaccess|http|cors|xmlhttprequest|cross-domain",
"answer_id": 1850482,
"answer_date": "2009-12-05T00:10:06.193Z",
"answer_score": 1007
} |
Please answer the following Stack Overflow question:
Title: Remove element by id
<p>When removing an element with standard JavaScript, you must go to its parent first:</p>
<pre><code>var element = document.getElementById("element-id");
element.parentNode.removeChild(element);
</code></pre>
<p>Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?</p> | <h3>Update 2011</h3>
<p>This was added to the <a href="https://dom.spec.whatwg.org/#dom-childnode-remove" rel="nofollow noreferrer">DOM spec</a> back <a href="https://github.com/whatwg/dom/commit/85ff0b8#diff-d8adac750acc947123f2d8e77244ac97ed1e32fa65c0ca334c08fc620ab7ad60R3756" rel="nofollow noreferrer">in 2011</a>, so you can just use:</p>
<pre class="lang-js prettyprint-override"><code>element.remove()
</code></pre>
<p>The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So <code>element.parentNode.removeChild(element)</code> mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.</p>
<p>As of DOM4, a helper function is provided to do the same thing: <a href="https://developer.mozilla.org/en/docs/Web/API/ChildNode.remove" rel="nofollow noreferrer"><code>element.remove()</code></a>. This <a href="https://caniuse.com/childnode-remove" rel="nofollow noreferrer">works in 96% of browsers</a> (as of 2020), but not IE 11.</p>
<p><strong>If you need to support older browsers, you can</strong>:</p>
<ul>
<li>Remove elements via the parent node</li>
<li>Modify the native DOM functions, as in <a href="https://stackoverflow.com/a/18120786/405550">Johan Dettmar's answer</a>, or</li>
<li>Use a <a href="https://github.com/WebReflection/dom4#dom4" rel="nofollow noreferrer">DOM4 polyfill</a>.</li>
</ul> | {
"question_id": 3387427,
"question_date": "2010-08-01T18:47:14.110Z",
"question_score": 1285,
"tags": "javascript|dom",
"answer_id": 27710003,
"answer_date": "2014-12-30T17:41:34.487Z",
"answer_score": 119
} |
Please answer the following Stack Overflow question:
Title: Difference Between Select and SelectMany
<p>I've been searching the difference between <code>Select</code> and <code>SelectMany</code> but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are standard array examples. </p>
<p>Can someone provide a LINQ To SQL example?</p> | <p><code>SelectMany</code> flattens queries that return lists of lists. For example</p>
<pre><code>public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
public string Name { get; set; }
}
IEnumerable<Person> people = new List<Person>();
// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
// And to include data from the parent in the result:
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
.SelectMany(p => p.PhoneNumbers,
(parent, child) => new { parent.Name, child.Number });
</code></pre>
<p><a href="https://dotnetfiddle.net/LNyymI" rel="noreferrer">Live Demo on .NET Fiddle</a></p> | {
"question_id": 958949,
"question_date": "2009-06-06T03:54:16.847Z",
"question_score": 1285,
"tags": "c#|linq-to-sql|linq",
"answer_id": 959057,
"answer_date": "2009-06-06T05:23:39.230Z",
"answer_score": 1861
} |
Please answer the following Stack Overflow question:
Title: How do I reverse a list or loop over it backwards?
<p>How do I iterate over a list in reverse in Python?</p>
<hr />
<p><sub>See also: <a href="https://stackoverflow.com/questions/4280691/">How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?</a></sub></p> | <p>To get a <em>new</em> reversed list, apply the <a href="https://docs.python.org/3/library/functions.html#reversed" rel="noreferrer"><code>reversed</code></a> function and collect the items into a <a href="https://docs.python.org/3/library/stdtypes.html#list" rel="noreferrer"><code>list</code></a>:</p>
<pre><code>>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
</code></pre>
<p>To iterate backwards through a list:</p>
<pre><code>>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
</code></pre> | {
"question_id": 3940128,
"question_date": "2010-10-15T06:59:39.417Z",
"question_score": 1284,
"tags": "python|list",
"answer_id": 3940144,
"answer_date": "2010-10-15T07:02:20.487Z",
"answer_score": 1587
} |
Please answer the following Stack Overflow question:
Title: Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
<p>We all know you can't do the following because of <code>ConcurrentModificationException</code>:</p>
<pre><code>for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
</code></pre>
<p>But this apparently works sometimes, but not always. Here's some specific code:</p>
<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
</code></pre>
<p>This, of course, results in:</p>
<pre><code>Exception in thread "main" java.util.ConcurrentModificationException
</code></pre>
<p>Even though multiple threads aren't doing it. Anyway.</p>
<p>What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?</p>
<p>I'm also using an arbitrary <code>Collection</code> here, not necessarily an <code>ArrayList</code>, so you can't rely on <code>get</code>.</p> | <p><a href="https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--" rel="noreferrer"><code>Iterator.remove()</code></a> is safe, you can use it like this:</p>
<pre><code>List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string.isEmpty()) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
</code></pre>
<p>Note that <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html#remove--" rel="noreferrer"><code>Iterator.remove()</code></a> is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified <strong>in any other way</strong> while the iteration is in progress.</p>
<p>Source:<a href="http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html" rel="noreferrer"> docs.oracle > The Collection Interface</a></p>
<hr>
<p>And similarly, if you have a <code>ListIterator</code> and want to <em>add</em> items, you can use <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#add-E-" rel="noreferrer"><code>ListIterator#add</code></a>, for the same reason you can use <code>Iterator#remove</code> — it's designed to allow it.</p>
<hr>
<p>In your case you tried to remove from a list, but the same restriction applies if trying to <code>put</code> into a <code>Map</code> while iterating its content. </p> | {
"question_id": 223918,
"question_date": "2008-10-21T23:23:33.123Z",
"question_score": 1281,
"tags": "java|collections|iteration",
"answer_id": 223929,
"answer_date": "2008-10-21T23:27:15.203Z",
"answer_score": 1659
} |
Please answer the following Stack Overflow question:
Title: Display number with leading zeros
<p>How do I display a leading zero for all numbers with less than two digits?</p>
<pre class="lang-none prettyprint-override"><code>1 → 01
10 → 10
100 → 100
</code></pre> | <p>In Python 2 (and Python 3) you can do:</p>
<pre><code>number = 1
print("%02d" % (number,))
</code></pre>
<p>Basically <strong>%</strong> is like <code>printf</code> or <code>sprintf</code> (see <a href="https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting" rel="noreferrer">docs</a>).</p>
<hr />
<p>For Python 3.+, the same behavior can also be achieved with <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="noreferrer"><code>format</code></a>:</p>
<pre><code>number = 1
print("{:02d}".format(number))
</code></pre>
<hr />
<p>For Python 3.6+ the same behavior can be achieved with <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">f-strings</a>:</p>
<pre><code>number = 1
print(f"{number:02d}")
</code></pre> | {
"question_id": 134934,
"question_date": "2008-09-25T18:06:06.487Z",
"question_score": 1278,
"tags": "python|integer|string-formatting",
"answer_id": 134951,
"answer_date": "2008-09-25T18:08:21.363Z",
"answer_score": 1639
} |
Please answer the following Stack Overflow question:
Title: Getting key with maximum value in dictionary?
<p>I have a dictionary where keys are strings, and values are integers.</p>
<pre><code>stats = {'a': 1, 'b': 3000, 'c': 0}
</code></pre>
<p>How do I get the key with the maximum value? In this case, it is <code>'b'</code>.</p>
<hr />
<p>Is there a nicer approach than using an intermediate list with reversed key-value tuples?</p>
<pre><code>inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
</code></pre> | <p>You can use <code>operator.itemgetter</code> for that:</p>
<pre><code>import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
</code></pre>
<p>And instead of building a new list in memory use <code>stats.iteritems()</code>. The <code>key</code> parameter to the <code>max()</code> function is a function that computes a key that is used to determine how to rank items.</p>
<p>Please note that if you were to have another key-value pair 'd': 3000 that this method will only return <strong>one</strong> of the <strong>two</strong> even though they both have the maximum value.</p>
<pre><code>>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
</code></pre>
<p>If using Python3:</p>
<pre><code>>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
</code></pre> | {
"question_id": 268272,
"question_date": "2008-11-06T10:49:58.757Z",
"question_score": 1277,
"tags": "python|dictionary|max",
"answer_id": 268285,
"answer_date": "2008-11-06T10:58:45.977Z",
"answer_score": 751
} |
Please answer the following Stack Overflow question:
Title: jQuery get specific option tag text
<p>All right, say I have this:</p>
<pre><code><select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
</code></pre>
<p>What would the selector look like if I wanted to get "Option B" when I have the value '2'?</p>
<p>Please note that this is not asking how to get the <em>selected</em> text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:</p>
<pre><code>$("#list[value='2']").text();
</code></pre>
<p>But it is not working.</p> | <p>It's looking for an element with id <code>list</code> which has a property <code>value</code> equal to <code>2</code>.<br>
What you want is the <code>option</code> child of the <code>list</code>:</p>
<pre><code>$("#list option[value='2']").text()
</code></pre> | {
"question_id": 196684,
"question_date": "2008-10-13T04:06:34.693Z",
"question_score": 1277,
"tags": "javascript|jquery|jquery-selectors|html-select",
"answer_id": 196687,
"answer_date": "2008-10-13T04:08:03.723Z",
"answer_score": 1144
} |
Please answer the following Stack Overflow question:
Title: Create a Pandas Dataframe by appending one row at a time
<p>How do I create an empty <code>DataFrame</code>, then add rows, one by one?</p>
<p>I created an empty <code>DataFrame</code>:</p>
<pre><code>df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
</code></pre>
<p>Then I can add a new row at the end and fill a single field with:</p>
<pre><code>df = df._set_value(index=len(df), col='qty1', value=10.0)
</code></pre>
<p>It works for only one field at a time. What is a better way to add new row to <code>df</code>?</p> | <p>You can use <code>df.loc[i]</code>, where the row with index <code>i</code> will be what you specify it to be in the dataframe.</p>
<pre><code>>>> import pandas as pd
>>> from numpy.random import randint
>>> df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
>>> for i in range(5):
>>> df.loc[i] = ['name' + str(i)] + list(randint(10, size=2))
>>> df
lib qty1 qty2
0 name0 3 3
1 name1 2 4
2 name2 2 8
3 name3 2 1
4 name4 9 6
</code></pre> | {
"question_id": 10715965,
"question_date": "2012-05-23T08:12:31.843Z",
"question_score": 1276,
"tags": "python|pandas|dataframe|append",
"answer_id": 24888331,
"answer_date": "2014-07-22T13:10:25.313Z",
"answer_score": 852
} |
Please answer the following Stack Overflow question:
Title: Running shell command and capturing the output
<p>I want to write a function that will execute a shell command and return its output <strong>as a string</strong>, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.</p>
<p>What would be a code example that would do such a thing?</p>
<p>For example:</p>
<pre><code>def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
</code></pre> | <p>In all officially maintained versions of Python, the simplest approach is to use the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="noreferrer"><code>subprocess.check_output</code></a> function:</p>
<pre><code>>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p><code>check_output</code> runs a single program that takes only arguments as input.<sup>1</sup> It returns the result exactly as printed to <code>stdout</code>. If you need to write input to <code>stdin</code>, skip ahead to the <code>run</code> or <code>Popen</code> sections. If you want to execute complex shell commands, see the note on <code>shell=True</code> at the end of this answer.</p>
<p>The <code>check_output</code> function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.</p>
<h3>Modern versions of Python (3.5 or higher): <code>run</code></h3>
<p>If you're using <strong>Python 3.5+</strong>, and <strong>do not need backwards compatibility</strong>, the new <a href="https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module" rel="noreferrer"><code>run</code></a> function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the <a href="https://docs.python.org/3/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> module. To capture the output of a program, pass the <code>subprocess.PIPE</code> flag to the <code>stdout</code> keyword argument. Then access the <code>stdout</code> attribute of the returned <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess" rel="noreferrer"><code>CompletedProcess</code></a> object:</p>
<pre><code>>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>The return value is a <code>bytes</code> object, so if you want a proper string, you'll need to <code>decode</code> it. Assuming the called process returns a UTF-8-encoded string:</p>
<pre><code>>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>This can all be compressed to a one-liner if desired:</p>
<pre><code>>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>If you want to pass input to the process's <code>stdin</code>, you can pass a <code>bytes</code> object to the <code>input</code> keyword argument:</p>
<pre><code>>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'
</code></pre>
<p>You can capture errors by passing <code>stderr=subprocess.PIPE</code> (capture to <code>result.stderr</code>) or <code>stderr=subprocess.STDOUT</code> (capture to <code>result.stdout</code> along with regular output). If you want <code>run</code> to throw an exception when the process returns a nonzero exit code, you can pass <code>check=True</code>. (Or you can check the <code>returncode</code> attribute of <code>result</code> above.) When security is not a concern, you can also run more complex shell commands by passing <code>shell=True</code> as described at the end of this answer.</p>
<p>Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:</p>
<pre><code>>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
</code></pre>
<p>Using <code>run</code> this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the <code>run</code> function alone.</p>
<h3>Older versions of Python (3-3.4): more about <code>check_output</code></h3>
<p>If you are using an older version of Python, or need modest backwards compatibility, you can use the <code>check_output</code> function as briefly described above. It has been available since Python 2.7.</p>
<pre><code>subprocess.check_output(*popenargs, **kwargs)
</code></pre>
<p>It takes takes the same arguments as <code>Popen</code> (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, <code>check_output</code> is equivalent to executing <code>run</code> with <code>check=True</code> and <code>stdout=PIPE</code>, and returning just the <code>stdout</code> attribute.</p>
<p>You can pass <code>stderr=subprocess.STDOUT</code> to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing <code>shell=True</code> as described at the end of this answer.</p>
<p>If you need to pipe from <code>stderr</code> or pass input to the process, <code>check_output</code> won't be up to the task. See the <code>Popen</code> examples below in that case.</p>
<h3>Complex applications and legacy versions of Python (2.6 and below): <code>Popen</code></h3>
<p>If you need deep backwards compatibility, or if you need more sophisticated functionality than <code>check_output</code> or <code>run</code> provide, you'll have to work directly with <code>Popen</code> objects, which encapsulate the low-level API for subprocesses.</p>
<p>The <code>Popen</code> constructor accepts either <strong>a single command</strong> without arguments, or <strong>a list</strong> containing a command as its first item, followed by any number of arguments, each as a separate item in the list. <a href="https://docs.python.org/3/library/shlex.html" rel="noreferrer"><code>shlex.split</code></a> can help parse strings into appropriately formatted lists. <code>Popen</code> objects also accept a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="noreferrer">host of different arguments</a> for process IO management and low-level configuration.</p>
<p>To send input and capture output, <code>communicate</code> is almost always the preferred method. As in:</p>
<pre><code>output = subprocess.Popen(["mycmd", "myarg"],
stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>Or</p>
<pre><code>>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE,
... stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo
</code></pre>
<p>If you set <code>stdin=PIPE</code>, <code>communicate</code> also allows you to pass data to the process via <code>stdin</code>:</p>
<pre><code>>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo
</code></pre>
<p>Note <a href="https://stackoverflow.com/a/21867841/577088">Aaron Hall's answer</a>, which indicates that on some systems, you may need to set <code>stdout</code>, <code>stderr</code>, and <code>stdin</code> all to <code>PIPE</code> (or <code>DEVNULL</code>) to get <code>communicate</code> to work at all.</p>
<p>In some rare cases, you may need complex, real-time output capturing. <a href="https://stackoverflow.com/a/4760274/577088">Vartec</a>'s answer suggests a way forward, but methods other than <code>communicate</code> are prone to deadlocks if not used carefully.</p>
<p>As with all the above functions, when security is not a concern, you can run more complex shell commands by passing <code>shell=True</code>.</p>
<h3>Notes</h3>
<p><strong>1. Running shell commands: the <code>shell=True</code> argument</strong></p>
<p>Normally, each call to <code>run</code>, <code>check_output</code>, or the <code>Popen</code> constructor executes a <em>single program</em>. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass <code>shell=True</code>, which all three functions support. For example:</p>
<pre><code>>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'
</code></pre>
<p>However, doing this raises <a href="https://docs.python.org/3/library/subprocess.html#security-considerations" rel="noreferrer">security concerns</a>. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via</p>
<pre><code>run(cmd, [stdout=etc...], input=other_output)
</code></pre>
<p>Or</p>
<pre><code>Popen(cmd, [stdout=etc...]).communicate(other_output)
</code></pre>
<p>The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like <a href="https://stackoverflow.com/questions/6341451/piping-together-several-subprocesses">this</a>.</p> | {
"question_id": 4760215,
"question_date": "2011-01-21T14:55:44.413Z",
"question_score": 1276,
"tags": "python|shell|subprocess",
"answer_id": 4760517,
"answer_date": "2011-01-21T15:27:52.300Z",
"answer_score": 1696
} |
Please answer the following Stack Overflow question:
Title: How do I find the location of my Python site-packages directory?
<p>How do I find the location of my site-packages directory?</p> | <p>There are two types of site-packages directories, <em>global</em> and <em>per user</em>.</p>
<ol>
<li><p><strong>Global</strong> site-packages ("<a href="https://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages">dist-packages</a>") directories are listed in <code>sys.path</code> when you run:</p>
<pre><code> python -m site
</code></pre>
<p>For a more concise list run <code>getsitepackages</code> from the <a href="https://docs.python.org/3/library/site.html#site.getsitepackages" rel="noreferrer">site module</a> in Python code:</p>
<pre><code> python -c 'import site; print(site.getsitepackages())'
</code></pre>
<p><em>Caution:</em> In virtual environments <a href="https://github.com/pypa/virtualenv/issues/228" rel="noreferrer">getsitepackages is not available</a> with <a href="https://github.com/pypa/virtualenv/pull/2379/files" rel="noreferrer">older versions of <code>virtualenv</code></a>, <code>sys.path</code> from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the <a href="https://docs.python.org/3/library/sysconfig.html#using-sysconfig-as-a-script" rel="noreferrer">sysconfig module</a> instead:</p>
<pre><code> python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
</code></pre>
</li>
<li><p>The <strong>per user</strong> site-packages directory (<a href="https://www.python.org/dev/peps/pep-0370/" rel="noreferrer">PEP 370</a>) is where Python installs your local packages:</p>
<pre><code> python -m site --user-site
</code></pre>
<p>If this points to a non-existing directory check the exit status of Python and see <code>python -m site --help</code> for explanations.</p>
<p><em>Hint:</em> Running <code>pip list --user</code> or <code>pip freeze --user</code> gives you a list of all installed <em>per user</em> site-packages.</p>
</li>
</ol>
<hr />
<h2>Practical Tips</h2>
<ul>
<li><p><code><package>.__path__</code> lets you identify the location(s) of a specific package: (<a href="https://stackoverflow.com/questions/2699287/what-is-path-useful-for">details</a>)</p>
<pre><code> $ python -c "import setuptools as _; print(_.__path__)"
['/usr/lib/python2.7/dist-packages/setuptools']
</code></pre>
</li>
<li><p><code><module>.__file__</code> lets you identify the location of a specific module: (<a href="https://softwareengineering.stackexchange.com/questions/111871/module-vs-package">difference</a>)</p>
<pre><code> $ python3 -c "import os as _; print(_.__file__)"
/usr/lib/python3.6/os.py
</code></pre>
</li>
<li><p>Run <code>pip show <package></code> to show Debian-style package information:</p>
<pre><code> $ pip show pytest
Name: pytest
Version: 3.8.2
Summary: pytest: simple powerful testing with Python
Home-page: https://docs.pytest.org/en/latest/
Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
Author-email: None
License: MIT license
Location: /home/peter/.local/lib/python3.4/site-packages
Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
</code></pre>
</li>
</ul> | {
"question_id": 122327,
"question_date": "2008-09-23T17:04:43.937Z",
"question_score": 1276,
"tags": "python",
"answer_id": 46071447,
"answer_date": "2017-09-06T09:24:00.913Z",
"answer_score": 922
} |
Please answer the following Stack Overflow question:
Title: Open link in new tab or window
<p>Is it possible to open an <code>a href</code> link in a new tab instead of the same tab?</p>
<pre><code><a href="http://your_url_here.html">Link</a>
</code></pre> | <p>You should add the <code>target="_blank"</code> and <code>rel="noopener noreferrer"</code> in the anchor tag.</p>
<p>For example:</p>
<pre><code><a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>
</code></pre>
<p>Adding <code>rel="noopener noreferrer"</code> is not mandatory, but it's a recommended security measure. More information can be found in the links below. </p>
<p>Source: </p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target" rel="noreferrer">MDN | HTML element <code><a></code> | attribute <code>target</code></a></li>
<li><a href="https://mathiasbynens.github.io/rel-noopener/" rel="noreferrer">About rel=noopener</a></li>
<li><a href="https://developers.google.com/web/tools/lighthouse/audits/noopener" rel="noreferrer">Opens External Anchors Using rel="noopener"</a></li>
</ul> | {
"question_id": 15551779,
"question_date": "2013-03-21T15:33:40.960Z",
"question_score": 1275,
"tags": "html|tabs|hyperlink|window|href",
"answer_id": 15551842,
"answer_date": "2013-03-21T15:36:05.243Z",
"answer_score": 2288
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of the `self` parameter? Why is it needed?
<p>Consider this example:</p>
<pre class="lang-py prettyprint-override"><code>class MyClass:
def func(self, name):
self.name = name
</code></pre>
<p>I know that <code>self</code> refers to the specific instance of <code>MyClass</code>. But why must <code>func</code> explicitly include <code>self</code> as a parameter? Why do we need to use <code>self</code> in the method's code? Some other languages make this implicit, or use special syntax instead.</p>
<hr />
<p><sub>For a <em>language-agnostic</em> consideration of the design decision, see <a href="https://stackoverflow.com/questions/910020/">What is the advantage of having this/self pointer mandatory explicit?</a>.</sub></p>
<p><sub>To close <em>debugging questions</em> where OP omitted a <code>self</code> parameter for a method and got a <code>TypeError</code>, use <a href="https://stackoverflow.com/questions/23944657">TypeError: method() takes 1 positional argument but 2 were given</a> instead. If OP omitted <code>self.</code> in the body of the method and got a <code>NameError</code>, consider <a href="https://stackoverflow.com/questions/5615648">How can I call a function within a class?</a>.</sub></p> | <p>The reason you need to use <code>self.</code> is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be <em>passed</em> automatically, but not <em>received</em> automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although <code>self</code> is the convention, and people will generally frown at you when you use something else.) <code>self</code> is not special to the code, it's just another object.</p>
<p>Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs <code>self.</code>.</p> | {
"question_id": 2709821,
"question_date": "2010-04-25T20:22:28.587Z",
"question_score": 1274,
"tags": "python|class|oop|self",
"answer_id": 2709832,
"answer_date": "2010-04-25T20:25:37.537Z",
"answer_score": 766
} |
Please answer the following Stack Overflow question:
Title: How to remove remote origin from a Git repository
<p>I just did <code>git init</code> to initialize my folder as Git repository and then added a remote repository using <code>git remote add origin URL</code>. Now I want to remove this <code>git remote add origin</code> and add a new repository <code>git remote add origin new-URL</code>. How can I do it?</p> | <p>Instead of removing and re-adding, you can do this:</p>
<pre><code>git remote set-url origin git://new.url.here
</code></pre>
<p>See this question: <a href="https://stackoverflow.com/questions/2432764/how-to-change-a-remote-repository-uri-using-git">How to change the URI (URL) for a remote Git repository?</a></p>
<p>To remove remote use this:</p>
<pre><code>git remote remove origin
</code></pre> | {
"question_id": 16330404,
"question_date": "2013-05-02T04:37:18.553Z",
"question_score": 1273,
"tags": "git|git-remote",
"answer_id": 16330439,
"answer_date": "2013-05-02T04:40:20.367Z",
"answer_score": 2388
} |
Please answer the following Stack Overflow question:
Title: Redefine tab as 4 spaces
<p>My current setting assumes 8 spaces; how could I redefine it?</p> | <p>It depends on what you mean. Do you want actual tab characters in your file to <em>appear</em> 4 spaces wide, or by "tab" do you actually mean an <em>indent</em>, generated by pressing the tab key, which would result in the file literally containing (up to) 4 space characters for each "tab" you type?</p>
<p>Depending on your answer, one of the following sets of
settings should work for you:</p>
<ul>
<li><p><strong>For tab characters that appear 4-spaces-wide</strong>:</p>
<pre><code>set tabstop=4
</code></pre>
<p>If you're using actual tab character in your source code you probably also want these settings (these are actually the defaults, but you may want to set them defensively):</p>
<pre><code>set softtabstop=0 noexpandtab
</code></pre>
<p>Finally, if you want an indent to correspond to a single tab, you should also use:</p>
<pre><code>set shiftwidth=4
</code></pre></li>
<li><p><strong>For indents that consist of 4 space characters</strong> but are entered with the tab key:</p>
<pre><code>set tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab
</code></pre></li>
</ul>
<p><strong>To make the above settings permanent add
these lines to your <a href="https://stackoverflow.com/a/34005877/90848">vimrc</a>.</strong></p>
<p>In case you need to make adjustments, or would simply like to understand what these options all mean, here's a breakdown of what each option means:</p>
<blockquote>
<h2><code>tabstop</code></h2>
<p>The width of a hard tabstop measured in "spaces" -- effectively the (maximum) width of an actual tab character.</p>
<h2><code>shiftwidth</code></h2>
<p>The size of an "indent". It's also measured in spaces, so if your code base indents with tab characters then you want <code>shiftwidth</code> to equal the number of tab characters times <code>tabstop</code>. This is also used by things like the <code>=</code>, <code>></code> and <code><</code> commands.</p>
<h2><code>softtabstop</code></h2>
<p>Setting this to a non-zero value other than <code>tabstop</code> will make the tab key (in insert mode)
insert a combination of spaces (and possibly tabs) to <em>simulate</em> tab stops at this width.</p>
<h2><code>expandtab</code></h2>
<p>Enabling this will make the tab key (in insert mode) insert spaces instead of
tab characters. This also affects the behavior of the <code>retab</code> command.</p>
<h2><code>smarttab</code></h2>
<p>Enabling this will make the tab key (in insert mode) insert spaces or tabs to
go to the next indent
of the next tabstop when the cursor is at the beginning of a line (i.e. the
only preceding characters are whitespace).</p>
</blockquote>
<p>For more details on any of these see <code>:help '<em>optionname</em>'</code> in vim (e.g. <code>:help 'tabstop'</code>) </p> | {
"question_id": 1878974,
"question_date": "2009-12-10T06:18:03.420Z",
"question_score": 1273,
"tags": "vim",
"answer_id": 1878983,
"answer_date": "2009-12-10T06:19:49.680Z",
"answer_score": 1855
} |
Please answer the following Stack Overflow question:
Title: Activity has leaked window that was originally added
<p>What is this error, and why does it happen?</p>
<pre><code>05-17 18:24:57.069: ERROR/WindowManager(18850): Activity com.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
05-17 18:24:57.069: ERROR/WindowManager(18850): android.view.WindowLeaked: Activity ccom.mypkg.myP has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44c46ff0 that was originally added here
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.view.ViewRoot.<init>(ViewRoot.java:231)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.view.Window$LocalWindowManager.addView(Window.java:424)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.Dialog.show(Dialog.java:239)
05-17 18:24:57.069: ERROR/WindowManager(18850): at com.mypkg.myP$PreparePairingLinkageData.onPreExecute(viewP.java:183)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.os.AsyncTask.execute(AsyncTask.java:391)
05-17 18:24:57.069: ERROR/WindowManager(18850): at com.mypkg.myP.onCreate(viewP.java:94)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.ActivityThread.access$2200(ActivityThread.java:126)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.os.Looper.loop(Looper.java:123)
05-17 18:24:57.069: ERROR/WindowManager(18850): at android.app.ActivityThread.main(ActivityThread.java:4595)
05-17 18:24:57.069: ERROR/WindowManager(18850): at java.lang.reflect.Method.invokeNative(Native Method)
05-17 18:24:57.069: ERROR/WindowManager(18850): at java.lang.reflect.Method.invoke(Method.java:521)
05-17 18:24:57.069: ERROR/WindowManager(18850): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-17 18:24:57.069: ERROR/WindowManager(18850): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-17 18:24:57.069: ERROR/WindowManager(18850): at dalvik.system.NativeStart.main(Native Method)
</code></pre> | <p>You're trying to show a Dialog after you've exited an Activity.</p>
<p><strong>[EDIT]</strong></p>
<p>This question is one of the top search on google for android developer,
therefore Adding few important points from comments, which might be more helpful for future investigator without going in depth of comment conversation.</p>
<p><strong>Answer 1</strong> : </p>
<blockquote>
<p>You're trying to show a Dialog after you've exited an Activity.</p>
</blockquote>
<p><strong>Answer 2</strong> </p>
<blockquote>
<p>This error can be a little misleading in some circumstances (although
the answer is still completely accurate) - i.e. in my case an
unhandled Exception was thrown in an AsyncTask, which caused the
Activity to shutdown, then an open progressdialog caused this
Exception.. so the 'real' exception was a little earlier in the log</p>
</blockquote>
<p><strong>Answer 3</strong> </p>
<blockquote>
<p>Call dismiss() on the Dialog instance you created before exiting your
Activity, e.g. in onPause() or onDestroy()</p>
</blockquote> | {
"question_id": 2850573,
"question_date": "2010-05-17T15:51:23.853Z",
"question_score": 1271,
"tags": "android|memory-leaks|dialog",
"answer_id": 2850597,
"answer_date": "2010-05-17T15:54:21.943Z",
"answer_score": 1686
} |
Please answer the following Stack Overflow question:
Title: How do I check if a string contains another string in Objective-C?
<p>How can I check if a string (<code>NSString</code>) contains another smaller string?</p>
<p>I was hoping for something like:</p>
<pre><code>NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
</code></pre>
<p>But the closest I could find was:</p>
<pre><code>if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
</code></pre>
<p>Anyway, is that the best way to find if a string contains another string?</p> | <pre><code>NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
NSLog(@"string does not contain bla");
} else {
NSLog(@"string contains bla!");
}
</code></pre>
<p>The key is noticing that <code>rangeOfString:</code> returns an <code>NSRange</code> struct, and <a href="https://developer.apple.com/documentation/foundation/nsstring/1410144-rangeofstring?language=objc" rel="noreferrer">the documentation says</a> that it returns the struct <code>{NSNotFound, 0}</code> if the "haystack" does not contain the "needle".</p>
<hr>
<p>And if you're on iOS 8 or OS X Yosemite, you can now do: <strong>(*NOTE: This WILL crash your app if this code is called on an iOS7 device).</strong></p>
<pre><code>NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
</code></pre>
<p>(This is also how it would work in Swift)</p>
<p> </p> | {
"question_id": 2753956,
"question_date": "2010-05-02T15:34:54.230Z",
"question_score": 1270,
"tags": "ios|objective-c|string|range|substring",
"answer_id": 2754075,
"answer_date": "2010-05-02T16:20:25.033Z",
"answer_score": 2484
} |
Please answer the following Stack Overflow question:
Title: How to read a text file into a string variable and strip newlines?
<p>I have a text file that looks like:</p>
<pre><code>ABC
DEF
</code></pre>
<p>How can I read the file into a single-line string without newlines, in this case creating a string <code>'ABCDEF'</code>?</p>
<hr />
<p><sub>For reading the file into a <em>list</em> of lines, but removing the trailing newline character from each line, see <a href="https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines">How to read a file without newlines?</a>.</sub></p> | <p>You could use:</p>
<pre><code>with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
</code></pre>
<p>Or if the file content is guaranteed to be one-line</p>
<pre><code>with open('data.txt', 'r') as file:
data = file.read().rstrip()
</code></pre> | {
"question_id": 8369219,
"question_date": "2011-12-03T16:47:54.157Z",
"question_score": 1269,
"tags": "python|string",
"answer_id": 8369345,
"answer_date": "2011-12-03T17:06:34.077Z",
"answer_score": 1773
} |
Please answer the following Stack Overflow question:
Title: How to drop rows of Pandas DataFrame whose value in a certain column is NaN
<p>I have this <code>DataFrame</code> and want only the records whose <code>EPS</code> column is not <code>NaN</code>:</p>
<pre><code>>>> df
STK_ID EPS cash
STK_ID RPT_Date
601166 20111231 601166 NaN NaN
600036 20111231 600036 NaN 12
600016 20111231 600016 4.3 NaN
601009 20111231 601009 NaN NaN
601939 20111231 601939 2.5 NaN
000001 20111231 000001 NaN NaN
</code></pre>
<p>...i.e. something like <code>df.drop(....)</code> to get this resulting dataframe:</p>
<pre><code> STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
</code></pre>
<p>How do I do that?</p> | <p>Don't drop, just take the rows where EPS is not NA:</p>
<pre class="lang-py prettyprint-override"><code>df = df[df['EPS'].notna()]
</code></pre> | {
"question_id": 13413590,
"question_date": "2012-11-16T09:17:22.947Z",
"question_score": 1269,
"tags": "python|pandas|dataframe|nan",
"answer_id": 13413845,
"answer_date": "2012-11-16T09:34:38.297Z",
"answer_score": 1368
} |
Please answer the following Stack Overflow question:
Title: What is the <leader> in a .vimrc file?
<p>I see <code><leader></code> in many <code>.vimrc</code> files, and I am wondering what does it mean? </p>
<p>What is it used for? </p>
<p>Just a general overview of the purpose and usage would be great.</p> | <p>The <a href="https://vimhelp.org/map.txt.html#%3CLeader%3E" rel="noreferrer"><code><Leader></code></a> key is mapped to <kbd>\</kbd> by default. So if you have a map of <code><Leader>t</code>, you can execute it by default with <kbd>\</kbd>+<kbd>t</kbd>. For more detail or re-assigning it using the <code>mapleader</code> variable, see</p>
<p>:help leader</p>
<pre>
To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used. It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead.
Example:
:map <Leader>A oanother line <Esc>
Works like:
:map \A oanother line <Esc>
But after:
:let mapleader = ","
It works like:
:map ,A oanother line <Esc>
Note that the value of "mapleader" is used at the moment the mapping is
defined. Changing "mapleader" after that has no effect for already defined
mappings.
</pre> | {
"question_id": 1764263,
"question_date": "2009-11-19T15:49:22.973Z",
"question_score": 1264,
"tags": "vim|macvim",
"answer_id": 1764336,
"answer_date": "2009-11-19T15:57:24.723Z",
"answer_score": 1162
} |
Please answer the following Stack Overflow question:
Title: Better way to set distance between flexbox items
<p>To set the minimal distance between flexbox items I'm using <code>margin: 0 5px</code> on <code>.item</code> and <code>margin: 0 -5px</code> on container. For me it seems like a hack, but I can't find any better way to do this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
display: flex;
width: 100px;
margin: 0 -5px;
}
.item {
background: gray;
width: 50px;
height: 50px;
margin: 0 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div></code></pre>
</div>
</div>
</p> | <ul>
<li>Flexbox doesn't have collapsing margins.</li>
<li>Flexbox doesn't have anything akin to <code>border-spacing</code> for tables (edit: <strong>CSS property <code>gap</code> fulfills this role in newer browsers, <a href="https://caniuse.com/#feat=flexbox-gap" rel="noreferrer">Can I use</a></strong>)</li>
</ul>
<p>Therefore achieving what you are asking for is a bit more difficult.</p>
<p>In my experience, the "cleanest" way that doesn't use <code>:first-child</code>/<code>:last-child</code> and works without any modification on <code>flex-wrap:wrap</code> is to set <code>padding:5px</code> on the container and <code>margin:5px</code> on the children. That will produce a <code>10px</code> gap between each child and between each child and their parent.</p>
<p><a href="http://jsfiddle.net/7XD8s/" rel="noreferrer">Demo</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.upper {
margin: 30px;
display: flex;
flex-direction: row;
width: 300px;
height: 80px;
border: 1px red solid;
padding: 5px; /* this */
}
.upper > div {
flex: 1 1 auto;
border: 1px red solid;
text-align: center;
margin: 5px; /* and that, will result in a 10px gap */
}
.upper.mc /* multicol test */ {
flex-direction: column;
flex-wrap: wrap;
width: 200px;
height: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="upper">
<div>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa<br/>aaa</div>
<div>aaa<br/>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa</div>
</div>
<div class="upper mc">
<div>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa<br/>aaa</div>
<div>aaa<br/>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa</div>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 20626685,
"question_date": "2013-12-17T05:35:30.253Z",
"question_score": 1263,
"tags": "css|flexbox",
"answer_id": 20653092,
"answer_date": "2013-12-18T08:31:54.587Z",
"answer_score": 636
} |
Please answer the following Stack Overflow question:
Title: Get the first element of an array
<p>I have an array: </p>
<p><code>array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )</code></p>
<p>I would like to get the first element of this array. Expected result: <i>string</i> <code>apple</code> </p>
<p>One requirement: <em>it cannot be done with passing by reference</em>, so <code>array_shift</code> is not a good solution.</p>
<p>How can I do this?</p> | <p>Original answer, but costly (O(n)):</p>
<pre><code>array_shift(array_values($array));
</code></pre>
<p>In O(1):</p>
<pre><code>array_pop(array_reverse($array));
</code></pre>
<p><strong>Other use cases, etc...</strong></p>
<p>If modifying (in the sense of resetting array pointers) of <code>$array</code> is not a problem, you might use:</p>
<pre><code>reset($array);
</code></pre>
<p>This should be theoretically more efficient, if a array "copy" is needed:</p>
<pre><code>array_shift(array_slice($array, 0, 1));
</code></pre>
<p>With PHP 5.4+ (but might cause an index error if empty):</p>
<pre><code>array_values($array)[0];
</code></pre> | {
"question_id": 1921421,
"question_date": "2009-12-17T12:26:44.363Z",
"question_score": 1263,
"tags": "php|arrays",
"answer_id": 3771228,
"answer_date": "2010-09-22T16:04:19.097Z",
"answer_score": 1578
} |
Please answer the following Stack Overflow question:
Title: How to add a new column to an existing DataFrame?
<p>I have the following indexed DataFrame with named columns and rows not- continuous numbers:</p>
<pre><code> a b c d
2 0.671399 0.101208 -0.181532 0.241273
3 0.446172 -0.243316 0.051767 1.577318
5 0.614758 0.075793 -0.451460 -0.012493
</code></pre>
<p>I would like to add a new column, <code>'e'</code>, to the existing data frame and do not want to change anything in the data frame (i.e., the new column always has the same length as the DataFrame). </p>
<pre><code>0 -0.335485
1 -1.166658
2 -0.385571
dtype: float64
</code></pre>
<p>How can I add column <code>e</code> to the above example? </p> | <p><strong>Edit 2017</strong></p>
<p>As indicated in the comments and by @Alexander, currently the best method to add the values of a Series as a new column of a DataFrame could be using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="noreferrer"><strong><code>assign</code></strong></a>:</p>
<pre><code>df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values)
</code></pre>
<hr />
<p><strong>Edit 2015</strong><br />
Some reported getting the <code>SettingWithCopyWarning</code> with this code.<br />
However, the code still runs perfectly with the current pandas version 0.16.1.</p>
<pre><code>>>> sLength = len(df1['a'])
>>> df1
a b c d
6 -0.269221 -0.026476 0.997517 1.294385
8 0.917438 0.847941 0.034235 -0.448948
>>> df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
>>> df1
a b c d e
6 -0.269221 -0.026476 0.997517 1.294385 1.757167
8 0.917438 0.847941 0.034235 -0.448948 2.228131
>>> pd.version.short_version
'0.16.1'
</code></pre>
<p>The <code>SettingWithCopyWarning</code> aims to inform of a possibly invalid assignment on a copy of the Dataframe. It doesn't necessarily say you did it wrong (it can trigger false positives) but from 0.13.0 it let you know there are more adequate methods for the same purpose. Then, if you get the warning, just follow its advise: <em>Try using .loc[row_index,col_indexer] = value instead</em></p>
<pre><code>>>> df1.loc[:,'f'] = pd.Series(np.random.randn(sLength), index=df1.index)
>>> df1
a b c d e f
6 -0.269221 -0.026476 0.997517 1.294385 1.757167 -0.050927
8 0.917438 0.847941 0.034235 -0.448948 2.228131 0.006109
>>>
</code></pre>
<p>In fact, this is currently the more efficient method as <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="noreferrer">described in pandas docs</a></p>
<hr />
<p>Original answer:</p>
<p>Use the original df1 indexes to create the series:</p>
<pre><code>df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
</code></pre> | {
"question_id": 12555323,
"question_date": "2012-09-23T19:00:01.430Z",
"question_score": 1261,
"tags": "python|pandas|dataframe|chained-assignment",
"answer_id": 12555510,
"answer_date": "2012-09-23T19:24:45.883Z",
"answer_score": 1277
} |
Please answer the following Stack Overflow question:
Title: What effect does the `--no-ff` flag have for `git merge`?
<p>Using <code>gitk log</code>, I could not spot a difference between the effect of <code>git merge</code> and <code>git merge --no-ff</code>. How can I observe the difference (with a git command or some tool)?</p> | <p>The <code>--no-ff</code> flag prevents <code>git merge</code> from executing a "fast-forward" if it detects that your current <code>HEAD</code> is an ancestor of the commit you're trying to merge. A fast-forward is when, instead of constructing a merge commit, git just moves your branch pointer to point at the incoming commit. This commonly occurs when doing a <code>git pull</code> without any local changes.</p>
<p>However, occasionally you want to prevent this behavior from happening, typically because you want to maintain a specific branch topology (e.g. you're merging in a topic branch and you want to ensure it looks that way when reading history). In order to do that, you can pass the <code>--no-ff</code> flag and <code>git merge</code> will <em>always</em> construct a merge instead of fast-forwarding.</p>
<p>Similarly, if you want to execute a <code>git pull</code> or use <code>git merge</code> in order to explicitly fast-forward, and you want to bail out if it can't fast-forward, then you can use the <code>--ff-only</code> flag. This way you can regularly do something like <code>git pull --ff-only</code> without thinking, and then if it errors out you can go back and decide if you want to merge or rebase.</p> | {
"question_id": 9069061,
"question_date": "2012-01-30T18:45:41.240Z",
"question_score": 1261,
"tags": "git|merge|fast-forward",
"answer_id": 9069127,
"answer_date": "2012-01-30T18:51:29.940Z",
"answer_score": 1362
} |
Please answer the following Stack Overflow question:
Title: Run/install/debug Android applications over Wi-Fi?
<p>I thought there was a way to test your applications in development over Wi-Fi. Is this possible?</p>
<p>I'd love to be able to untether my phone and develop wirelessly.</p> | <p>See forum post <em><a href="http://forum.xda-developers.com/showpost.php?p=7594419&postcount=9" rel="noreferrer">Any way to view Android screen remotely without root? - Post #9</a></em>.</p>
<ol>
<li>Connect the device via USB and make sure debugging is working;</li>
<li><code>adb tcpip 5555</code>. This makes the device to start listening for connections on port 5555;</li>
<li>Look up the device IP address with <code>adb shell netcfg</code> or <code>adb shell ifconfig</code> with 6.0 and higher;</li>
<li>You can disconnect the USB now;</li>
<li><code>adb connect <DEVICE_IP_ADDRESS>:5555</code>. This connects to the server we set up on the device on step 2;</li>
<li>Now you have a device over the network with which you can debug as usual.</li>
</ol>
<p>To switch the server back to the USB mode, run <code>adb usb</code>, which will put the server on your phone back to the USB mode. If you have more than one device, you can specify the device with the <code>-s</code> option: <code>adb -s <DEVICE_IP_ADDRESS>:5555 usb</code>.</p>
<p>No root required!</p>
<p>To find the IP address of the device: run <code>adb shell</code> and then <code>netcfg</code>. You'll see it there.
To find the IP address while using OSX run the command <code>adb shell ip route</code>.</p>
<hr>
<p><strong>WARNING</strong>: leaving the option enabled is dangerous, anyone in your network can connect to your device in debug, even if you are in data network. Do it only when connected to a trusted Wi-Fi and remember to disconnect it when done!</p>
<hr>
<p>@Sergei suggested that line 2 should be modified, commenting: "-d option needed to connect to the USB device when the other connection persists (for example, emulator connected or other Wi-Fi device)".</p>
<p>This information may prove valuable to future readers, but I rolled-back to the original version that had received 178 upvotes.</p>
<hr>
<p><strong>On some device</strong> you can do the same thing even <strong>if you do not have an USB cable</strong>:</p>
<ol>
<li>Enable ADB over network in developer setting
<a href="https://i.stack.imgur.com/8euGG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8euGG.png" alt="Screenshot Showing the option on"></a>
It should show the IP address</li>
<li><code>adb connect <DEVICE_IP_ADDRESS>:5555</code></li>
<li>Disable the setting when done</li>
</ol>
<hr>
<p>Using Android Studio there is <a href="https://plugins.jetbrains.com/plugin/7856?pr=androidstudio" rel="noreferrer">a plugin</a> allowing you to connect USB Debugging without the need of using any ADB command from a terminal.</p> | {
"question_id": 4893953,
"question_date": "2011-02-04T02:23:38.143Z",
"question_score": 1261,
"tags": "android|debugging|adb|wifi",
"answer_id": 10236938,
"answer_date": "2012-04-19T21:19:06.687Z",
"answer_score": 1960
} |
Please answer the following Stack Overflow question:
Title: If Python is interpreted, what are .pyc files?
<p>Python is an interpreted language. But why does my source directory contain <code>.pyc</code> files, which are identified by Windows as "Compiled Python Files"?</p> | <p>They contain <a href="http://en.wikipedia.org/wiki/Bytecode" rel="noreferrer">byte code</a>, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine.</p>
<p><a href="https://docs.python.org/3/glossary.html#term-interpreted" rel="noreferrer">Python's documentation</a> explains the definition like this:</p>
<blockquote>
<p>Python is an interpreted language, as
opposed to a compiled one, though the
distinction can be blurry because of
the presence of the bytecode compiler.
This means that source files can be
run directly without explicitly
creating an executable which is then
run.</p>
</blockquote> | {
"question_id": 2998215,
"question_date": "2010-06-08T14:27:13.667Z",
"question_score": 1260,
"tags": "python|compiled|interpreted-language|pyc",
"answer_id": 2998228,
"answer_date": "2010-06-08T14:28:40.827Z",
"answer_score": 749
} |
Please answer the following Stack Overflow question:
Title: How do I check if a variable exists?
<p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p> | <p>To check the existence of a local variable:</p>
<pre><code>if 'myVar' in locals():
# myVar exists.
</code></pre>
<p>To check the existence of a global variable:</p>
<pre><code>if 'myVar' in globals():
# myVar exists.
</code></pre>
<p>To check if an object has an attribute:</p>
<pre><code>if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
</code></pre> | {
"question_id": 843277,
"question_date": "2009-05-09T13:10:31.610Z",
"question_score": 1258,
"tags": "python|exception|variables",
"answer_id": 843293,
"answer_date": "2009-05-09T13:16:05.670Z",
"answer_score": 2109
} |
Please answer the following Stack Overflow question:
Title: What is the difference between null=True and blank=True in Django?
<p>When we add a model field in Django we generally write:</p>
<pre><code>models.CharField(max_length=100, null=True, blank=True)
</code></pre>
<p>The same is done with <code>ForeignKey</code>, <code>DecimalField</code> etc. What is the basic difference between:</p>
<ol>
<li><code>null=True</code> only</li>
<li><code>blank=True</code> only</li>
<li><code>null=True</code> and <code>blank=True</code></li>
</ol>
<p>in respect to different (<code>CharField</code>, <code>ForeignKey</code>, <code>ManyToManyField</code>, <code>DateTimeField</code>) fields? What are the advantages/disadvantages of using option 1, 2, or 3?</p> | <p><code>null=True</code> sets <code>NULL</code> (versus <code>NOT NULL</code>) on the column in your DB. Blank values for Django field types such as <code>DateTimeField</code> or <code>ForeignKey</code> will be stored as <code>NULL</code> in the DB.</p>
<p><code>blank</code> determines whether the field will be required in forms. This includes the admin and your custom forms. If <code>blank=True</code> then the field will not be required, whereas if it's <code>False</code> the field cannot be blank.</p>
<p>The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow <code>NULL</code> values for that field. The exception is <code>CharField</code>s and <code>TextField</code>s, which in Django are <em>never</em> saved as <code>NULL</code>. Blank values are stored in the DB as an empty string (<code>''</code>).</p>
<p>A few examples:</p>
<pre><code>models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
</code></pre>
<p>Obviously, Those two options don't make logical sense to use (though there might be a use case for <code>null=True, blank=False</code> if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)</p>
<pre><code>models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
</code></pre>
<p><code>CHAR</code> and <code>TEXT</code> types are never saved as <code>NULL</code> by Django, so <code>null=True</code> is unnecessary. However, you can manually set one of these fields to <code>None</code> to force set it as <code>NULL</code>. If you have a scenario where that might be necessary, you should still include <code>null=True</code>.</p> | {
"question_id": 8609192,
"question_date": "2011-12-22T20:11:03.550Z",
"question_score": 1258,
"tags": "python|django|django-models",
"answer_id": 8609425,
"answer_date": "2011-12-22T20:35:26.763Z",
"answer_score": 1481
} |
Please answer the following Stack Overflow question:
Title: How to get current time and date in Android
<p>How can I get the current time and date in an Android app?</p> | <p>You could use:</p>
<pre><code>import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();
</code></pre>
<p>There are plenty of constants in Calendar for everything you need.</p>
<p>Check the <a href="http://developer.android.com/reference/java/util/Calendar.html" rel="noreferrer">Calendar class documentation</a>.</p> | {
"question_id": 5369682,
"question_date": "2011-03-20T16:12:25.657Z",
"question_score": 1257,
"tags": "android|date|time",
"answer_id": 5369753,
"answer_date": "2011-03-20T16:27:31.343Z",
"answer_score": 1480
} |
Please answer the following Stack Overflow question:
Title: Sort ArrayList of custom Objects by property
<p>I read about sorting ArrayLists using a Comparator but in all of the examples people used <code>compareTo</code> which according to some research is a method for Strings.</p>
<p>I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(<code>getStartDay()</code>). Normally I compare them by <code>item1.getStartDate().before(item2.getStartDate())</code> so I was wondering whether I could write something like:</p>
<pre><code>public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}
public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);
...
}
</code></pre> | <p>Since <a href="//docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer"><code>Date</code></a> implements <a href="//docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html" rel="noreferrer"><code>Comparable</code></a>, it has a <code>compareTo</code> method just like <code>String</code> does.</p>
<p>So your custom <a href="//docs.oracle.com/javase/8/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> could look like this:</p>
<pre><code>public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}
</code></pre>
<p>The <code>compare()</code> method must return an <code>int</code>, so you couldn't directly return a <code>boolean</code> like you were planning to anyway.</p>
<p>Your sorting code would be just about like you wrote:</p>
<pre><code>Collections.sort(Database.arrayList, new CustomComparator());
</code></pre>
<p>A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:</p>
<pre><code>Collections.sort(Database.arrayList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
</code></pre>
<hr />
<h1>Since <a href="/questions/tagged/java-8" class="post-tag" title="show questions tagged 'java-8'" rel="tag">java-8</a></h1>
<p>You can now write the last example in a shorter form by using a <a href="//docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="noreferrer">lambda expression</a> for the <code>Comparator</code>:</p>
<pre><code>Collections.sort(Database.arrayList,
(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
</code></pre>
<p>And <code>List</code> has a <a href="//docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-" rel="noreferrer"><code>sort(Comparator)</code></a> method, so you can shorten this even further:</p>
<pre><code>Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
</code></pre>
<p>This is such a common idiom that there's <a href="//docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function-" rel="noreferrer">a built-in method</a> to generate a <code>Comparator</code> for a class with a <code>Comparable</code> key:</p>
<pre><code>Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
</code></pre>
<p>All of these are equivalent forms.</p> | {
"question_id": 2784514,
"question_date": "2010-05-06T21:09:36.060Z",
"question_score": 1256,
"tags": "java|sorting|date|comparator",
"answer_id": 2784576,
"answer_date": "2010-05-06T21:18:23.063Z",
"answer_score": 1690
} |
Please answer the following Stack Overflow question:
Title: Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing
<p>I had an interesting job interview experience a while back. The question started really easy:</p>
<blockquote>
<p><strong>Q1</strong>: We have a bag containing numbers <code>1</code>, <code>2</code>, <code>3</code>, …, <code>100</code>. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of the bag. Find the missing number.</p>
</blockquote>
<p>I've heard this interview question before, of course, so I very quickly answered along the lines of:</p>
<blockquote>
<p><strong>A1</strong>: Well, the sum of the numbers <code>1 + 2 + 3 + … + N</code> is <code>(N+1)(N/2)</code> (see <a href="http://en.wikipedia.org/wiki/Arithmetic_sum#Sum" rel="noreferrer">Wikipedia: sum of arithmetic series</a>). For <code>N = 100</code>, the sum is <code>5050</code>.</p>
<p>Thus, if all numbers are present in the bag, the sum will be exactly <code>5050</code>. Since one number is missing, the sum will be less than this, and the difference is that number. So we can find that missing number in <code>O(N)</code> time and <code>O(1)</code> space.</p>
</blockquote>
<p>At this point I thought I had done well, but all of a sudden the question took an unexpected turn:</p>
<blockquote>
<p><strong>Q2</strong>: That is correct, but now how would you do this if <em>TWO</em> numbers are missing?</p>
</blockquote>
<p>I had never seen/heard/considered this variation before, so I panicked and couldn't answer the question. The interviewer insisted on knowing my thought process, so I mentioned that perhaps we can get more information by comparing against the expected product, or perhaps doing a second pass after having gathered some information from the first pass, etc, but I really was just shooting in the dark rather than actually having a clear path to the solution.</p>
<p>The interviewer did try to encourage me by saying that having a second equation is indeed one way to solve the problem. At this point I was kind of upset (for not knowing the answer before hand), and asked if this is a general (read: "useful") programming technique, or if it's just a trick/gotcha answer.</p>
<p>The interviewer's answer surprised me: you can generalize the technique to find 3 missing numbers. In fact, you can generalize it to find <em>k</em> missing numbers.</p>
<blockquote>
<p><strong>Qk</strong>: If exactly <em>k</em> numbers are missing from the bag, how would you find it efficiently?</p>
</blockquote>
<p>This was a few months ago, and I still couldn't figure out what this technique is. Obviously there's a <code>Ω(N)</code> time lower bound since we must scan all the numbers at least once, but the interviewer insisted that the <em>TIME</em> and <em>SPACE</em> complexity of the solving technique (minus the <code>O(N)</code> time input scan) is defined in <em>k</em> not <em>N</em>.</p>
<p>So the question here is simple:</p>
<ul>
<li>How would you solve <strong>Q2</strong>?</li>
<li>How would you solve <strong>Q3</strong>?</li>
<li>How would you solve <strong>Qk</strong>?</li>
</ul>
<hr />
<h3>Clarifications</h3>
<ul>
<li>Generally there are <em>N</em> numbers from 1..<em>N</em>, not just 1..100.</li>
<li>I'm not looking for the obvious set-based solution, e.g. using a <a href="http://en.wikipedia.org/wiki/Bit_array" rel="noreferrer">bit set</a>, encoding the presence/absence each number by the value of a designated bit, therefore using <code>O(N)</code> bits in additional space. We can't afford any additional space proportional to <em>N</em>.</li>
<li>I'm also not looking for the obvious sort-first approach. This and the set-based approach are worth mentioning in an interview (they are easy to implement, and depending on <em>N</em>, can be very practical). I'm looking for the Holy Grail solution (which may or may not be practical to implement, but has the desired asymptotic characteristics nevertheless).</li>
</ul>
<p>So again, of course you must scan the input in <code>O(N)</code>, but you can only capture small amount of information (defined in terms of <em>k</em> not <em>N</em>), and must then find the <em>k</em> missing numbers somehow.</p> | <p>Here's a summary of <a href="https://stackoverflow.com/questions/3492302/easy-interview-question-got-harder-given-numbers-1-100-find-the-missing-number/3492664#3492664">Dimitris Andreou's</a> <a href="http://books.google.com/books?id=415loiMd_c0C&lpg=PP1&dq=muthukrishnan%20data%20stream%20algorithms&hl=el&pg=PA1#v=onepage&q=muthukrishnan%20data%20stream%20algorithms&f=false" rel="noreferrer">link</a>.</p>
<p>Remember sum of i-th powers, where i=1,2,..,k. This reduces the problem to solving the system of equations</p>
<p>a<sub>1</sub> + a<sub>2</sub> + ... + a<sub>k</sub> = b<sub>1</sub></p>
<p>a<sub>1</sub><sup>2</sup> + a<sub>2</sub><sup>2</sup> + ... + a<sub>k</sub><sup>2</sup> = b<sub>2</sub></p>
<p>...</p>
<p>a<sub>1</sub><sup>k</sup> + a<sub>2</sub><sup>k</sup> + ... + a<sub>k</sub><sup>k</sup> = b<sub>k</sub></p>
<p>Using <a href="https://en.wikipedia.org/wiki/Newton_identities#Formulation_in_terms_of_symmetric_polynomials" rel="noreferrer">Newton's identities</a>, knowing b<sub>i</sub> allows to compute</p>
<p>c<sub>1</sub> = a<sub>1</sub> + a<sub>2</sub> + ... a<sub>k</sub></p>
<p>c<sub>2</sub> = a<sub>1</sub>a<sub>2</sub> + a<sub>1</sub>a<sub>3</sub> + ... + a<sub>k-1</sub>a<sub>k</sub></p>
<p>...</p>
<p>c<sub>k</sub> = a<sub>1</sub>a<sub>2</sub> ... a<sub>k</sub></p>
<p>If you expand the polynomial (x-a<sub>1</sub>)...(x-a<sub>k</sub>) the coefficients will be exactly c<sub>1</sub>, ..., c<sub>k</sub> - see <a href="https://en.wikipedia.org/wiki/Vi%C3%A8te's_formulas" rel="noreferrer">Viète's formulas</a>. Since every polynomial factors uniquely (ring of polynomials is an <a href="https://en.wikipedia.org/wiki/Euclidean_domain" rel="noreferrer">Euclidean domain</a>), this means a<sub>i</sub> are uniquely determined, up to permutation.</p>
<p>This ends a proof that remembering powers is enough to recover the numbers. For constant k, this is a good approach.</p>
<p>However, when k is varying, the direct approach of computing c<sub>1</sub>,...,c<sub>k</sub> is prohibitely expensive, since e.g. c<sub>k</sub> is the product of all missing numbers, magnitude n!/(n-k)!. To overcome this, perform <a href="https://en.wikipedia.org/wiki/Finite_field_arithmetic" rel="noreferrer">computations in Z<sub>q</sub> field</a>, where q is a prime such that n <= q < 2n - it exists by <a href="https://en.wikipedia.org/wiki/Bertrand's_postulate" rel="noreferrer">Bertrand's postulate</a>. The proof doesn't need to be changed, since the formulas still hold, and factorization of polynomials is still unique. You also need an algorithm for factorization over finite fields, for example the one by <a href="https://en.wikipedia.org/wiki/Berlekamp's_algorithm" rel="noreferrer">Berlekamp</a> or <a href="https://en.wikipedia.org/wiki/Cantor%E2%80%93Zassenhaus_algorithm" rel="noreferrer">Cantor-Zassenhaus</a>.</p>
<p>High level pseudocode for constant k:</p>
<ul>
<li>Compute i-th powers of given numbers</li>
<li>Subtract to get sums of i-th powers of unknown numbers. Call the sums b<sub>i</sub>.</li>
<li>Use Newton's identities to compute coefficients from b<sub>i</sub>; call them c<sub>i</sub>. Basically, c<sub>1</sub> = b<sub>1</sub>; c<sub>2</sub> = (c<sub>1</sub>b<sub>1</sub> - b<sub>2</sub>)/2; see Wikipedia for exact formulas</li>
<li>Factor the polynomial x<sup>k</sup>-c<sub>1</sub>x<sup>k-1</sup> + ... + c<sub>k</sub>.</li>
<li>The roots of the polynomial are the needed numbers a<sub>1</sub>, ..., a<sub>k</sub>.</li>
</ul>
<p>For varying k, find a prime n <= q < 2n using e.g. Miller-Rabin, and perform the steps with all numbers reduced modulo q.</p>
<p>EDIT: The previous version of this answer stated that instead of Z<sub>q</sub>, where q is prime, it is possible to use a finite field of characteristic 2 (q=2^(log n)). This is not the case, since Newton's formulas require division by numbers up to k.</p> | {
"question_id": 3492302,
"question_date": "2010-08-16T10:26:58.180Z",
"question_score": 1256,
"tags": "arrays|algorithm|math",
"answer_id": 3492967,
"answer_date": "2010-08-16T12:13:14.393Z",
"answer_score": 633
} |
Please answer the following Stack Overflow question:
Title: How to write a:hover in inline CSS?
<p>I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.</p>
<p>How can I use <code>a:hover</code> in inline CSS inside the HTML style attribute?</p>
<p>E.g. you can't reliably use CSS classes in HTML emails.</p> | <p>Short answer: you can't.</p>
<p>Long answer: you shouldn't. </p>
<p>Give it a class name or an id and use stylesheets to apply the style.</p>
<p><code>:hover</code> is a pseudo-selector and, for <a href="http://en.wikipedia.org/wiki/Cascading_Style_Sheets" rel="noreferrer">CSS</a>, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria). </p>
<p>Response to the OP's comments:</p>
<p>See <em><a href="https://web.archive.org/web/20160104183713/http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript" rel="noreferrer">Totally Pwn CSS with Javascript</a></em> for a good script on adding CSS rules dynamically. Also see <em><a href="http://www.quirksmode.org/dom/changess.html" rel="noreferrer">Change style sheet</a></em> for some of the theory on the subject.</p>
<p>Also, don't forget, you can add links to external stylesheets if that's an option. For example,</p>
<pre><code><script type="text/javascript">
var link = document.createElement("link");
link.setAttribute("rel","stylesheet");
link.setAttribute("href","http://wherever.com/yourstylesheet.css");
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
</script>
</code></pre>
<p>Caution: the above assumes there is a <a href="https://en.wikipedia.org/wiki/HTML_element#Document_structure_elements" rel="noreferrer">head</a> section. </p> | {
"question_id": 1033156,
"question_date": "2009-06-23T15:07:28.823Z",
"question_score": 1255,
"tags": "html|css|inline-styles",
"answer_id": 1033166,
"answer_date": "2009-06-23T15:09:04.513Z",
"answer_score": 685
} |
Please answer the following Stack Overflow question:
Title: How does the @property decorator work in Python?
<p>I would like to understand how the built-in function <code>property</code> works. What confuses me is that <code>property</code> can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.</p>
<p>This example is from the <a href="http://docs.python.org/3/library/functions.html#property" rel="noreferrer">documentation</a>:</p>
<pre><code>class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
</code></pre>
<p><code>property</code>'s arguments are <code>getx</code>, <code>setx</code>, <code>delx</code> and a doc string.</p>
<p>In the code below <code>property</code> is used as a decorator. The object of it is the <code>x</code> function, but in the code above there is no place for an object function in the arguments.</p>
<pre><code>class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
</code></pre>
<p>How are the <code>x.setter</code> and <code>x.deleter</code> decorators created in this case?</p> | <p>The <code>property()</code> function returns a special <a href="https://docs.python.org/howto/descriptor.html" rel="noreferrer">descriptor object</a>:</p>
<pre class="lang-python prettyprint-override"><code>>>> property()
<property object at 0x10ff07940>
</code></pre>
<p>It is this object that has <em>extra</em> methods:</p>
<pre><code>>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>
</code></pre>
<p>These act as decorators <em>too</em>. They return a new property object:</p>
<pre><code>>>> property().getter(None)
<property object at 0x10ff079f0>
</code></pre>
<p>that is a copy of the old object, but with one of the functions replaced.</p>
<p>Remember, that the <code>@decorator</code> syntax is just syntactic sugar; the syntax:</p>
<pre><code>@property
def foo(self): return self._foo
</code></pre>
<p>really means the same thing as</p>
<pre><code>def foo(self): return self._foo
foo = property(foo)
</code></pre>
<p>so <code>foo</code> the function is replaced by <code>property(foo)</code>, which we saw above is a special object. Then when you use <code>@foo.setter()</code>, what you are doing is call that <code>property().setter</code> method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.</p>
<p>The following sequence also creates a full-on property, by using those decorator methods.</p>
<p>First we create some functions and a <code>property</code> object with just a getter:</p>
<pre><code>>>> def getter(self): print('Get!')
...
>>> def setter(self, value): print('Set to {!r}!'.format(value))
...
>>> def deleter(self): print('Delete!')
...
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True
</code></pre>
<p>Next we use the <code>.setter()</code> method to add a setter:</p>
<pre><code>>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True
</code></pre>
<p>Last we add a deleter with the <code>.deleter()</code> method:</p>
<pre><code>>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True
</code></pre>
<p>Last but not least, the <code>property</code> object acts as a <a href="https://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="noreferrer">descriptor object</a>, so it has <a href="https://docs.python.org/reference/datamodel.html#object.__get__" rel="noreferrer"><code>.__get__()</code></a>, <a href="http://docs.python.org/reference/datamodel.html#object.__set__" rel="noreferrer"><code>.__set__()</code></a> and <a href="http://docs.python.org/reference/datamodel.html#object.__delete__" rel="noreferrer"><code>.__delete__()</code></a> methods to hook into instance attribute getting, setting and deleting:</p>
<pre><code>>>> class Foo: pass
...
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!
</code></pre>
<p>The Descriptor Howto includes a <a href="http://docs.python.org/howto/descriptor.html#properties" rel="noreferrer">pure Python sample implementation</a> of the <code>property()</code> type:</p>
<blockquote>
<pre><code>class Property:
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
</code></pre>
</blockquote> | {
"question_id": 17330160,
"question_date": "2013-06-26T20:47:15.163Z",
"question_score": 1255,
"tags": "python|properties|decorator|python-decorators|python-internals",
"answer_id": 17330273,
"answer_date": "2013-06-26T20:54:27.500Z",
"answer_score": 1214
} |
Please answer the following Stack Overflow question:
Title: How do I limit the number of rows returned by an Oracle query after ordering?
<p>Is there a way to make an <code>Oracle</code> query behave like it contains a MySQL <code>limit</code> clause?</p>
<p>In MySQL, I can do this:</p>
<pre><code>select *
from sometable
order by name
limit 20,10
</code></pre>
<p>to get the 21st to the 30th rows (skip the first 20, give the next 10). The rows are selected after the <code>order by</code>, so it really starts on the 20th name alphabetically.</p>
<p>In Oracle, the only thing people mention is the <code>rownum</code> pseudo-column, but it is evaluated <em>before</em> <code>order by</code>, which means this:</p>
<pre><code>select *
from sometable
where rownum <= 10
order by name
</code></pre>
<p>will return a random set of ten rows ordered by name, which is not usually what I want. It also doesn't allow for specifying an offset.</p> | <p>You can use a subquery for this like</p>
<pre><code>select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
</code></pre>
<p>Have also a look at the topic <a href="https://blogs.oracle.com/oraclemagazine/post/on-rownum-and-limiting-results" rel="noreferrer">On ROWNUM and limiting results</a> at Oracle/AskTom for more information.</p>
<p><strong>Update</strong>:
To limit the result with both lower and upper bounds things get a bit more bloated with</p>
<pre><code>select * from
( select a.*, ROWNUM rnum from
( <your_query_goes_here, with order by> ) a
where ROWNUM <= :MAX_ROW_TO_FETCH )
where rnum >= :MIN_ROW_TO_FETCH;
</code></pre>
<p>(Copied from specified AskTom-article)</p>
<p><strong>Update 2</strong>:
Starting with Oracle 12c (12.1) there is a syntax available to limit rows or start at offsets.</p>
<pre><code>SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
</code></pre>
<p>See <a href="https://stackoverflow.com/a/26051830/57601">this answer</a> for more examples. Thanks to Krumia for the hint.</p> | {
"question_id": 470542,
"question_date": "2009-01-22T19:48:43.930Z",
"question_score": 1254,
"tags": "sql|oracle|pagination|sql-limit",
"answer_id": 470571,
"answer_date": "2009-01-22T19:55:58.797Z",
"answer_score": 908
} |
Please answer the following Stack Overflow question:
Title: What is a race condition?
<p>When writing multithreaded applications, one of the most common problems experienced is race conditions.</p>
<p>My questions to the community are:</p>
<ul>
<li>What is the race condition?</li>
<li>How do you detect them?</li>
<li>How do you handle them?</li>
<li>Finally, how do you prevent them from occurring?</li>
</ul> | <p>A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. </p>
<p>Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:</p>
<pre><code>if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
// y will not be equal to 10.
}
</code></pre>
<p>The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.</p>
<p>In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:</p>
<pre><code>// Obtain lock for x
if (x == 5)
{
y = x * 2; // Now, nothing can change x until the lock is released.
// Therefore y = 10
}
// release lock for x
</code></pre> | {
"question_id": 34510,
"question_date": "2008-08-29T15:55:10.457Z",
"question_score": 1253,
"tags": "multithreading|concurrency|terminology|race-condition",
"answer_id": 34550,
"answer_date": "2008-08-29T16:05:23.100Z",
"answer_score": 1565
} |
Please answer the following Stack Overflow question:
Title: How can I disable the UITableView selection?
<p>When you tap a row in a <code>UITableView</code>, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?</p> | <p>For me, the following worked fine:</p>
<pre><code>tableView.allowsSelection = false
</code></pre>
<p>This means <code>didSelectRowAt#</code> simply won't work. That is to say, touching a row of the table, as such, will do absolutely nothing. (And hence, obviously, there will never be a selected-animation.)</p>
<p>(Note that if, on the cells, you have <code>UIButton</code> or any other controls, of course those controls will still work. Any controls you happen to have on the table cell, are totally unrelated to UITableView's ability to allow you to "select a row" using <code>didSelectRowAt#</code>.)</p>
<p>Another point to note is that: This doesn't work when the <code>UITableView</code> is in editing mode. To restrict cell selection in editing mode use the code as below:</p>
<pre><code>tableView.allowsSelectionDuringEditing = false
</code></pre> | {
"question_id": 190908,
"question_date": "2008-10-10T11:32:27.833Z",
"question_score": 1253,
"tags": "ios|uitableview|cocoa-touch",
"answer_id": 1166670,
"answer_date": "2009-07-22T16:56:19.283Z",
"answer_score": 648
} |
Please answer the following Stack Overflow question:
Title: How to merge a specific commit in Git
<p>I have forked a branch from a repository in GitHub and committed something specific to me. Now I found the original repository had a good feature which was at <code>HEAD</code>.</p>
<p>I want to merge it only without previous commits. What should I do? I know how to merge all commits:</p>
<pre><code>git branch -b a-good-feature
git pull repository master
git checkout master
git merge a-good-feature
git commit -a
git push
</code></pre> | <p>'<a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer"><code>git cherry-pick</code></a>' should be your answer here.</p>
<blockquote>
<p>Apply the change introduced by an existing commit. </p>
</blockquote>
<p>Do not forget to read <a href="https://stackoverflow.com/users/36723/bdonlan">bdonlan</a>'s answer about the consequence of cherry-picking in this post:<br>
<a href="https://stackoverflow.com/questions/880957/pull-all-commits-from-a-branch-push-specified-commits-to-another/881014#881014">"Pull all commits from a branch, push specified commits to another"</a>, where:</p>
<pre><code>A-----B------C
\
\
D
</code></pre>
<p>becomes:</p>
<pre><code>A-----B------C
\
\
D-----C'
</code></pre>
<blockquote>
<p>The problem with this commit is that git considers commits to include all history before them</p>
<p>Where C' has a different <code>SHA-1</code> ID.<br>
Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.</p>
<p>This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).<br>
More importantly though, <strong>it ignores functional dependencies - if C actually used a function defined in B, you'll never know</strong>.</p>
</blockquote> | {
"question_id": 881092,
"question_date": "2009-05-19T05:27:34.407Z",
"question_score": 1251,
"tags": "git|merge",
"answer_id": 881112,
"answer_date": "2009-05-19T05:35:40.607Z",
"answer_score": 1360
} |
Please answer the following Stack Overflow question:
Title: What do Clustered and Non-Clustered index actually mean?
<p>I have a limited exposure to DB and have only used DB as an application programmer. I want to know about <code>Clustered</code> and <code>Non clustered indexes</code>.
I googled and what I found was :</p>
<blockquote>
<p><em>A clustered index is a special type of index that reorders the way
records in the table are physically
stored. Therefore table can have only
one clustered index. The leaf nodes
of a clustered index contain the data
pages. A nonclustered index is a
special type of index in which the
logical order of the index does not
match the physical stored order of
the rows on disk. The leaf node of a
nonclustered index does not consist of
the data pages. Instead, the leaf
nodes contain index rows.</em></p>
</blockquote>
<p>What I found in SO was <a href="https://stackoverflow.com/questions/91688/what-are-the-differencespros-cons-between-clustered-and-non-clustered-indexes">What are the differences between a clustered and a non-clustered index?</a>.</p>
<p>Can someone explain this in plain English?</p> | <p>With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.</p>
<p>With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records. </p>
<p>It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.</p>
<p>Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.</p> | {
"question_id": 1251636,
"question_date": "2009-08-09T15:59:41.927Z",
"question_score": 1251,
"tags": "sql-server|performance|indexing|clustered-index|non-clustered-index",
"answer_id": 1251652,
"answer_date": "2009-08-09T16:05:40.293Z",
"answer_score": 1258
} |
Please answer the following Stack Overflow question:
Title: What's the difference between a mock & stub?
<p>I've read various articles about mocking vs stubbing in testing, including <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Martin Fowler's Mocks Aren't Stubs</a>, but still don't understand the difference.</p> | <p><strong>Stub</strong></p>
<p>I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the dependency (abstract class or interface most likely) you are faking for testing purposes and the methods would just be stubbed out with set responses. They would not do anything fancy and you would have already written the stubbed code for it outside of your test.</p>
<p><strong>Mock</strong></p>
<p>A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.</p>
<p><strong>Difference between Mocks and Stubs</strong></p>
<p>Tests written with mocks usually follow an <code>initialize -> set expectations -> exercise -> verify</code> pattern to testing. While the pre-written stub would follow an <code>initialize -> exercise -> verify</code>. </p>
<p><strong>Similarity between Mocks and Stubs</strong></p>
<p>The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.</p> | {
"question_id": 3459287,
"question_date": "2010-08-11T14:19:57.170Z",
"question_score": 1251,
"tags": "testing|mocking|stub",
"answer_id": 3459491,
"answer_date": "2010-08-11T14:38:08.387Z",
"answer_score": 887
} |
Please answer the following Stack Overflow question:
Title: How do I escape a single quote in SQL Server?
<p>I am trying to <code>insert</code> some text data into a table in SQL Server 9.</p>
<p>The text includes a single quote <code>'</code>.</p>
<p>How do I escape that?</p>
<p>I tried using two single quotes, but it threw me some errors.</p>
<p>eg. <code>insert into my_table values('hi, my name''s tim.');</code></p> | <p><strong>Single quotes are escaped by doubling them up</strong>, just as you've shown us in your example. The following SQL illustrates this functionality. I tested it on SQL Server 2008:</p>
<pre><code>DECLARE @my_table TABLE (
[value] VARCHAR(200)
)
INSERT INTO @my_table VALUES ('hi, my name''s tim.')
SELECT * FROM @my_table
</code></pre>
<h3>Results</h3>
<pre><code>value
==================
hi, my name's tim.
</code></pre> | {
"question_id": 1586560,
"question_date": "2009-10-19T01:18:22.493Z",
"question_score": 1250,
"tags": "sql|sql-server|tsql|delimiter|single-quotes",
"answer_id": 1586588,
"answer_date": "2009-10-19T01:30:51.833Z",
"answer_score": 1804
} |
Please answer the following Stack Overflow question:
Title: What's the difference between utf8_general_ci and utf8_unicode_ci?
<p>Between <code>utf8_general_ci</code> and <code>utf8_unicode_ci</code>, are there any differences in terms of performance?</p> | <p><strong>For those people still arriving at this question in 2020 or later, there are newer options that may be better than <em>both</em> of these. For example, <code>utf8_unicode_520_ci</code>.</strong></p>
<p>All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.</p>
<p><code>_unicode_ci</code> and <code>_general_ci</code> are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as <code>_unicode_520_ci</code> for equivalent rules based on Unicode 5.2, or the MySQL 8.x specific <code>_0900_ai_ci</code> for equivalent rules based on Unicode 9.0 (and with no equivalent <code>_general_ci</code> variant). People reading this now should probably use one of these newer collations instead of either <code>_unicode_ci</code> or <code>_general_ci</code>. The description of those older collations below is provided for interest only.</p>
<p><em>MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use <code>utf8mb4</code> instead of <code>utf8</code> for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.</em></p>
<p><strong>Key differences</strong></p>
<ul>
<li><p><code>utf8mb4_unicode_ci</code> is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.</p>
</li>
<li><p><code>utf8mb4_general_ci</code> is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.</p>
<p>On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.</p>
</li>
</ul>
<p><strong>Benefits of <code>utf8mb4_unicode_ci</code> over <code>utf8mb4_general_ci</code></strong></p>
<p><code>utf8mb4_unicode_ci</code>, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.</p>
<p>As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified <code>utf8mb4_general_ci</code> sorting in MySQL, but there are still a few differences:</p>
<ul>
<li><p>For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas <code>utf8mb4_general_ci</code> sorts them as single characters (presumably like "s" and "e" respectively).</p>
</li>
<li><p>Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. <code>utf8mb4_unicode_ci</code> handles these properly.</p>
</li>
</ul>
<p>In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot <em>more</em> differences between Unicode sorting and the simplified <code>utf8mb4_general_ci</code> sorting. The suitability of <code>utf8mb4_general_ci</code> will depend heavily on the language used. For some languages, it'll be quite inadequate.</p>
<p><strong>What should you use?</strong></p>
<p>There is almost certainly no reason to use <code>utf8mb4_general_ci</code> anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.</p>
<p>In the past, some people recommended to use <code>utf8mb4_general_ci</code> except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.</p>
<p>There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, <code>utf8mb4_general_ci</code> is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.</p>
<p>One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.</p>
<p><strong>What the parts mean</strong></p>
<p>Firstly, <code>ci</code> is for <em>case-insensitive</em> sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are <code>cs</code> (case-sensitive) for textual data where case is important, and <code>bin</code>, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.</p>
<p>Next, <code>unicode</code> or <code>general</code> refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with <code>unicode</code> and <code>general</code> being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that <code>unicode</code> uses rules from Unicode 4.0. Recent versions of MySQL and MariaDB add the rulesets <code>unicode_520</code> using rules from Unicode 5.2, and MySQL 8.x adds <code>0900</code> (dropping the "unicode_" part) using rules from Unicode 9.0.</p>
<p>And lastly, <code>utf8mb4</code> is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.</p> | {
"question_id": 766809,
"question_date": "2009-04-20T03:43:49.213Z",
"question_score": 1248,
"tags": "mysql|unicode|utf-8|collation|character-set",
"answer_id": 766996,
"answer_date": "2009-04-20T05:19:47.703Z",
"answer_score": 1886
} |
Please answer the following Stack Overflow question:
Title: What is "Linting"?
<p><strong>PHPLint</strong>, <strong>JSLint</strong>, and I recently came across "you can lint your <strong>JS</strong> code on the fly" while reading something about some <em>IDE</em>.</p>
<p>So, what <em>is</em> "linting"?</p> | <p>Linting is the process of running a program that will analyse code for potential errors.</p>
<p>See <a href="http://en.wikipedia.org/wiki/Lint_%28software%29" rel="noreferrer">lint</a> on wikipedia:</p>
<blockquote>
<p>lint was the name originally given to a particular program that flagged some suspicious and non-portable constructs (likely to be bugs) in C language source code. The term is now applied generically to tools that flag suspicious usage in software written in any computer language.</p>
</blockquote> | {
"question_id": 8503559,
"question_date": "2011-12-14T11:14:43.227Z",
"question_score": 1248,
"tags": "lint|gjslint",
"answer_id": 8503586,
"answer_date": "2011-12-14T11:16:28.393Z",
"answer_score": 1210
} |
Please answer the following Stack Overflow question:
Title: GitHub relative link in Markdown file
<p>Is there a way to create a URL anchor, <code><a></code>, link from within a Markdown file, to another file within the same repository and branch (aka a link relative to the current branch)?</p>
<p>For example, in the master branch I have a README.md file, which I would like do something like:</p>
<pre><code># My Project
is really really cool. My Project has a subdir named myLib, see below.
## myLib documentation
see documentation [here](myLib/README.md)
</code></pre>
<p>This would allow me to link from one .md to another within the same branch and not have to worry about which branch I'm in (avoid having to do an absolute URL that includes the github.com branch name).</p>
<p>Here is a working example of what I mean:</p>
<ol>
<li>GOTO <a href="http://github.com/rynop/testRel">http://github.com/rynop/testRel</a>, link does not work.</li>
<li>GOTO <a href="http://github.com/rynop/testRel/blob/master/README.md">http://github.com/rynop/testRel/blob/master/README.md</a>, link works.</li>
</ol>
<p>This is expected because at this point the starting URL is in the branch. Now how do I get it to pick up the current branch in the README.md at the root of the repository?</p>
<p><strong>Update</strong>: I opened an <a href="https://github.com/github/markup/issues/84">issue</a> against GitHub for this feature request.</p> | <p>Update <strong>30th, January 2013</strong>, 16 months later:</p>
<h2><a href="https://github.com/blog/1395-relative-links-in-markup-files" rel="noreferrer">GitHub Blog Post <strong>Relative links in markup files</strong></a>:</h2>
<blockquote>
<p>Starting today, <strong>GitHub supports relative links in markup files</strong>.<br />
Now you can link directly between different documentation files, whether you view the documentation on GitHub itself, or locally, using a different markup renderer.</p>
<p>You want examples of link definitions and how they work? Here's some Markdown for you.<br />
Instead of an absolute link:</p>
<pre><code>[a link](https://github.com/user/repo/blob/branch/other_file.md)
</code></pre>
<p>…you can use a relative link:</p>
<pre><code>[a relative link](other_file.md)
[a relative link](path%20with%20spaces/other_file.md)
</code></pre>
<p>and we'll make sure it gets linked to <code>user/repo/blob/branch/other_file.md</code>.</p>
<p>If you were using a workaround like <code>[a workaround link](repo/blob/master/other_file.md)</code>, you'll have to update your documentation to use the new syntax.</p>
<p>This also means <strong>your documentation can now easily stand on its own, without always pointing to GitHub</strong>.</p>
</blockquote>
<p><a href="https://stackoverflow.com/users/4288506/marcono1234">Marcono1234</a> adds in <a href="https://stackoverflow.com/questions/7653483/github-relative-link-in-markdown-file/7658676#comment121919252_7658676">the comments</a></p>
<blockquote>
<p>Also useful: When the link starts with a <code>/</code>, it is relative to the root of the repository (regardless of whether the markdown file is nested in subdirectories)</p>
</blockquote>
<hr />
<p>Update December 20th, 2011:</p>
<p>The <a href="https://github.com/github/markup/issues/84#issuecomment-3223278" rel="noreferrer">GitHub markup issue 84</a> is currently closed by <a href="https://github.com/technoweenie" rel="noreferrer">technoweenie</a>, with the comment:</p>
<blockquote>
<p>We tried adding a <code><base></code> tag for this, but it causes problems with other relative links on the site.</p>
</blockquote>
<hr />
<p>October 12th, 2011:</p>
<p>If you look at the <strong><a href="https://raw.github.com/github/markup/master/README.md" rel="noreferrer">raw source of the <code>README.md</code></a></strong> of Markdown itself(!), relative paths don't seem to be supported.<br />
You will find references like:</p>
<pre><code>[r2h]: http://github.com/github/markup/tree/master/lib/github/commands/rest2html
[r2hc]: http://github.com/github/markup/tree/master/lib/github/markups.rb#L13
</code></pre>
<hr />
<p>As noted in <a href="https://stackoverflow.com/users/2229448/invisiblewolf">InvisibleWolf</a>'s <a href="https://stackoverflow.com/a/46189724/6309">answer</a>, if the target link is a directory and it has space, then you need to use <code>%20</code> for each space.</p> | {
"question_id": 7653483,
"question_date": "2011-10-04T20:12:23.047Z",
"question_score": 1247,
"tags": "github|markdown|github-flavored-markdown",
"answer_id": 7658676,
"answer_date": "2011-10-05T08:39:27.347Z",
"answer_score": 1461
} |
Please answer the following Stack Overflow question:
Title: How can I sanitize user input with PHP?
<p>Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?</p> | <p>It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called <a href="https://www.php.net/manual/en/security.magicquotes.php" rel="noreferrer">magic-quotes</a>, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).</p>
<p>What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.</p>
<p>Another example is HTML: If you embed strings within HTML markup, you must escape it with <a href="http://php.net/manual/function.htmlspecialchars.php" rel="noreferrer"><code>htmlspecialchars</code></a>. This means that every single <code>echo</code> or <code>print</code> statement should use <code>htmlspecialchars</code>.</p>
<p>A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with <a href="http://php.net/manual/function.exec.php" rel="noreferrer"><code>exec</code></a>, then you must use <a href="http://php.net/manual/function.escapeshellcmd.php" rel="noreferrer"><code>escapeshellcmd</code></a> and <a href="http://php.net/manual/function.escapeshellarg.php" rel="noreferrer"><code>escapeshellarg</code></a>.</p>
<p>Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, <a href="https://www.php.net/json_encode" rel="noreferrer"><code>json_encode()</code></a> that will correctly format every bit of data.</p>
<p>And so on and so forth ...</p>
<p>The <em>only</em> case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.</p> | {
"question_id": 129677,
"question_date": "2008-09-24T20:20:39.650Z",
"question_score": 1247,
"tags": "php|security|xss|sql-injection|user-input",
"answer_id": 130323,
"answer_date": "2008-09-24T22:30:37Z",
"answer_score": 1276
} |
Please answer the following Stack Overflow question:
Title: What's the difference between implementation, api and compile in Gradle?
<p>After updating to Android Studio 3.0 and creating a new project, I noticed that in <code>build.gradle</code> there is a new way to add new dependencies instead of <code>compile</code> there is <code>implementation</code> and instead of <code>testCompile</code> there is <code>testImplementation</code>.</p>
<p>Example:</p>
<pre><code> implementation 'com.android.support:appcompat-v7:25.0.0'
testImplementation 'junit:junit:4.12'
</code></pre>
<p>instead of</p>
<pre><code> compile 'com.android.support:appcompat-v7:25.0.0'
testCompile 'junit:junit:4.12'
</code></pre>
<p>What's the difference between them and what should I be using?</p> | <p><strong>tl;dr</strong></p>
<p>Just replace:</p>
<ul>
<li><code>compile</code> with <code>implementation</code> (if you don't need transitivity) or <code>api</code> (if you need transitivity)</li>
<li><code>testCompile</code> with <code>testImplementation</code></li>
<li><code>debugCompile</code> with <code>debugImplementation</code></li>
<li><code>androidTestCompile</code> with <code>androidTestImplementation</code></li>
<li><code>compileOnly</code> is still valid. It was added in 3.0 to replace provided and not compile. (<code>provided</code> introduced when Gradle didn't have a configuration name for that use-case and named it after Maven's provided scope.)</li>
</ul>
<p>It is one of the breaking changes coming with <a href="https://developer.android.com/studio/releases/gradle-plugin#3-0-0" rel="noreferrer">Android Gradle plugin 3.0</a> that Google <a href="https://youtu.be/7ll-rkLCtyk?t=22m20s" rel="noreferrer">announced at IO17</a>.</p>
<p>The <code>compile</code> configuration is <a href="https://youtu.be/7ll-rkLCtyk?t=29m18s" rel="noreferrer">now deprecated</a> and should be replaced by <code>implementation</code> or <code>api</code></p>
<p>From the <a href="https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation" rel="noreferrer">Gradle documentation</a>:</p>
<blockquote>
<pre><code>dependencies {
api 'commons-httpclient:commons-httpclient:3.1'
implementation 'org.apache.commons:commons-lang3:3.5'
}
</code></pre>
<p>Dependencies appearing in the <code>api</code> configurations will be
transitively exposed to consumers of the library, and as such will
appear on the compile classpath of consumers.</p>
<p>Dependencies found in the <code>implementation</code> configuration will, on the
other hand, not be exposed to consumers, and therefore not leak into
the consumers' compile classpath. This comes with several benefits:</p>
<ul>
<li>dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive
dependency</li>
<li>faster compilation thanks to reduced classpath size</li>
<li>less recompilations when implementation dependencies change: consumers would not need to be recompiled</li>
<li>cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that
distinguish exactly between what is required to compile against the
library and what is required to use the library at runtime (in other
words, don't mix what is needed to compile the library itself and what
is needed to compile against the library).</li>
</ul>
<p><strong>The compile configuration still exists, but should not be used as it will not offer the guarantees that the <code>api</code> and <code>implementation</code> configurations provide.</strong></p>
</blockquote>
<hr />
<p><strong>Note:</strong> if you are only using a library in your app module -the common case- you won't notice any difference.<br />
you will only see the difference if you have a complex project with modules depending on each other, or you are creating a library.</p> | {
"question_id": 44493378,
"question_date": "2017-06-12T07:13:13.100Z",
"question_score": 1246,
"tags": "gradle|build.gradle|dependency-management|gradle-plugin|transitive-dependency",
"answer_id": 44493379,
"answer_date": "2017-06-12T07:13:13.100Z",
"answer_score": 1481
} |
Please answer the following Stack Overflow question:
Title: How to sort an array of integers correctly
<p>Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)</code></pre>
</div>
</div>
</p>
<p>I'd expect this to show <code>99, 104, 140000</code>. Instead it shows <code>104, 140000, 99</code>. So it seems the sort is handling the values as strings.</p>
<p>Is there a way to get the sort function to actually sort on integer value?</p> | <p>By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);</code></pre>
</div>
</div>
</p>
<p>Documentation:</p>
<p>Mozilla <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" rel="nofollow noreferrer"><code>Array.prototype.sort()</code></a> recommends this compare function for arrays that don't contain Infinity or NaN. (Because <code>Infinity - Infinity</code> is NaN, not 0).</p>
<p>Also examples of sorting objects by key.</p> | {
"question_id": 1063007,
"question_date": "2009-06-30T10:43:11.510Z",
"question_score": 1245,
"tags": "javascript|arrays|sorting|numbers",
"answer_id": 1063027,
"answer_date": "2009-06-30T10:47:04.857Z",
"answer_score": 1813
} |
Please answer the following Stack Overflow question:
Title: What is a mixin and why is it useful?
<p>In <a href="https://rads.stackoverflow.com/amzn/click/com/0596009259" rel="noreferrer" rel="nofollow noreferrer"><em>Programming Python</em></a>, Mark Lutz mentions the term <em>mixin</em>. I am from a C/C++/C# background and I have not heard the term before. What is a mixin?</p>
<p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=programming+python+guimixin&source=bl&ots=HU833giXzH&sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&hl=en&ei=x8iRSaTTF5iq-ganpbGPCw&sa=X&oi=book_result&resnum=3&ct=result" rel="noreferrer">this example</a> (which I have linked to because it is quite long), I am presuming it is a case of using multiple inheritance to extend a class as opposed to proper subclassing. Is this right?</p>
<p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p>
<p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p> | <p>A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:</p>
<ol>
<li>You want to provide a lot of optional features for a class.</li>
<li>You want to use one particular feature in a lot of different classes.</li>
</ol>
<p>For an example of number one, consider <a href="http://werkzeug.pocoo.org/docs/wrappers/" rel="noreferrer">werkzeug's request and response system</a>. I can make a plain old request object by saying:</p>
<pre><code>from werkzeug import BaseRequest
class Request(BaseRequest):
pass
</code></pre>
<p>If I want to add accept header support, I would make that</p>
<pre><code>from werkzeug import BaseRequest, AcceptMixin
class Request(AcceptMixin, BaseRequest):
pass
</code></pre>
<p>If I wanted to make a request object that supports accept headers, etags, authentication, and user agent support, I could do this:</p>
<pre><code>from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin
class Request(AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin, BaseRequest):
pass
</code></pre>
<p>The difference is subtle, but in the above examples, the mixin classes weren't made to stand on their own. In more traditional multiple inheritance, the <code>AuthenticationMixin</code> (for example) would probably be something more like <code>Authenticator</code>. That is, the class would probably be designed to stand on its own.</p> | {
"question_id": 533631,
"question_date": "2009-02-10T18:50:42.337Z",
"question_score": 1245,
"tags": "python|oop|multiple-inheritance|mixins",
"answer_id": 547714,
"answer_date": "2009-02-13T21:15:17.283Z",
"answer_score": 905
} |
Please answer the following Stack Overflow question:
Title: Retrieving the last record in each group - MySQL
<p>There is a table <code>messages</code> that contains data as shown below:</p>
<pre><code>Id Name Other_Columns
-------------------------
1 A A_data_1
2 A A_data_2
3 A A_data_3
4 B B_data_1
5 B B_data_2
6 C C_data_1
</code></pre>
<p>If I run a query <code>select * from messages group by name</code>, I will get the result as:</p>
<pre><code>1 A A_data_1
4 B B_data_1
6 C C_data_1
</code></pre>
<p>What query will return the following result?</p>
<pre><code>3 A A_data_3
5 B B_data_2
6 C C_data_1
</code></pre>
<p>That is, the last record in each group should be returned.</p>
<p>At present, this is the query that I use:</p>
<pre><code>SELECT
*
FROM (SELECT
*
FROM messages
ORDER BY id DESC) AS x
GROUP BY name
</code></pre>
<p>But this looks highly inefficient. Any other ways to achieve the same result?</p> | <p>MySQL 8.0 now supports <a href="https://dev.mysql.com/doc/refman/8.0/en/window-functions.html" rel="noreferrer">windowing functions</a>, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries:</p>
<pre><code>WITH ranked_messages AS (
SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn
FROM messages AS m
)
SELECT * FROM ranked_messages WHERE rn = 1;
</code></pre>
<p>This and other approaches to finding <a href="https://dev.mysql.com/doc/refman/8.0/en/example-maximum-column-group-row.html" rel="noreferrer">groupwise maximal rows</a> are illustrated in the MySQL manual.</p>
<p>Below is the original answer I wrote for this question in 2009:</p>
<hr />
<p>I write the solution this way:</p>
<pre><code>SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL;
</code></pre>
<p>Regarding performance, one solution or the other can be better, depending on the nature of your data. So you should test both queries and use the one that is better at performance given your database.</p>
<p>For example, I have a copy of the <a href="https://archive.org/details/stackexchange" rel="noreferrer">StackOverflow August data dump</a>. I'll use that for benchmarking. There are 1,114,357 rows in the <code>Posts</code> table. This is running on <a href="https://www.mysql.com/" rel="noreferrer">MySQL</a> 5.0.75 on my Macbook Pro 2.40GHz.</p>
<p>I'll write a query to find the most recent post for a given user ID (mine).</p>
<p><strong>First using the technique <a href="https://stackoverflow.com/questions/1313120/sql-retrieving-the-last-record-in-each-group/1313140#1313140">shown</a> by @Eric with the <code>GROUP BY</code> in a subquery:</strong></p>
<pre><code>SELECT p1.postid
FROM Posts p1
INNER JOIN (SELECT pi.owneruserid, MAX(pi.postid) AS maxpostid
FROM Posts pi GROUP BY pi.owneruserid) p2
ON (p1.postid = p2.maxpostid)
WHERE p1.owneruserid = 20860;
1 row in set (1 min 17.89 sec)
</code></pre>
<p>Even the <a href="https://dev.mysql.com/doc/refman/5.7/en/using-explain.html" rel="noreferrer"><code>EXPLAIN</code> analysis</a> takes over 16 seconds:</p>
<pre><code>+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 76756 | |
| 1 | PRIMARY | p1 | eq_ref | PRIMARY,PostId,OwnerUserId | PRIMARY | 8 | p2.maxpostid | 1 | Using where |
| 2 | DERIVED | pi | index | NULL | OwnerUserId | 8 | NULL | 1151268 | Using index |
+----+-------------+------------+--------+----------------------------+-------------+---------+--------------+---------+-------------+
3 rows in set (16.09 sec)
</code></pre>
<p><strong>Now produce the same query result using <a href="https://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column/123481#123481">my technique</a> with <code>LEFT JOIN</code>:</strong></p>
<pre><code>SELECT p1.postid
FROM Posts p1 LEFT JOIN posts p2
ON (p1.owneruserid = p2.owneruserid AND p1.postid < p2.postid)
WHERE p2.postid IS NULL AND p1.owneruserid = 20860;
1 row in set (0.28 sec)
</code></pre>
<p>The <code>EXPLAIN</code> analysis shows that both tables are able to use their indexes:</p>
<pre><code>+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
| 1 | SIMPLE | p1 | ref | OwnerUserId | OwnerUserId | 8 | const | 1384 | Using index |
| 1 | SIMPLE | p2 | ref | PRIMARY,PostId,OwnerUserId | OwnerUserId | 8 | const | 1384 | Using where; Using index; Not exists |
+----+-------------+-------+------+----------------------------+-------------+---------+-------+------+--------------------------------------+
2 rows in set (0.00 sec)
</code></pre>
<hr />
<p>Here's the DDL for my <code>Posts</code> table:</p>
<pre><code>CREATE TABLE `posts` (
`PostId` bigint(20) unsigned NOT NULL auto_increment,
`PostTypeId` bigint(20) unsigned NOT NULL,
`AcceptedAnswerId` bigint(20) unsigned default NULL,
`ParentId` bigint(20) unsigned default NULL,
`CreationDate` datetime NOT NULL,
`Score` int(11) NOT NULL default '0',
`ViewCount` int(11) NOT NULL default '0',
`Body` text NOT NULL,
`OwnerUserId` bigint(20) unsigned NOT NULL,
`OwnerDisplayName` varchar(40) default NULL,
`LastEditorUserId` bigint(20) unsigned default NULL,
`LastEditDate` datetime default NULL,
`LastActivityDate` datetime default NULL,
`Title` varchar(250) NOT NULL default '',
`Tags` varchar(150) NOT NULL default '',
`AnswerCount` int(11) NOT NULL default '0',
`CommentCount` int(11) NOT NULL default '0',
`FavoriteCount` int(11) NOT NULL default '0',
`ClosedDate` datetime default NULL,
PRIMARY KEY (`PostId`),
UNIQUE KEY `PostId` (`PostId`),
KEY `PostTypeId` (`PostTypeId`),
KEY `AcceptedAnswerId` (`AcceptedAnswerId`),
KEY `OwnerUserId` (`OwnerUserId`),
KEY `LastEditorUserId` (`LastEditorUserId`),
KEY `ParentId` (`ParentId`),
CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`PostTypeId`) REFERENCES `posttypes` (`PostTypeId`)
) ENGINE=InnoDB;
</code></pre>
<hr />
<p><strong>Note to commenters: If you want another benchmark with a different version of MySQL, a different dataset, or different table design, feel free to do it yourself. I have shown the technique above. Stack Overflow is here to show you how to do software development work, not to do all the work for you.</strong></p> | {
"question_id": 1313120,
"question_date": "2009-08-21T17:04:04.147Z",
"question_score": 1243,
"tags": "mysql|sql|group-by|greatest-n-per-group|groupwise-maximum",
"answer_id": 1313293,
"answer_date": "2009-08-21T17:39:46.603Z",
"answer_score": 1278
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.