input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How do I get the list of keys in a Dictionary? <p>I only want the Keys and not the Values of a Dictionary.</p> <p>I haven't been able to get any code to do this yet. Using another array proved to be too much work as I use remove also.</p> <p><strong>How do I get a List of the Keys in a Dictionary?</strong></p>
<pre><code>List&lt;string&gt; keyList = new List&lt;string&gt;(this.yourDictionary.Keys); </code></pre>
{ "question_id": 1276763, "question_date": "2009-08-14T08:54:42.360Z", "question_score": 205, "tags": "c#|list|dictionary", "answer_id": 1276792, "answer_date": "2009-08-14T08:59:47.950Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: XPath with multiple conditions <p>What XPath can I use to select any category with a name attribute specified and any child node author with the value specified.</p> <p>I've tried different variations of the path below with no success:</p> <pre><code>//quotes/category[@name='Sport' and author="James Small"] </code></pre> <p>The XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;quotes&gt; &lt;category name="Sport"&gt; &lt;author&gt;James Small&lt;quote date="09/02/1985"&gt;Quote One&lt;/quote&gt;&lt;quote date="11/02/1925"&gt;Quote nine&lt;/quote&gt;&lt;/author&gt; &lt;/category&gt; &lt;category name="Music"&gt; &lt;author&gt;Stephen Swann &lt;quote date="04/08/1972"&gt;Quote eleven&lt;/quote&gt;&lt;/author&gt; &lt;/category&gt; &lt;/quotes&gt; </code></pre>
<p>Try:<br> <code>//category[@name='Sport' and ./author/text()='James Small']</code></p>
{ "question_id": 10247978, "question_date": "2012-04-20T14:14:20.463Z", "question_score": 205, "tags": "xml|xslt|xpath", "answer_id": 10248149, "answer_date": "2012-04-20T14:26:03.853Z", "answer_score": 306 }
Please answer the following Stack Overflow question: Title: It is more efficient to use if-return-return or if-else-return? <p>Suppose I have an <code>if</code> statement with a <code>return</code>. From the efficiency perspective, should I use</p> <pre><code>if(A &gt; B): return A+1 return A-1 </code></pre> <p>or</p> <pre><code>if(A &gt; B): return A+1 else: return A-1 </code></pre> <p>Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?</p>
<p>Since the <code>return</code> statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).</p> <p>The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the <code>if</code> condition is false anyway.</p> <p>Note that Python supports a syntax that allows you to use only one <code>return</code> statement in your case:</p> <pre><code>return A+1 if A &gt; B else A-1 </code></pre>
{ "question_id": 9191388, "question_date": "2012-02-08T10:20:53.333Z", "question_score": 205, "tags": "python|c|performance|compiler-construction", "answer_id": 9191474, "answer_date": "2012-02-08T10:25:56.537Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: How to set URL query params in Vue with Vue-Router <p>I am trying to set query params with <a href="https://github.com/vuejs/vue-router" rel="noreferrer">Vue-router</a> when changing input fields, I don't want to navigate to some other page but just want to modify url query params on the same page, I am doing like this:</p> <pre><code>this.$router.replace({ query: { q1: "q1" } }) </code></pre> <p>But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it.</p> <hr> <p>Edited:</p> <p>Here is my router code:</p> <pre><code>export default new Router({ mode: 'history', scrollBehavior: (to, from, savedPosition) =&gt; { if (to.hash) { return {selector: to.hash} } else { return {x: 0, y: 0} } }, routes: [ ....... { path: '/user/:id', component: UserView }, ] }) </code></pre>
<p>Here is the example in docs:</p> <pre><code>// with query, resulting in /register?plan=private router.push({ path: 'register', query: { plan: 'private' }}) </code></pre> <p>Ref: <a href="https://router.vuejs.org/en/essentials/navigation.html" rel="noreferrer">https://router.vuejs.org/en/essentials/navigation.html</a></p> <p>As mentioned in those docs, <code>router.replace</code> works like <code>router.push</code></p> <p>So, you seem to have it right in your sample code in question. But I think you may need to include either <code>name</code> or <code>path</code> parameter also, so that the router has some route to navigate to. Without a <code>name</code> or <code>path</code>, it does not look very meaningful.</p> <p>This is my current understanding now:</p> <ul> <li><code>query</code> is optional for router - some additional info for the component to construct the view</li> <li><code>name</code> or <code>path</code> is mandatory - it decides what component to show in your <code>&lt;router-view&gt;</code>.</li> </ul> <p>That might be the missing thing in your sample code.</p> <p><strong>EDIT: Additional details after comments</strong></p> <p>Have you tried using <strong>named routes</strong> in this case? You have dynamic routes, and it is easier to provide params and query separately:</p> <pre><code>routes: [ { name: 'user-view', path: '/user/:id', component: UserView }, // other routes ] </code></pre> <p>and then in your methods:</p> <pre><code>this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} }) </code></pre> <p>Technically there is no difference between the above and <code>this.$router.replace({path: "/user/123", query:{q1: "q1"}})</code>, but it is easier to supply dynamic params on named routes than composing the route string. But in either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.</p> <p>After you are inside the route, you can fetch your dynamic params as <code>this.$route.params.id</code> and your query params as <code>this.$route.query.q1</code>.</p>
{ "question_id": 40382388, "question_date": "2016-11-02T14:25:37.960Z", "question_score": 205, "tags": "javascript|vue-router|vue.js", "answer_id": 40394184, "answer_date": "2016-11-03T05:04:08.677Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: How can I tell when a MySQL table was last updated? <p>In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated.</p> <p>What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value?</p>
<p>In later versions of MySQL you can use the <code>information_schema</code> database to tell you when another table was updated:</p> <pre><code>SELECT UPDATE_TIME FROM information_schema.tables WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tabname' </code></pre> <p>This does of course mean opening a connection to the database.</p> <hr> <p>An alternative option would be to "touch" a particular file whenever the MySQL table is updated:</p> <p>On database updates:</p> <ul> <li>Open your timestamp file in <code>O_RDRW</code> mode</li> <li><code>close</code> it again</li> </ul> <p>or alternatively</p> <ul> <li>use <a href="http://us3.php.net/manual/en/function.touch.php" rel="noreferrer"><code>touch()</code></a>, the PHP equivalent of the <code>utimes()</code> function, to change the file timestamp.</li> </ul> <p>On page display:</p> <ul> <li>use <code>stat()</code> to read back the file modification time.</li> </ul>
{ "question_id": 307438, "question_date": "2008-11-21T00:48:59.003Z", "question_score": 205, "tags": "mysql|sql", "answer_id": 307488, "answer_date": "2008-11-21T01:06:42.150Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: How to calculate rolling / moving average using python + NumPy / SciPy? <p>There seems to be no function that simply calculates the moving average on numpy/scipy, leading to <a href="https://stackoverflow.com/questions/12816011/weighted-moving-average-with-numpy-convolve">convoluted solutions</a>.</p> <p>My question is two-fold:</p> <ul> <li>What's the easiest way to (correctly) implement a moving average with numpy?</li> <li>Since this seems non-trivial and error prone, is there a good reason not to have the <a href="https://www.python.org/dev/peps/pep-0206/#batteries-included-philosophy" rel="noreferrer">batteries included</a> in this case?</li> </ul>
<p>A simple way to achieve this is by using <a href="https://docs.scipy.org/doc/numpy-1.14.1/reference/generated/numpy.convolve.html" rel="noreferrer"><code>np.convolve</code></a>. The idea behind this is to leverage the way the <a href="https://en.wikipedia.org/wiki/Convolution#Discrete_convolution" rel="noreferrer">discrete convolution</a> is computed and use it to return a <i>rolling mean</i>. This can be done by convolving with a sequence of <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ones.html" rel="noreferrer"><code>np.ones</code></a> of a length equal to the sliding window length we want.</p> <p>In order to do so we could define the following function:</p> <pre><code>def moving_average(x, w): return np.convolve(x, np.ones(w), 'valid') / w </code></pre> <p>This function will be taking the convolution of the sequence <code>x</code> and a sequence of ones of length <code>w</code>. Note that the chosen <code>mode</code> is <code>valid</code> so that the convolution product is only given for points where the sequences overlap completely.</p> <hr> <p>Some examples:</p> <pre><code>x = np.array([5,3,8,10,2,1,5,1,0,2]) </code></pre> <p>For a moving average with a window of length <code>2</code> we would have:</p> <pre><code>moving_average(x, 2) # array([4. , 5.5, 9. , 6. , 1.5, 3. , 3. , 0.5, 1. ]) </code></pre> <p>And for a window of length <code>4</code>:</p> <pre><code>moving_average(x, 4) # array([6.5 , 5.75, 5.25, 4.5 , 2.25, 1.75, 2. ]) </code></pre> <hr> <h2>How does <code>convolve</code> work?</h2> <p>Lets have a more in depth look at the way the discrete convolution is being computed. The following function aims to replicate the way <code>np.convolve</code> is computing the output values:</p> <pre><code>def mov_avg(x, w): for m in range(len(x)-(w-1)): yield sum(np.ones(w) * x[m:m+w]) / w </code></pre> <p>Which, for the same example above would also yield:</p> <pre><code>list(mov_avg(x, 2)) # [4.0, 5.5, 9.0, 6.0, 1.5, 3.0, 3.0, 0.5, 1.0] </code></pre> <p>So what is being done at each step is to take the inner product between the array of ones and the current <i> window</i>. In this case the multiplication by <code>np.ones(w)</code> is superfluous given that we are directly taking the <code>sum</code> of the sequence.</p> <p>Bellow is an example of how the first outputs are computed so that it is a little clearer. Lets suppose we want a window of <code>w=4</code>:</p> <pre><code>[1,1,1,1] [5,3,8,10,2,1,5,1,0,2] = (1*5 + 1*3 + 1*8 + 1*10) / w = 6.5 </code></pre> <p>And the following output would be computed as:</p> <pre><code> [1,1,1,1] [5,3,8,10,2,1,5,1,0,2] = (1*3 + 1*8 + 1*10 + 1*2) / w = 5.75 </code></pre> <p>And so on, returning a moving average of the sequence once all overlaps have been performed.</p>
{ "question_id": 14313510, "question_date": "2013-01-14T04:59:12.233Z", "question_score": 205, "tags": "python|numpy|time-series|moving-average|rolling-computation", "answer_id": 54628145, "answer_date": "2019-02-11T10:11:13.497Z", "answer_score": 211 }
Please answer the following Stack Overflow question: Title: Form inside a form, is that alright? <p>Whether we can have a form inside another form?. Is there any problem with that.</p>
<p>Though you can have several <code>&lt;form&gt;</code> elements in one HTML page, you cannot nest them.</p>
{ "question_id": 3430214, "question_date": "2010-08-07T11:21:06.800Z", "question_score": 205, "tags": "html|forms", "answer_id": 3430226, "answer_date": "2010-08-07T11:25:17.497Z", "answer_score": 259 }
Please answer the following Stack Overflow question: Title: How to convert a table to a data frame <p>I have a table in R that has <code>str()</code> of this:</p> <pre><code> table [1:3, 1:4] 0.166 0.319 0.457 0.261 0.248 ... - attr(*, "dimnames")=List of 2 ..$ x: chr [1:3] "Metro &gt;=1 million" "Metro &lt;1 million" "Non-Metro Counties" ..$ y: chr [1:4] "q1" "q2" "q3" "q4" </code></pre> <p>And looks like this when I print it:</p> <pre><code> y x q1 q2 q3 q4 Metro &gt;=1 million 0.1663567 0.2612212 0.2670441 0.3053781 Metro &lt;1 million 0.3192857 0.2480012 0.2341030 0.1986102 Non-Metro Counties 0.4570341 0.2044960 0.2121102 0.1263597 </code></pre> <p>I want to get rid of the <code>x</code> and <code>y</code> and convert it to a data frame that looks exactly the same as the above (three rows, four columns), but without the <code>x</code> or <code>y</code>. If I use <code>as.data.frame(mytable)</code>, instead I get this:</p> <pre><code> x y Freq 1 Metro &gt;=1 million q1 0.1663567 2 Metro &lt;1 million q1 0.3192857 3 Non-Metro Counties q1 0.4570341 4 Metro &gt;=1 million q2 0.2612212 5 Metro &lt;1 million q2 0.2480012 6 Non-Metro Counties q2 0.2044960 7 Metro &gt;=1 million q3 0.2670441 8 Metro &lt;1 million q3 0.2341030 9 Non-Metro Counties q3 0.2121102 10 Metro &gt;=1 million q4 0.3053781 11 Metro &lt;1 million q4 0.1986102 12 Non-Metro Counties q4 0.1263597 </code></pre> <p>I probably fundamentally do not understand how tables relate to data frames. </p>
<p>I figured it out already:</p> <pre><code>as.data.frame.matrix(mytable) </code></pre> <p>does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this <a href="http://toddjobe.blogspot.com/2010/08/converting-r-contingency-tables-to-data.html" rel="noreferrer">as.data.frame.matrix() function for contingency tables at the Computational Ecology blog</a>.</p>
{ "question_id": 10758961, "question_date": "2012-05-25T17:35:18.957Z", "question_score": 205, "tags": "r|dataframe", "answer_id": 10759011, "answer_date": "2012-05-25T17:40:01.557Z", "answer_score": 386 }
Please answer the following Stack Overflow question: Title: numpy max vs amax vs maximum <p>numpy has three different functions which seem like they can be used for the same things --- except that <code>numpy.maximum</code> can <em>only</em> be used element-wise, while <code>numpy.max</code> and <code>numpy.amax</code> can be used on particular axes, or all elements. Why is there more than just <code>numpy.max</code>? Is there some subtlety to this in performance?</p> <p>(Similarly for <code>min</code> vs. <code>amin</code> vs. <code>minimum</code>)</p>
<p><code>np.max</code> is just an alias for <code>np.amax</code>. This function only works on a <em>single</em> input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an <code>axis</code> argument and will find the maximum value along an axis of the input array (returning a new array).</p> <pre><code>&gt;&gt;&gt; a = np.array([[0, 1, 6], [2, 4, 1]]) &gt;&gt;&gt; np.max(a) 6 &gt;&gt;&gt; np.max(a, axis=0) # max of each column array([2, 4, 6]) </code></pre> <p>The default behaviour of <code>np.maximum</code> is to take <em>two</em> arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:</p> <pre><code>&gt;&gt;&gt; b = np.array([3, 6, 1]) &gt;&gt;&gt; c = np.array([4, 2, 9]) &gt;&gt;&gt; np.maximum(b, c) array([4, 6, 9]) </code></pre> <p>But <code>np.maximum</code> is also a <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html" rel="noreferrer">universal function</a> which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):</p> <pre><code>&gt;&gt;&gt; d = np.array([2, 0, 3, -4, -2, 7, 9]) &gt;&gt;&gt; np.maximum.accumulate(d) array([2, 2, 3, 3, 3, 7, 9]) </code></pre> <p>This is not possible with <code>np.max</code>.</p> <p>You can make <code>np.maximum</code> imitate <code>np.max</code> to a certain extent when using <code>np.maximum.reduce</code>:</p> <pre><code>&gt;&gt;&gt; np.maximum.reduce(d) 9 &gt;&gt;&gt; np.max(d) 9 </code></pre> <p>Basic testing suggests the two approaches are comparable in performance; and they should be, as <a href="https://github.com/numpy/numpy/blob/v1.16.1/numpy/core/_methods.py#L16-L28" rel="noreferrer"><code>np.max()</code> actually calls <code>np.maximum.reduce</code></a> to do the computation.</p>
{ "question_id": 33569668, "question_date": "2015-11-06T15:02:46.263Z", "question_score": 205, "tags": "python|numpy|math|max", "answer_id": 33569857, "answer_date": "2015-11-06T15:13:06.880Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: Create a custom event in Java <p>I want to do something like this in Java but I don't know the way:</p> <p>When event "object 1 say 'hello'" happens, then object 2 responds to that event by saying "hello".</p> <p>Can somebody give me a hint or sample code?</p>
<p>You probably want to look into the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="noreferrer">observer pattern</a>.</p> <p>Here's some sample code to get yourself started:</p> <pre><code>import java.util.*; // An interface to be implemented by everyone interested in "Hello" events interface HelloListener { void someoneSaidHello(); } // Someone who says "Hello" class Initiater { private List&lt;HelloListener&gt; listeners = new ArrayList&lt;HelloListener&gt;(); public void addListener(HelloListener toAdd) { listeners.add(toAdd); } public void sayHello() { System.out.println("Hello!!"); // Notify everybody that may be interested. for (HelloListener hl : listeners) hl.someoneSaidHello(); } } // Someone interested in "Hello" events class Responder implements HelloListener { @Override public void someoneSaidHello() { System.out.println("Hello there..."); } } class Test { public static void main(String[] args) { Initiater initiater = new Initiater(); Responder responder = new Responder(); initiater.addListener(responder); initiater.sayHello(); // Prints "Hello!!!" and "Hello there..." } } </code></pre> <hr> <p>Related article: <a href="http://programming.guide/java/create-a-custom-event.html" rel="noreferrer">Java: Creating a custom event</a></p>
{ "question_id": 6270132, "question_date": "2011-06-07T18:48:54.090Z", "question_score": 205, "tags": "java|events|listener|handler", "answer_id": 6270150, "answer_date": "2011-06-07T18:50:29.320Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: How to print binary tree diagram in Java? <p>How can I print a binary tree in Java so that the output is like:</p> <pre><code> 4 / \ 2 5 </code></pre> <p>My node:</p> <pre><code>public class Node&lt;A extends Comparable&gt; { Node&lt;A&gt; left, right; A data; public Node(A data){ this.data = data; } } </code></pre>
<p>I've created simple binary tree printer. You can use and modify it as you want, but it's not optimized anyway. I think that a lot of things can be improved here ;)</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BTreePrinterTest { private static Node&lt;Integer&gt; test1() { Node&lt;Integer&gt; root = new Node&lt;Integer&gt;(2); Node&lt;Integer&gt; n11 = new Node&lt;Integer&gt;(7); Node&lt;Integer&gt; n12 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n21 = new Node&lt;Integer&gt;(2); Node&lt;Integer&gt; n22 = new Node&lt;Integer&gt;(6); Node&lt;Integer&gt; n23 = new Node&lt;Integer&gt;(3); Node&lt;Integer&gt; n24 = new Node&lt;Integer&gt;(6); Node&lt;Integer&gt; n31 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n32 = new Node&lt;Integer&gt;(8); Node&lt;Integer&gt; n33 = new Node&lt;Integer&gt;(4); Node&lt;Integer&gt; n34 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n35 = new Node&lt;Integer&gt;(8); Node&lt;Integer&gt; n36 = new Node&lt;Integer&gt;(4); Node&lt;Integer&gt; n37 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n38 = new Node&lt;Integer&gt;(8); root.left = n11; root.right = n12; n11.left = n21; n11.right = n22; n12.left = n23; n12.right = n24; n21.left = n31; n21.right = n32; n22.left = n33; n22.right = n34; n23.left = n35; n23.right = n36; n24.left = n37; n24.right = n38; return root; } private static Node&lt;Integer&gt; test2() { Node&lt;Integer&gt; root = new Node&lt;Integer&gt;(2); Node&lt;Integer&gt; n11 = new Node&lt;Integer&gt;(7); Node&lt;Integer&gt; n12 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n21 = new Node&lt;Integer&gt;(2); Node&lt;Integer&gt; n22 = new Node&lt;Integer&gt;(6); Node&lt;Integer&gt; n23 = new Node&lt;Integer&gt;(9); Node&lt;Integer&gt; n31 = new Node&lt;Integer&gt;(5); Node&lt;Integer&gt; n32 = new Node&lt;Integer&gt;(8); Node&lt;Integer&gt; n33 = new Node&lt;Integer&gt;(4); root.left = n11; root.right = n12; n11.left = n21; n11.right = n22; n12.right = n23; n22.left = n31; n22.right = n32; n23.left = n33; return root; } public static void main(String[] args) { BTreePrinter.printNode(test1()); BTreePrinter.printNode(test2()); } } class Node&lt;T extends Comparable&lt;?&gt;&gt; { Node&lt;T&gt; left, right; T data; public Node(T data) { this.data = data; } } class BTreePrinter { public static &lt;T extends Comparable&lt;?&gt;&gt; void printNode(Node&lt;T&gt; root) { int maxLevel = BTreePrinter.maxLevel(root); printNodeInternal(Collections.singletonList(root), 1, maxLevel); } private static &lt;T extends Comparable&lt;?&gt;&gt; void printNodeInternal(List&lt;Node&lt;T&gt;&gt; nodes, int level, int maxLevel) { if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes)) return; int floor = maxLevel - level; int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0))); int firstSpaces = (int) Math.pow(2, (floor)) - 1; int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1; BTreePrinter.printWhitespaces(firstSpaces); List&lt;Node&lt;T&gt;&gt; newNodes = new ArrayList&lt;Node&lt;T&gt;&gt;(); for (Node&lt;T&gt; node : nodes) { if (node != null) { System.out.print(node.data); newNodes.add(node.left); newNodes.add(node.right); } else { newNodes.add(null); newNodes.add(null); System.out.print(" "); } BTreePrinter.printWhitespaces(betweenSpaces); } System.out.println(""); for (int i = 1; i &lt;= endgeLines; i++) { for (int j = 0; j &lt; nodes.size(); j++) { BTreePrinter.printWhitespaces(firstSpaces - i); if (nodes.get(j) == null) { BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1); continue; } if (nodes.get(j).left != null) System.out.print("/"); else BTreePrinter.printWhitespaces(1); BTreePrinter.printWhitespaces(i + i - 1); if (nodes.get(j).right != null) System.out.print("\\"); else BTreePrinter.printWhitespaces(1); BTreePrinter.printWhitespaces(endgeLines + endgeLines - i); } System.out.println(""); } printNodeInternal(newNodes, level + 1, maxLevel); } private static void printWhitespaces(int count) { for (int i = 0; i &lt; count; i++) System.out.print(" "); } private static &lt;T extends Comparable&lt;?&gt;&gt; int maxLevel(Node&lt;T&gt; node) { if (node == null) return 0; return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1; } private static &lt;T&gt; boolean isAllElementsNull(List&lt;T&gt; list) { for (Object object : list) { if (object != null) return false; } return true; } } </code></pre> <p>Output 1 :</p> <pre><code> 2 / \ / \ / \ / \ 7 5 / \ / \ / \ / \ 2 6 3 6 / \ / \ / \ / \ 5 8 4 5 8 4 5 8 </code></pre> <p>Output 2 :</p> <pre><code> 2 / \ / \ / \ / \ 7 5 / \ \ / \ \ 2 6 9 / \ / 5 8 4 </code></pre>
{ "question_id": 4965335, "question_date": "2011-02-11T03:28:33.277Z", "question_score": 205, "tags": "java|data-structures|printing|binary-tree", "answer_id": 4973083, "answer_date": "2011-02-11T19:16:55.407Z", "answer_score": 272 }
Please answer the following Stack Overflow question: Title: How to use mongoimport to import csv <p>Trying to import a CSV with contact information:</p> <pre><code>Name,Address,City,State,ZIP Jane Doe,123 Main St,Whereverville,CA,90210 John Doe,555 Broadway Ave,New York,NY,10010 </code></pre> <p>Running this doesn't seem to add any documents to the database:</p> <pre><code>$ mongoimport -d mydb -c things --type csv --file locations.csv --headerline </code></pre> <p>Trace says <code>imported 1 objects</code>, but firing up the Mongo shell and running <code>db.things.find()</code> doesn't show any new documents. </p> <p>What am I missing?</p>
<p>Your example worked for me with MongoDB 1.6.3 and 1.7.3. Example below was for 1.7.3. Are you using an older version of MongoDB?</p> <pre><code>$ cat &gt; locations.csv Name,Address,City,State,ZIP Jane Doe,123 Main St,Whereverville,CA,90210 John Doe,555 Broadway Ave,New York,NY,10010 ctrl-d $ mongoimport -d mydb -c things --type csv --file locations.csv --headerline connected to: 127.0.0.1 imported 3 objects $ mongo MongoDB shell version: 1.7.3 connecting to: test &gt; use mydb switched to db mydb &gt; db.things.find() { "_id" : ObjectId("4d32a36ed63d057130c08fca"), "Name" : "Jane Doe", "Address" : "123 Main St", "City" : "Whereverville", "State" : "CA", "ZIP" : 90210 } { "_id" : ObjectId("4d32a36ed63d057130c08fcb"), "Name" : "John Doe", "Address" : "555 Broadway Ave", "City" : "New York", "State" : "NY", "ZIP" : 10010 } </code></pre>
{ "question_id": 4686500, "question_date": "2011-01-13T23:27:49.280Z", "question_score": 205, "tags": "database|mongodb|csv|import|mongoimport", "answer_id": 4704373, "answer_date": "2011-01-16T07:57:55.433Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Fill SVG path element with a background-image <p>Is it possible to set a <code>background-image</code> for an SVG <code>&lt;path&gt;</code> element?</p> <p>For instance, if I set the element <code>class="wall"</code>, the CSS style <code>.wall {fill: red;}</code> works, but <code>.wall{background-image: url(wall.jpg)}</code> does not, neither <code>.wall {background-color: red;}</code>.</p>
<p>You can do it by making the background into a <a href="http://www.w3.org/TR/SVG/pservers.html#Patterns" rel="noreferrer">pattern</a>:</p> <pre><code>&lt;defs&gt; &lt;pattern id=&quot;img1&quot; patternUnits=&quot;userSpaceOnUse&quot; width=&quot;100&quot; height=&quot;100&quot;&gt; &lt;image href=&quot;wall.jpg&quot; x=&quot;0&quot; y=&quot;0&quot; width=&quot;100&quot; height=&quot;100&quot; /&gt; &lt;/pattern&gt; &lt;/defs&gt; </code></pre> <p>Adjust the width and height according to your image, then reference it from the path like this:</p> <pre><code>&lt;path d=&quot;M5,50 l0,100 l100,0 l0,-100 l-100,0 M215,100 a50,50 0 1 1 -100,0 50,50 0 1 1 100,0 M265,50 l50,100 l-100,0 l50,-100 z&quot; fill=&quot;url(#img1)&quot; /&gt; </code></pre> <p><a href="http://www.boogdesign.com/examples/svg/path-pattern-fill.svg" rel="noreferrer">Working example</a></p>
{ "question_id": 3796025, "question_date": "2010-09-25T23:48:03.090Z", "question_score": 205, "tags": "html|css|image|svg|background-image", "answer_id": 3798797, "answer_date": "2010-09-26T16:45:44.713Z", "answer_score": 308 }
Please answer the following Stack Overflow question: Title: How to convert DateTime? to DateTime <p>I want to convert a nullable DateTime (<code>DateTime?</code>) to a <code>DateTime</code>, but I am getting an error:</p> <blockquote> <p>Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)</p> </blockquote> <p>I have attempted the following:</p> <pre><code>DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate; </code></pre>
<p>You want to use the <a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="noreferrer">null-coalescing operator</a>, which is designed for exactly this purpose.</p> <p>Using it you end up with this code.</p> <pre><code>DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now; </code></pre>
{ "question_id": 1091870, "question_date": "2009-07-07T11:46:10.617Z", "question_score": 205, "tags": "c#|.net|datetime", "answer_id": 1091901, "answer_date": "2009-07-07T11:54:23.830Z", "answer_score": 347 }
Please answer the following Stack Overflow question: Title: Creating a DateTime in a specific Time Zone in c# <p>I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.</p> <p>In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located.</p> <p>From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified.</p> <p>How do I create a DateTime with a specific timezone like PST?</p>
<p><a href="https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512">Jon's answer</a> talks about <a href="http://msdn.microsoft.com/en-us/library/system.timezone.aspx" rel="noreferrer">TimeZone</a>, but I'd suggest using <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="noreferrer">TimeZoneInfo</a> instead.</p> <p>Personally I like keeping things in UTC where possible (at least for the past; <a href="https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/" rel="noreferrer">storing UTC for the <em>future</em> has potential issues</a>), so I'd suggest a structure like this:</p> <pre><code>public struct DateTimeWithZone { private readonly DateTime utcDateTime; private readonly TimeZoneInfo timeZone; public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone) { var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); this.timeZone = timeZone; } public DateTime UniversalTime { get { return utcDateTime; } } public TimeZoneInfo TimeZone { get { return timeZone; } } public DateTime LocalTime { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } } } </code></pre> <p>You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.</p>
{ "question_id": 246498, "question_date": "2008-10-29T11:48:05.917Z", "question_score": 205, "tags": "c#|.net|datetime|timezone|.net-3.5", "answer_id": 246529, "answer_date": "2008-10-29T12:00:15.860Z", "answer_score": 259 }
Please answer the following Stack Overflow question: Title: Pipenv: Command Not Found <p>I'm new to Python development and attempting to use pipenv. I ran the command <code>pip install pipenv</code>, which ran successfully:</p> <pre><code>... Successfully built pipenv pathlib shutilwhich pythonz-bd virtualenv-clone Installing collected packages: virtualenv, pathlib, shutilwhich, backports.shutil-get-terminal-size, pythonz-bd, virtualenv-clone, pew, first, six, click, pip-tools, certifi, chardet, idna, urllib3, requests, pipenv ... </code></pre> <p>However, when I run the command <code>pipenv install</code> in a fresh root project directory I receive the following message: <code>-bash: pipenv: command not found</code>. I suspect that I might need to modify my .bashrc, but I'm unclear about what to add to the file or if modification is even necessary.</p>
<p>That happens because you are not installing it globally (system wide). For it to be available in your <code>path</code> you need to install it using <code>sudo</code>, like this:</p> <pre><code>$ sudo pip install pipenv </code></pre>
{ "question_id": 46391721, "question_date": "2017-09-24T15:28:45.357Z", "question_score": 205, "tags": "python|python-3.x|pip|pipenv", "answer_id": 46396136, "answer_date": "2017-09-25T00:35:45.193Z", "answer_score": 204 }
Please answer the following Stack Overflow question: Title: How to remove commits from a pull request <p>I did a pull request but after that I made some commits to the project locally which ended polluting my pull request, I tried to remove it but without any luck.</p> <p>I found some similar questions on StackOverflow but I can't apply what's in there. It's my first pull request on GitHub so it's kinda strange to me how all of this works.</p> <p>The highlighted commit is the one I need to keep and remove all the other stuff. It becomes the fourth commit in the history because I make some merge stuff.</p> <p><a href="https://i.stack.imgur.com/rapAX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rapAX.png" alt="enter image description here"></a></p> <p>my git log <a href="https://i.stack.imgur.com/Ja84G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ja84G.png" alt="enter image description here"></a></p> <p>Can someone please explain what's going on and how to fix this problem? </p>
<p>You have several techniques to do it.</p> <p><a href="https://stackoverflow.com/questions/34519665/how-to-move-head-back-to-a-previous-location/34519716#34519716">This post - read the part about the revert</a> will explain in details what we want to do and how to do it.</p> <p>Here is the most simple solution to your problem:</p> <pre><code># Checkout the desired branch git checkout &lt;branch&gt; # Undo the desired commit git revert &lt;commit&gt; # Update the remote with the undo of the code # The force is a tricky flag since it will force the push but # your administrator can block it, so if it's not an option you # can delete the old branch and push it again git push origin &lt;branch&gt; --force </code></pre> <p>The revert command will create a new commit with the <strong>undo</strong> of the original commit.</p>
{ "question_id": 36168839, "question_date": "2016-03-23T02:38:58.567Z", "question_score": 205, "tags": "git|github|pull-request", "answer_id": 36170904, "answer_date": "2016-03-23T06:05:06.173Z", "answer_score": 173 }
Please answer the following Stack Overflow question: Title: How do I calculate the normal vector of a line segment? <p>Suppose I have a line segment going from (x1,y1) to (x2,y2). How do I calculate the normal vector perpendicular to the line?</p> <p>I can find lots of stuff about doing this for planes in 3D, but no 2D stuff.</p> <p>Please go easy on the maths (links to worked examples, diagrams or algorithms are welcome), I'm a programmer more than I'm a mathematician ;)</p>
<p>If we define <code>dx = x2 - x1</code> and <code>dy = y2 - y1</code>, then the normals are <code>(-dy, dx)</code> and <code>(dy, -dx)</code>.</p> <p>Note that no division is required, and so you're not risking dividing by zero.</p>
{ "question_id": 1243614, "question_date": "2009-08-07T08:35:36.627Z", "question_score": 205, "tags": "math|geometry|vector", "answer_id": 1243676, "answer_date": "2009-08-07T08:49:19.330Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: When to use 'npm start' and when to use 'ng serve'? <blockquote> <p><code>ng serve</code> serves an Angular project via a development server</p> </blockquote> <p>&nbsp;</p> <blockquote> <p><code>npm start</code> runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.</p> </blockquote> <p>It seems like <code>ng serve</code> starts the embedded server whereas <code>npm start</code> starts the Node servers.</p> <p>Can someone throw some light on it?</p>
<p><code>npm start</code> will run whatever you have defined for the <code>start</code> command of the <code>scripts</code> object in your <code>package.json</code> file.</p> <p>So if it looks like this:</p> <pre><code>"scripts": { "start": "ng serve" } </code></pre> <p>Then <code>npm start</code> will run <code>ng serve</code>.</p>
{ "question_id": 40190538, "question_date": "2016-10-22T09:34:30.270Z", "question_score": 205, "tags": "angular|angular-cli", "answer_id": 40190595, "answer_date": "2016-10-22T09:39:51.820Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Can CSS force a line break after each word in an element? <p>I'm building a multilingual site, with the owner helping me with some translations. Some of the displayed phrases need line breaks to maintain the style of the site. </p> <p>Unfortunately, the owner isn't a computer guy, so if he sees <code>foo&lt;br /&gt;bar</code> there's the chance he'll modify the data somehow as he's translating.</p> <p>Is there a CSS solution (besides changing the width) to apply to an element which would break after every word?</p> <p>(I know I can do this in PHP, but I'm wondering if there's a nifty trick I don't know about in CSS to accomplish the same thing, perhaps in the CJK features.) </p> <p><strong>EDIT</strong></p> <p>I'll attempt to diagram what's happening:</p> <pre><code>---------------- ---------------- | Short Word | | Gargantuan | | | | Word | ---------------- ---------------- </code></pre> <p>The long word breaks automatically, the short word doesn't. I want it to look like this:</p> <pre><code>---------------- ---------------- | Short | | Gargantuan | | Word | | Word | ---------------- ---------------- </code></pre>
<p>Use</p> <pre class="lang-css prettyprint-override"><code>.one-word-per-line { word-spacing: &lt;parent-width&gt;; } .your-classname{ width: min-intrinsic; width: -webkit-min-content; width: -moz-min-content; width: min-content; display: table-caption; display: -ms-grid; -ms-grid-columns: min-content; } </code></pre> <p>where <code>&lt;parent-width&gt;</code> is the width of the parent element (or an arbitrary high value that doesn't fit into one line). That way you can be sure that there is even a line-break after a single letter. Works with Chrome/FF/Opera/IE7+ (and probably even IE6 since it's supporting word-spacing as well).</p>
{ "question_id": 4212909, "question_date": "2010-11-18T08:32:50.620Z", "question_score": 205, "tags": "css|line-breaks", "answer_id": 10831230, "answer_date": "2012-05-31T09:50:51.483Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: com.jcraft.jsch.JSchException: UnknownHostKey <p>I'm trying to use <a href="http://www.jcraft.com/jsch/" rel="nofollow noreferrer">Jsch</a> to establish an SSH connection in Java. My code produces the following exception:</p> <pre><code>com.jcraft.jsch.JSchException: UnknownHostKey: mywebsite.example. RSA key fingerprint is 22:fb:ee:fe:18:cd:aa:9a:9c:78:89:9f:b4:78:75:b4 </code></pre> <p>I cannot find how to verify the host key in the Jsch documentation. I have included my code below.</p> <pre><code>import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class ssh { public static void main(String[] arg) { try { JSch jsch = new JSch(); //create SSH connection String host = &quot;mywebsite.example&quot;; String user = &quot;username&quot;; String password = &quot;123456&quot;; Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.connect(); } catch(Exception e) { System.out.println(e); } } } </code></pre>
<p>I would either:</p> <ol> <li>Try to <code>ssh</code> from the command line and accept the public key (the host will be added to <code>~/.ssh/known_hosts</code> and everything should then work fine from Jsch) <em>-OR-</em></li> <li><p>Configure JSch to not use "StrictHostKeyChecking" (this introduces insecurities and should only be used for testing purposes), using the following code:</p> <pre><code>java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); </code></pre></li> </ol> <p>Option #1 (adding the host to the <code>~/.ssh/known_hosts</code> file) has my preference.</p>
{ "question_id": 2003419, "question_date": "2010-01-05T00:45:31.920Z", "question_score": 205, "tags": "java|ssh|jsch", "answer_id": 2003460, "answer_date": "2010-01-05T00:57:12.840Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Return anonymous type results? <p>Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?</p> <p>Say I have two tables:</p> <pre><code>Dogs: Name, Age, BreedId Breeds: BreedId, BreedName </code></pre> <p>I want to return all dogs with their <code>BreedName</code>. I should get all dogs using something like this with no problems:</p> <pre><code>public IQueryable&lt;Dog&gt; GetDogs() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select d; return result; } </code></pre> <p>But if I want dogs with breeds and try this I have problems:</p> <pre><code>public IQueryable&lt;Dog&gt; GetDogsWithBreedNames() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select new { Name = d.Name, BreedName = b.BreedName }; return result; } </code></pre> <p>Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type? Or do I have to create my own class for <code>DogsWithBreedNames</code> and specify that type in the select? Or is there another easier way?</p>
<p>I tend to go for this pattern:</p> <pre><code>public class DogWithBreed { public Dog Dog { get; set; } public string BreedName { get; set; } } public IQueryable&lt;DogWithBreed&gt; GetDogsWithBreedNames() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select new DogWithBreed() { Dog = d, BreedName = b.BreedName }; return result; } </code></pre> <p>It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.</p>
{ "question_id": 534690, "question_date": "2009-02-10T23:10:44.317Z", "question_score": 205, "tags": "c#|linq|linq-to-sql", "answer_id": 534794, "answer_date": "2009-02-10T23:35:56.317Z", "answer_score": 224 }
Please answer the following Stack Overflow question: Title: How can I create a text box for a note in markdown? <p>I am writing a document in markdown. I am using the wonderful pandoc to create docx and tex files from the markdown source. I would like to have a textbox for tips and notes to readers the way programming books often do. I cannot figure out how to do this in markdown. Can you help?</p>
<p>What I usually do for putting alert box (e.g. Note or Warning) in markdown texts (not only when using pandoc but also every where that markdown is supported) is surrounding the content with two horizontal lines:</p> <pre><code>--- **NOTE** It works with almost all markdown flavours (the below blank line matters). --- </code></pre> <p>which would be something like this:</p> <hr> <p><strong>NOTE</strong></p> <p>It works with all markdown flavours (the below blank line matters).</p> <hr> <p>The good thing is that you don't need to worry about which markdown flavour is supported or which extension is installed or enabled.</p> <p><strong>EDIT</strong>: As @filups21 has mentioned in the comments, it seems that a horizontal line is represented by <code>***</code> in RMarkdown. So, the solution mentioned before does not work with all markdown flavours as it was originally claimed.</p>
{ "question_id": 25654845, "question_date": "2014-09-03T22:52:44.730Z", "question_score": 205, "tags": "markdown|pandoc", "answer_id": 41449789, "answer_date": "2017-01-03T18:10:04.430Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Set TextView text from html-formatted string resource in XML <p>I have some fixed strings inside my <code>strings.xml</code>, something like:</p> <pre><code>&lt;resources&gt; &lt;string name="somestring"&gt; &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt; Content &lt;/string&gt; &lt;/resources&gt; </code></pre> <p>and in my layout I've got a <code>TextView</code> which I'd like to fill with the html-formatted string.</p> <pre><code>&lt;TextView android:id="@+id/formattedtext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/htmlstring"/&gt; </code></pre> <p>if I do this, the content of <code>formattedtext</code> is just the content of <code>somestring</code> stripped of any html tags and thus unformatted.</p> <p>I know that it is possible to set the formatted text programmatically with </p> <p><code>.setText(Html.fromHtml(somestring));</code> </p> <p>because I use this in other parts of my program where it is working as expected.</p> <p>To call this function I need an <code>Activity</code>, but at the moment my layout is just a simple more or less static view in plain XML and I'd prefer to leave it that way, to save me from the overhead of creating an <code>Activity</code> just to set some text.</p> <p>Am I overlooking something obvious? Is it not possible at all? Any help or workarounds welcome!</p> <p>Edit: Just tried some things and it seems that HTML formatting in xml has some restraints: </p> <ul> <li><p>tags must be written lowercase </p></li> <li><p>some tags which are mentioned <a href="https://stackoverflow.com/questions/3207769/android-textview-with-html-seperator">here</a> do not work, e.g. <code>&lt;br/&gt;</code> (it's possible to use <code>\n</code> instead)</p></li> </ul>
<p>Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You <em><strong>CAN</strong></em> include raw HTML in strings.xml, as long as you wrap it in</p> <pre><code>&lt;![CDATA[ ...raw html... ]]&gt; </code></pre> <h3>Edge Cases:</h3> <ul> <li>Characters like apostrophe ('), double-quote (&quot;), and ampersand (&amp;) only need to be escaped if you want them to appear in the rendered text AS themselves, but they COULD be plausibly interpreted as HTML. <ul> <li><code>'</code> and <code>&quot;</code> can be represented as<code>\'</code> and <code>\&quot;</code>, or <code>&amp;apos;</code> and <code>&amp;quot;</code>.</li> <li><code>&lt;</code> and <code>&gt;</code> <em>always</em> need to be escaped as <code>&amp;lt;</code> and <code>&amp;gt;</code> if you literally want them to render as '&lt;' and '&gt;' in the text.</li> <li>Ampersand (&amp;) is a little more complicated. <ul> <li>Ampersand followed by whitespace renders as ampersand.</li> <li>Ampersand followed by one or more characters that don't form a valid HTML entity code render as Ampersand followed by those characters. So... <code>&amp;qqq;</code> renders as <code>&amp;qqq;</code>, but <code>&amp;lt;1</code> renders as <code>&lt;1</code>.</li> </ul> </li> </ul> </li> </ul> <p>Example:</p> <pre><code>&lt;string name=&quot;nice_html&quot;&gt; &lt;![CDATA[ &lt;p&gt;This is a html-formatted \&quot;string\&quot; with &lt;b&gt;bold&lt;/b&gt; and &lt;i&gt;italic&lt;/i&gt; text&lt;/p&gt; &lt;p&gt;This is another paragraph from the same \'string\'.&lt;/p&gt; &lt;p&gt;To be clear, 0 &amp;lt; 1, &amp; 10 &amp;gt; 1&lt;p&gt; ]]&gt; &lt;/string&gt; </code></pre> <p>Then, in your code:</p> <pre><code>TextView foo = (TextView)findViewById(R.id.foo); foo.setText(Html.fromHtml(getString(R.string.nice_html), FROM_HTML_MODE_LEGACY)); </code></pre> <p>IMHO, this is several orders of magnitude nicer to work with :-)</p> <hr /> <p><strong>August 2021 update:</strong> My original answer used Html.fromHtml(String), which was deprecated in API 24. The alternative <a href="https://developer.android.com/reference/android/text/Html#fromHtml(java.lang.String,%20int)" rel="noreferrer">fromHtml(String,int)</a> form is suggested as its replacement.</p> <p>FROM_HTML_MODE_LEGACY is likely to work... but one of the other flags might be a better choice for what you want to do.</p> <p>On a final note, if you'd prefer to render Android Spanned text suitable for use in a TextView using <strong>Markdown</strong> syntax instead of HTML, there are now multiple thirdparty libraries to make it easy including <a href="https://noties.io/Markwon" rel="noreferrer">https://noties.io/Markwon</a>.</p>
{ "question_id": 3235131, "question_date": "2010-07-13T07:51:10.633Z", "question_score": 205, "tags": "html|android|formatting|textview", "answer_id": 6159538, "answer_date": "2011-05-28T03:52:44.713Z", "answer_score": 502 }
Please answer the following Stack Overflow question: Title: Binary search (bisection) in Python <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html" rel="noreferrer">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p> <p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p> <p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p> <p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p> <p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
<p><code>bisect_left</code> finds the first position <code>p</code> at which an element could be inserted in a given sorted range while maintaining the sorted order. That will be the position of <code>x</code> if <code>x</code> exists in the range. If <code>p</code> is the past-the-end position, <code>x</code> wasn't found. Otherwise, we can test to see if <code>x</code> is there to see if <code>x</code> was found.</p> <pre class="lang-python prettyprint-override"><code>from bisect import bisect_left def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) pos = bisect_left(a, x, lo, hi) # find insertion position return pos if pos != hi and a[pos] == x else -1 # don't walk off the end </code></pre>
{ "question_id": 212358, "question_date": "2008-10-17T14:23:17.630Z", "question_score": 205, "tags": "python|binary-search|bisection", "answer_id": 2233940, "answer_date": "2010-02-10T02:05:27.873Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: How to Reload ReCaptcha using JavaScript? <p>I have a signup form with AJAX so that I want to refresh Recaptcha image anytime an error is occured (i.e. username already in use).</p> <p>I am looking for a code compatible with ReCaptcha to reload it using JavaScript.</p>
<p><strong>Important:</strong> Version 1.0 of the reCAPTCHA API is no longer supported. Please upgrade to Version 2.0.</p> <p>You can use <em>grecaptcha.reset();</em> to reset the captcha.</p> <p>Source: <a href="https://developers.google.com/recaptcha/docs/display#js_api" rel="noreferrer">https://developers.google.com/recaptcha/docs/display#js_api</a></p>
{ "question_id": 3371314, "question_date": "2010-07-30T12:21:15.907Z", "question_score": 205, "tags": "javascript|recaptcha", "answer_id": 37607334, "answer_date": "2016-06-03T06:27:33.140Z", "answer_score": 53 }
Please answer the following Stack Overflow question: Title: How can I change default dialog button text color in android 5 <p>I have many alert dialogs in my app. It is a default layout but I am adding positive and negative buttons to the dialog. So the buttons get the default text color of Android 5 (green). I tried to changed it without success. Any idea how to change that text color?</p> <p>My Custom dialog:</p> <pre><code>public class MyCustomDialog extends AlertDialog.Builder { public MyCustomDialog(Context context,String title,String message) { super(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); View viewDialog = inflater.inflate(R.layout.dialog_simple, null, false); TextView titleTextView = (TextView)viewDialog.findViewById(R.id.title); titleTextView.setText(title); TextView messageTextView = (TextView)viewDialog.findViewById(R.id.message); messageTextView.setText(message); this.setCancelable(false); this.setView(viewDialog); } } </code></pre> <p>Creating the dialog:</p> <pre><code>MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ... } }).show(); </code></pre> <p>That negativeButton is a default dialog button and takes the default green color from Android 5 Lollipop.</p> <p>Many thanks</p> <p><img src="https://i.stack.imgur.com/K9rRe.png" alt="Custom dialog with green button"></p>
<p>You can try to create the <code>AlertDialog</code> object first, and then use it to set up to change the color of the button and then show it. (Note that on <code>builder</code> object instead of calling <code>show()</code> we call <code>create()</code> to get the <code>AlertDialog</code> object:</p> <pre><code>//1. create a dialog object 'dialog' MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage); AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ... } }).create(); //2. now setup to change color of the button dialog.setOnShowListener( new OnShowListener() { @Override public void onShow(DialogInterface arg0) { dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT); } }); dialog.show() </code></pre> <p>The reason you have to do it on <code>onShow()</code> and cannot just get that button after you create your dialog is that the button would not have been created yet. </p> <p>I changed <code>AlertDialog.BUTTON_POSITIVE</code> to <code>AlertDialog.BUTTON_NEGATIVE</code> to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.</p>
{ "question_id": 27965662, "question_date": "2015-01-15T14:29:29.163Z", "question_score": 205, "tags": "android|android-layout|android-5.0-lollipop|android-alertdialog|textcolor", "answer_id": 27965874, "answer_date": "2015-01-15T14:40:10.450Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: Resize svg when window is resized in d3.js <p>I'm drawing a scatterplot with d3.js. With the help of this question :<br> <a href="https://stackoverflow.com/questions/3437786/how-to-get-web-page-size-browser-window-size-screen-size-in-a-cross-browser-wa">Get the size of the screen, current web page and browser window</a></p> <p>I'm using this answer :</p> <pre><code>var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight|| e.clientHeight|| g.clientHeight; </code></pre> <p>So I'm able to fit my plot to the user's window like this :</p> <pre><code>var svg = d3.select("body").append("svg") .attr("width", x) .attr("height", y) .append("g"); </code></pre> <p>Now I'd like that something takes care of resizing the plot when the user resize the window.</p> <p>PS : I'm not using jQuery in my code.</p>
<p>Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.</p> <p>Here is how I did it:</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>d3.select("div#chartId") .append("div") // Container class to make it responsive. .classed("svg-container", true) .append("svg") // Responsive SVG needs these 2 attributes and no width and height attr. .attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", "0 0 600 400") // Class to make it responsive. .classed("svg-content-responsive", true) // Fill with a rectangle for visualization. .append("rect") .classed("rect", true) .attr("width", 600) .attr("height", 400);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.svg-container { display: inline-block; position: relative; width: 100%; padding-bottom: 100%; /* aspect ratio */ vertical-align: top; overflow: hidden; } .svg-content-responsive { display: inline-block; position: absolute; top: 10px; left: 0; } svg .rect { fill: gold; stroke: steelblue; stroke-width: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"&gt;&lt;/script&gt; &lt;div id="chartId"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Note:</strong> Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.</p> <p>More info / tutorials: </p> <p><a href="http://thenewcode.com/744/Make-SVG-Responsive" rel="noreferrer">http://thenewcode.com/744/Make-SVG-Responsive</a></p> <p><a href="http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php" rel="noreferrer">http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php</a></p>
{ "question_id": 16265123, "question_date": "2013-04-28T16:37:32.463Z", "question_score": 205, "tags": "javascript|d3.js", "answer_id": 25978286, "answer_date": "2014-09-22T15:55:51.930Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: How can I get the domain name of my site within a Django template? <p>How do I get the domain name of my current site from within a Django template? I've tried looking in the tag and filters but nothing there.</p>
<p>I think what you want is to have access to the request context, see RequestContext.</p>
{ "question_id": 1451138, "question_date": "2009-09-20T14:27:19.397Z", "question_score": 205, "tags": "python|python-3.x|django|django-templates|django-template-filters", "answer_id": 1451155, "answer_date": "2009-09-20T14:35:03.147Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: Why is Event.target not Element in Typescript? <p>I simply want to do this with my <code>KeyboardEvent</code></p> <pre><code>var tag = evt.target.tagName.toLowerCase(); </code></pre> <p>While <code>Event.target</code> is of type <code>EventTarget</code>, it does not inherit from <code>Element</code>. So I have to cast it like this:</p> <pre><code>var tag = (&lt;Element&gt;evt.target).tagName.toLowerCase(); </code></pre> <p>This is probably due to some browsers not following standards, right? What is the correct browser-agnostic implementation in TypeScript?</p> <p>P.S. I am using jQuery to capture the <code>KeyboardEvent</code>.</p>
<p>It doesn't inherit from <code>Element</code> because not all event targets are elements.</p> <p><a href="https://developer.mozilla.org/en/docs/Web/API/EventTarget" rel="noreferrer">From MDN</a>:</p> <blockquote> <p>Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.</p> </blockquote> <p>Even the <code>KeyboardEvent</code> you're trying to use can occur on a DOM element or on the window object (and theoretically on other things), so right there it wouldn't make sense for <code>evt.target</code> to be defined as an <code>Element</code>.</p> <p>If it is an event on a DOM element, then I would say that you can safely assume <code>evt.target</code>. is an <code>Element</code>. I don't think this is an matter of cross-browser behavior. Merely that <code>EventTarget</code> is a more abstract interface than <code>Element</code>.</p> <p>Further reading: <a href="https://github.com/Microsoft/TypeScript/issues/29540" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/29540</a></p>
{ "question_id": 28900077, "question_date": "2015-03-06T13:43:24.873Z", "question_score": 205, "tags": "typescript|event-listener", "answer_id": 28900856, "answer_date": "2015-03-06T14:26:48.953Z", "answer_score": 104 }
Please answer the following Stack Overflow question: Title: Word wrap for a label in Windows Forms <p>How can one get word wrap functionality for a <code>Label</code> for text which goes out of bounds?</p>
<p>The quick answer: switch <strong>off</strong> <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autosize%28v=vs.110%29.aspx" rel="noreferrer">AutoSize</a>.</p> <p>The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.</p> <p>Basically what you need to do in OnPaint is:</p> <ol> <li>Measure the height of the text (Graphics.MeasureString).</li> <li>If the label height is not equal to the height of the text set the height and return.</li> <li>Draw the text.</li> </ol> <p>You will also need to set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resizeredraw%28v=vs.110%29.aspx" rel="noreferrer">ResizeRedraw</a> style flag in the constructor.</p>
{ "question_id": 1204804, "question_date": "2009-07-30T06:33:12.270Z", "question_score": 205, "tags": "c#|.net|winforms|label|controls", "answer_id": 1204821, "answer_date": "2009-07-30T06:37:06.083Z", "answer_score": 182 }