input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to make the first option of <select> selected with jQuery <p>How do I make the first option of selected with jQuery?</p> <pre><code>&lt;select id="target"&gt; &lt;option value="1"&gt;...&lt;/option&gt; &lt;option value="2"&gt;...&lt;/option&gt; &lt;/select&gt; </code></pre>
<pre><code>$("#target").val($("#target option:first").val()); </code></pre>
{ "question_id": 1414276, "question_date": "2009-09-12T04:28:50.020Z", "question_score": 608, "tags": "jquery|select", "answer_id": 1414278, "answer_date": "2009-09-12T04:31:42.427Z", "answer_score": 1054 }
Please answer the following Stack Overflow question: Title: GitHub "fatal: remote origin already exists" <p>I am trying to follow along <a href="http://ruby.railstutorial.org/chapters/beginning#fnref:1.16" rel="noreferrer">Michael Hartl's Rails tutorial</a> but I've run across an error. </p> <p>I signed up on Github and issued a new SSH key and made a new repository. But when I enter the next line into the terminal I get the following error:</p> <pre><code>Parkers-MacBook-Pro:.ssh ppreyer$ git remote add origin [email protected]:ppreyer/first_app.git fatal: remote origin already exists. </code></pre> <p>Just wondered if anybody else has run across this problem?</p>
<p>TL;DR you should just update the existing remote:</p> <pre><code>$ git remote set-url origin [email protected]:ppreyer/first_app.git </code></pre> <p><strong>Long version:</strong></p> <p>As the error message indicates, there is already a remote configured with the same name. So you can either add the new remote with a different name or update the existing one if you don't need it:</p> <p>To add a new remote, called for example <code>github</code> instead of <code>origin</code> (which obviously already exists in your system), do the following:</p> <pre><code>$ git remote add github [email protected]:ppreyer/first_app.git </code></pre> <p>Remember though, everywhere in the tutorial you see <em>"origin"</em> you should replace it with <em>"github"</em>. For example <code>$ git push origin master</code> should now be <code>$ git push github master</code>.</p> <p>However, if you want to see what that <code>origin</code> which already exists is, you can do a <code>$ git remote -v</code>. If you think this is there by some error, you can update it like so:</p> <pre><code>$ git remote set-url origin [email protected]:ppreyer/first_app.git </code></pre>
{ "question_id": 10904339, "question_date": "2012-06-05T20:21:19.777Z", "question_score": 608, "tags": "git|github", "answer_id": 10904450, "answer_date": "2012-06-05T20:28:54.463Z", "answer_score": 1140 }
Please answer the following Stack Overflow question: Title: Git - Ignore node_modules folder everywhere <p>I have a project containing multiple other projects : </p> <ul> <li>Main project <ul> <li>Mini project 1</li> <li>Mini project 2</li> </ul></li> </ul> <p>All containing <code>node_modules</code> folder. I want git to ignore the folder no matter where it is starting from the root folder. Something like this to add in .gitignore : </p> <pre><code>*node_modules/* </code></pre>
<p>Add <code>node_modules/</code> or <code>node_modules</code> to the <code>.gitignore</code> file to ignore all directories called <code>node_modules</code> in the current folder and any subfolders like the below image.</p> <p><a href="https://i.stack.imgur.com/vPzT1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vPzT1.png" alt="example" /></a></p>
{ "question_id": 29820791, "question_date": "2015-04-23T10:30:44.360Z", "question_score": 608, "tags": "git|node-modules", "answer_id": 29820869, "answer_date": "2015-04-23T10:34:24.243Z", "answer_score": 1201 }
Please answer the following Stack Overflow question: Title: JavaScript checking for null vs. undefined and difference between == and === <ol> <li><p>How do I check a variable if it's <code>null</code> or <code>undefined</code> and what is the difference between the <code>null</code> and <code>undefined</code>?</p></li> <li><p>What is the difference between <code>==</code> and <code>===</code> (it's hard to search Google for "===" )?</p></li> </ol>
<blockquote> <p>How do I check a variable if it's <code>null</code> or <code>undefined</code>...</p> </blockquote> <p>Is the variable <code>null</code>:</p> <pre><code>if (a === null) // or if (a == null) // but see note below </code></pre> <p>...but note the latter will also be true if <code>a</code> is <code>undefined</code>.</p> <p>Is it <code>undefined</code>:</p> <pre><code>if (typeof a === "undefined") // or if (a === undefined) // or if (a == undefined) // but see note below </code></pre> <p>...but again, note that the last one is vague; it will also be true if <code>a</code> is <code>null</code>.</p> <p>Now, despite the above, the <strong>usual</strong> way to check for those is to use the fact that they're <em>falsey</em>:</p> <pre><code>if (!a) { // `a` is falsey, which includes `undefined` and `null` // (and `""`, and `0`, and `NaN`, and [of course] `false`) } </code></pre> <p>This is defined by <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-toboolean">ToBoolean</a> in the spec.</p> <blockquote> <p>...and what is the difference between the <code>null</code> and <code>undefined</code>?</p> </blockquote> <p>They're both values usually used to indicate the absence of something. <code>undefined</code> is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value <code>undefined</code>; there's a difference between calling a function with the value <code>undefined</code> for an argument, and leaving that argument off entirely.)</p> <p><code>null</code> is slightly more specific than <code>undefined</code>: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use <code>null</code>, not <code>undefined</code>. And similarly, the DOM's <code>getElementById</code> operation returns an object reference&nbsp;&mdash; either a valid one (if it found the DOM element), or <code>null</code> (if it didn't).</p> <p>Interestingly (or not), they're their own types. Which is to say, <code>null</code> is the only value in the Null type, and <code>undefined</code> is the only value in the Undefined type.</p> <blockquote> <p>What is the difference between "==" and "==="</p> </blockquote> <p>The only difference between them is that <code>==</code> will do type coercion to try to get the values to match, and <code>===</code> won't. So for instance <code>"1" == 1</code> is true, because <code>"1"</code> coerces to <code>1</code>. But <code>"1" === 1</code> is <em>false</em>, because the types don't match. (<code>"1" !== 1</code> is true.) The first (real) step of <code>===</code> is "Are the types of the operands the same?" and if the answer is "no", the result is <code>false</code>. If the types are the same, it does exactly what <code>==</code> does.</p> <p>Type coercion uses quite complex rules and can have surprising results (for instance, <code>"" == 0</code> is true).</p> <p>More in the spec:</p> <ul> <li><a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-abstract-equality-comparison">Abstract Equality Comparison</a> (<code>==</code>, also called "loose" equality)</li> <li><a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-strict-equality-comparison">Strict Equality Comparison</a> (<code>===</code>)</li> </ul>
{ "question_id": 5101948, "question_date": "2011-02-24T08:10:55.243Z", "question_score": 608, "tags": "javascript|null|undefined", "answer_id": 5101991, "answer_date": "2011-02-24T08:15:07.343Z", "answer_score": 971 }
Please answer the following Stack Overflow question: Title: How to implement class constants? <p>In TypeScript, the <code>const</code> keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."</p> <p>I find myself in need to clearly indicate in code that a property should not be changed. I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this? </p> <p>I'm currently using a read-only property, but I'm new to Typescript (and JavaScript) and wonder whether there is a better way:</p> <pre><code>get MY_CONSTANT():number {return 10}; </code></pre> <p>I'm using typescript 1.8. Suggestions?</p> <p>PS: I'm now using typescript 2.0.3, so I've accepted <a href="https://stackoverflow.com/a/37265481/6588498">David's answer</a></p>
<p>TypeScript 2.0 has the <a href="https://github.com/Microsoft/TypeScript/pull/6532" rel="noreferrer"><code>readonly</code> modifier</a>:</p> <pre><code>class MyClass { readonly myReadOnlyProperty = 1; myMethod() { console.log(this.myReadOnlyProperty); this.myReadOnlyProperty = 5; // error, readonly } } new MyClass().myReadOnlyProperty = 5; // error, readonly </code></pre> <p>It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.</p> <p><strong>Alternative Solution</strong></p> <p>An alternative is to use the <code>static</code> keyword with <code>readonly</code>:</p> <pre><code>class MyClass { static readonly myReadOnlyProperty = 1; constructor() { MyClass.myReadOnlyProperty = 5; // error, readonly } myMethod() { console.log(MyClass.myReadOnlyProperty); MyClass.myReadOnlyProperty = 5; // error, readonly } } MyClass.myReadOnlyProperty = 5; // error, readonly </code></pre> <p>This has the benefit of not being assignable in the constructor and only existing in one place.</p>
{ "question_id": 37265275, "question_date": "2016-05-17T00:32:02.607Z", "question_score": 608, "tags": "typescript|class-constants", "answer_id": 37265481, "answer_date": "2016-05-17T00:59:25.640Z", "answer_score": 919 }
Please answer the following Stack Overflow question: Title: .war vs .ear file <p>What is the difference between a .war and .ear file?</p>
<p>From <a href="http://www.geekinterview.com/question_details/630" rel="noreferrer">GeekInterview</a>:</p> <blockquote> <p>In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality </p> <p>JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension </p> <p>WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension </p> <p>EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.</p> </blockquote>
{ "question_id": 1594667, "question_date": "2009-10-20T13:38:28.067Z", "question_score": 608, "tags": "java|jakarta-ee|deployment", "answer_id": 1594723, "answer_date": "2009-10-20T13:45:25.783Z", "answer_score": 513 }
Please answer the following Stack Overflow question: Title: CSS '>' selector; what is it? <p>I've seen the "greater than" (<code>&gt;</code>) used in CSS code a few times, but I can't work out what it does. What does it do?</p>
<h2><code>&gt;</code> selects immediate children</h2> <p>For example, if you have nested divs like such:</p> <pre><code>&lt;div class='outer'&gt; &lt;div class="middle"&gt; &lt;div class="inner"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;div class="middle"&gt; &lt;div class="inner"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and you declare a css rule in your stylesheet like such:</p> <pre><code>.outer &gt; div { ... } </code></pre> <p>your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { border: 1px solid black; padding: 10px; } .outer &gt; div { border: 1px solid orange; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='outer'&gt; div.outer - This is the parent. &lt;div class="middle"&gt; div.middle - This is an immediate child of "outer". This will receive the orange border. &lt;div class="inner"&gt;div.inner - This is an immediate child of "middle". This will not receive the orange border.&lt;/div&gt; &lt;/div&gt; &lt;div class="middle"&gt; div.middle - This is an immediate child of "outer". This will receive the orange border. &lt;div class="inner"&gt;div.inner - This is an immediate child of "middle". This will not receive the orange border.&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p&gt;Without Words&lt;/p&gt; &lt;div class='outer'&gt; &lt;div class="middle"&gt; &lt;div class="inner"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;div class="middle"&gt; &lt;div class="inner"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Side note</h2> <p>If you, instead, had a space <code></code> between selectors instead of <code>&gt;</code>, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the <code>&gt;</code> does.</p> <p>NOTE: The <code>&gt;</code> selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.</p> <p>If you're looking into less-well-used CSS selectors, you may also want to look at <code>+</code>, <code>~</code>, and <code>[attr]</code> selectors, all of which can be very useful.</p> <p><a href="http://www.quirksmode.org/css/selectors/">This page</a> has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.</p>
{ "question_id": 4459821, "question_date": "2010-12-16T10:39:47.480Z", "question_score": 608, "tags": "css|css-selectors", "answer_id": 4459872, "answer_date": "2010-12-16T10:44:29.223Z", "answer_score": 808 }
Please answer the following Stack Overflow question: Title: Is there a quick change tabs function in Visual Studio Code? <p>The current function of giving me a dropdown option of which tab to choose is just so annoying. Is there a possibility to remove it so the tabs would work like in some modern web browser.</p>
<p>By default, <kbd>Ctrl</kbd>+<kbd>Tab</kbd> in Visual Studio Code cycles through tabs in order of most recently used. This is confusing because it depends on hidden state.</p> <p>Web browsers cycle through tabs in visible order. This is much more intuitive. </p> <p>To achieve this in Visual Studio Code, you have to edit <code>keybindings.json</code>. Use the Command Palette with <kbd>CTRL+SHIFT+P</kbd>, enter "Preferences: Open Keyboard Shortcuts (JSON)", and hit <kbd>Enter</kbd>. </p> <p>Then add to the end of the file:</p> <pre class="lang-json prettyprint-override"><code>[ // ... { "key": "ctrl+tab", "command": "workbench.action.nextEditor" }, { "key": "ctrl+shift+tab", "command": "workbench.action.previousEditor" } ] </code></pre> <p>Alternatively, to only cycle through tabs of the current window/split view, you can use:</p> <pre class="lang-json prettyprint-override"><code>[ { "key": "ctrl+tab", "command": "workbench.action.nextEditorInGroup" }, { "key": "ctrl+shift+tab", "command": "workbench.action.previousEditorInGroup" } ] </code></pre> <hr> <p>Alternatively, you can use <kbd>Ctrl</kbd>+<kbd>PageDown</kbd> (Windows) or <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>Right</kbd> (Mac).</p>
{ "question_id": 38957302, "question_date": "2016-08-15T14:41:57.970Z", "question_score": 608, "tags": "visual-studio-code|vscode-settings", "answer_id": 38978993, "answer_date": "2016-08-16T15:33:26.177Z", "answer_score": 1062 }
Please answer the following Stack Overflow question: Title: How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name? <p>Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="https://stackoverflow.com/a/19799236/8479">https://stackoverflow.com/a/19799236/8479</a></p> <hr> <p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p> <p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p> <p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p> <p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p> <pre><code>rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem Now use the timestamp by in a new ZIP file name. "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code </code></pre> <p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p> <p>I'm using Windows Server 2003 and Windows&nbsp;XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p>
<p>See <em><a href="http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/" rel="noreferrer">Windows Batch File (.bat) to get current date in MMDDYYYY format</a></em>:</p> <pre><code>@echo off For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b) echo %mydate%_%mytime% </code></pre> <p>If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:</p> <pre><code>For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b) </code></pre> <blockquote> <p>C:> .\date.bat <br /> 2008-10-14_0642</p> </blockquote> <p>If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:</p> <pre><code>@echo off for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^&gt;NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6% echo Local date is [%ldt%] </code></pre> <blockquote> <p>C:>test.cmd<br /> Local date is [2012-06-19 10:23:47.048]</p> </blockquote>
{ "question_id": 203090, "question_date": "2008-10-14T22:25:34.303Z", "question_score": 607, "tags": "windows|datetime|batch-file|cmd", "answer_id": 203116, "answer_date": "2008-10-14T22:36:53.733Z", "answer_score": 718 }
Please answer the following Stack Overflow question: Title: How to iterate (keys, values) in JavaScript? <p>I have a dictionary that has the format of</p> <pre><code>dictionary = {0: {object}, 1:{object}, 2:{object}} </code></pre> <p>How can I iterate through this dictionary by doing something like</p> <pre><code>for ((key, value) in dictionary) { //Do stuff where key would be 0 and value would be the object } </code></pre>
<h1>tl;dr</h1> <ol> <li>In ECMAScript 2017, just call <code>Object.entries(yourObj)</code>.</li> <li>In ECMAScript 2015, it is possible with <code>Map</code>s.</li> <li>In ECMAScript 5, it is not possible.</li> </ol> <h1>ECMAScript 2017</h1> <p>ECMAScript 2017 introduced a new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries" rel="noreferrer"><code>Object.entries</code></a> function. You can use this to iterate the object as you wanted.</p> <pre><code>'use strict'; const object = {'a': 1, 'b': 2, 'c' : 3}; for (const [key, value] of Object.entries(object)) { console.log(key, value); } </code></pre> <h2>Output</h2> <pre><code>a 1 b 2 c 3 </code></pre> <hr /> <h1>ECMAScript 2015</h1> <p>In ECMAScript 2015, there is not <code>Object.entries</code> but you can use <code>Map</code> objects instead and iterate over them with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries" rel="noreferrer"><code>Map.prototype.entries</code></a>. Quoting the example from that page,</p> <pre><code>var myMap = new Map(); myMap.set(&quot;0&quot;, &quot;foo&quot;); myMap.set(1, &quot;bar&quot;); myMap.set({}, &quot;baz&quot;); var mapIter = myMap.entries(); console.log(mapIter.next().value); // [&quot;0&quot;, &quot;foo&quot;] console.log(mapIter.next().value); // [1, &quot;bar&quot;] console.log(mapIter.next().value); // [Object, &quot;baz&quot;] </code></pre> <p>Or iterate with <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><code>for..of</code></a>, like this</p> <pre><code>'use strict'; var myMap = new Map(); myMap.set(&quot;0&quot;, &quot;foo&quot;); myMap.set(1, &quot;bar&quot;); myMap.set({}, &quot;baz&quot;); for (const entry of myMap.entries()) { console.log(entry); } </code></pre> <h2>Output</h2> <pre><code>[ '0', 'foo' ] [ 1, 'bar' ] [ {}, 'baz' ] </code></pre> <p>Or</p> <pre><code>for (const [key, value] of myMap.entries()) { console.log(key, value); } </code></pre> <h2>Output</h2> <pre><code>0 foo 1 bar {} baz </code></pre> <hr /> <h1>ECMAScript 5:</h1> <p>No, it's not possible with objects.</p> <p>You should either iterate with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for..in</code></a>, or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys</code></a>, like this</p> <pre><code>for (var key in dictionary) { // check if the property/key is defined in the object itself, not in parent if (dictionary.hasOwnProperty(key)) { console.log(key, dictionary[key]); } } </code></pre> <p><strong>Note:</strong> The <code>if</code> condition above is necessary only if you want to iterate over the properties which are the <code>dictionary</code> object's very own. Because <code>for..in</code> will iterate through all the inherited enumerable properties.</p> <p>Or</p> <pre><code>Object.keys(dictionary).forEach(function(key) { console.log(key, dictionary[key]); }); </code></pre>
{ "question_id": 34913675, "question_date": "2016-01-21T01:11:53.807Z", "question_score": 607, "tags": "javascript|dictionary|object|iterator", "answer_id": 34913701, "answer_date": "2016-01-21T01:14:53.163Z", "answer_score": 857 }
Please answer the following Stack Overflow question: Title: Twitter Bootstrap Form File Element Upload Button <p>Why isn't there a fancy file element upload button for twitter bootstrap? It would be sweet if the blue primary button was implemented for the upload button. Is it even possible to finesse the upload button using CSS? (seems like a native browser element that can't be manipulated) </p>
<p>Here's a solution for Bootstrap 3, 4, and 5.</p> <p>To make a functional file input control that looks like a button, you only need HTML:</p> <p><strong>HTML</strong></p> <pre><code>&lt;label class=&quot;btn btn-default&quot;&gt; Browse &lt;input type=&quot;file&quot; hidden&gt; &lt;/label&gt; </code></pre> <p>This works in all modern browsers, including IE9+. If you need support for old IE as well, please use the legacy approach shown below.</p> <p>This techniques relies on the HTML5 <code>hidden</code> attribute. Bootstrap 4 uses the following CSS to shim this feature in unsupportive browsers. You may need to add if you're using Bootstrap 3.</p> <pre><code>[hidden] { display: none !important; } </code></pre> <hr /> <h2>Legacy approach for old IE</h2> <p>If you need support for IE8 and below, use the following HTML/CSS:</p> <p><strong>HTML</strong></p> <pre><code>&lt;span class=&quot;btn btn-default btn-file&quot;&gt; Browse &lt;input type=&quot;file&quot;&gt; &lt;/span&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.btn-file { position: relative; overflow: hidden; } .btn-file input[type=file] { position: absolute; top: 0; right: 0; min-width: 100%; min-height: 100%; font-size: 100px; text-align: right; filter: alpha(opacity=0); opacity: 0; outline: none; background: white; cursor: inherit; display: block; } </code></pre> <p>Note that old IE doesn't trigger the file input when you click on a <code>&lt;label&gt;</code>, so the The CSS &quot;bloat&quot; does a couple things to work around that:</p> <ul> <li>Makes the file input span the full width/height of the surrounding <code>&lt;span&gt;</code></li> <li>Makes the file input invisible</li> </ul> <hr /> <h2>Feedback &amp; Additional Reading</h2> <p>I've posted more details about this method, as well as examples for how to show the user which/how many files are selected:</p> <p><a href="https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/" rel="noreferrer">https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/</a></p>
{ "question_id": 11235206, "question_date": "2012-06-27T21:41:56.507Z", "question_score": 607, "tags": "css|forms|twitter-bootstrap|input-type-file", "answer_id": 18164555, "answer_date": "2013-08-10T17:30:55.270Z", "answer_score": 1021 }
Please answer the following Stack Overflow question: Title: How to download a file with Node.js (without using third-party libraries)? <p>How do I download a file with Node.js <strong>without using third-party libraries</strong>?</p> <p>I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory.</p>
<p>You can create an HTTP <code>GET</code> request and pipe its <code>response</code> into a writable file stream:</p> <pre><code>const http = require('http'); // or 'https' for https:// URLs const fs = require('fs'); const file = fs.createWriteStream(&quot;file.jpg&quot;); const request = http.get(&quot;http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg&quot;, function(response) { response.pipe(file); // after download completed close filestream file.on(&quot;finish&quot;, () =&gt; { file.close(); console.log(&quot;Download Completed&quot;); }); }); </code></pre> <p>If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like <a href="https://github.com/visionmedia/commander.js/" rel="noreferrer">Commander</a>.</p> <p>More detailed explanation in <a href="https://sebhastian.com/nodejs-download-file/" rel="noreferrer">https://sebhastian.com/nodejs-download-file/</a></p>
{ "question_id": 11944932, "question_date": "2012-08-14T02:21:44.943Z", "question_score": 607, "tags": "javascript|node.js|download|fs", "answer_id": 11944984, "answer_date": "2012-08-14T02:28:16.983Z", "answer_score": 819 }
Please answer the following Stack Overflow question: Title: How do I get the directory from a file's full path? <p>What is the simplest way to get the directory that a file is in? I'm using this to set a working directory.</p> <pre><code>string filename = @"C:\MyDirectory\MyFile.bat"; </code></pre> <p>In this example, I should get "C:\MyDirectory".</p>
<p>If you've definitely got an absolute path, use <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx" rel="noreferrer"><code>Path.GetDirectoryName(path)</code></a>.</p> <p>If you might only get a relative name, use <code>new FileInfo(path).Directory.FullName</code>.</p> <p>Note that <code>Path</code> and <code>FileInfo</code> are both found in the namespace <code>System.IO</code>.</p>
{ "question_id": 674479, "question_date": "2009-03-23T17:49:13.673Z", "question_score": 607, "tags": "c#|.net|file|file-io|directory", "answer_id": 674495, "answer_date": "2009-03-23T17:52:23.573Z", "answer_score": 954 }
Please answer the following Stack Overflow question: Title: How do I programmatically determine operating system in Java? <p>I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?</p>
<p>You can use:</p> <pre><code>System.getProperty("os.name") </code></pre> <p>P.S. You may find this code useful:</p> <pre><code>class ShowProperties { public static void main(String[] args) { System.getProperties().list(System.out); } } </code></pre> <p>All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)</p>
{ "question_id": 228477, "question_date": "2008-10-23T03:47:05.663Z", "question_score": 607, "tags": "java|operating-system", "answer_id": 228481, "answer_date": "2008-10-23T03:48:47.127Z", "answer_score": 715 }
Please answer the following Stack Overflow question: Title: How to declare global variables in Android? <p>I am creating an application which requires login. I created the main and the login activity.</p> <p>In the main activity <code>onCreate</code> method I added the following condition:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ... loadSettings(); if(strSessionString == null) { login(); } ... } </code></pre> <p>The <code>onActivityResult</code> method which is executed when the login form terminates looks like this:</p> <pre><code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(SHOW_SUBACTICITY_LOGIN): { if(resultCode == Activity.RESULT_OK) { strSessionString = data.getStringExtra(Login.SESSIONSTRING); connectionAvailable = true; strUsername = data.getStringExtra(Login.USERNAME); } } } </code></pre> <p>The problem is the login form sometimes appears twice (the <code>login()</code> method is called twice) and also when the phone keyboard slides the login form appears again and I guess the problem is the variable <code>strSessionString</code>.</p> <p>Does anyone know how to set the variable global in order to avoid login form appearing after the user already successfully authenticates?</p>
<p>I wrote this answer back in '09 when Android was relatively new, and there were many not well established areas in Android development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagreement I have with the use of Singletons rather than subclassing Application. Read it at your own risk.</p> <p><strong>ORIGINAL ANSWER:</strong> </p> <p>The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.</p> <p>As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.</p> <p>The way to do this is to create your own subclass of <a href="http://developer.android.com/reference/android/app/Application.html" rel="noreferrer">android.app.Application</a>, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any <code>context</code> using the <code>Context.getApplicationContext()</code> method (<code>Activity</code> also provides a method <code>getApplication()</code> which has the exact same effect). Following is an extremely simplified example, with caveats to follow:</p> <pre><code>class MyApp extends Application { private String myState; public String getState(){ return myState; } public void setState(String s){ myState = s; } } class Blah extends Activity { @Override public void onCreate(Bundle b){ ... MyApp appState = ((MyApp)getApplicationContext()); String state = appState.getState(); ... } } </code></pre> <p>This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).</p> <p>Something to note from the example above; suppose we had instead done something like:</p> <pre><code>class MyApp extends Application { private String myState = /* complicated and slow initialization */; public String getState(){ return myState; } } </code></pre> <p>Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) will be performed every time Application is instantiated! You may think, well, this is only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it is entirely possible for your process to be instantiated -just- to handle a background broadcast event. If your broadcast processing has no need for this state you have potentially just done a whole series of complicated and slow operations for nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated way of using Application which makes more sense for anything but the simplest of uses:</p> <pre><code>class MyApp extends Application { private MyStateManager myStateManager = new MyStateManager(); public MyStateManager getStateManager(){ return myStateManager ; } } class MyStateManager { MyStateManager() { /* this should be fast */ } String getState() { /* if necessary, perform blocking calls here */ /* make sure to deal with any multithreading/synchronicity issues */ ... return state; } } class Blah extends Activity { @Override public void onCreate(Bundle b){ ... MyStateManager stateManager = ((MyApp)getApplicationContext()).getStateManager(); String state = stateManager.getState(); ... } } </code></pre> <p>While I prefer Application subclassing to using singletons here as the more elegant solution, I would rather developers use singletons if really necessary over not thinking at all through the performance and multithreading implications of associating state with the Application subclass.</p> <p><strong>NOTE 1:</strong> Also as anticafe commented, in order to correctly tie your Application override to your application a tag is necessary in the manifest file. Again, see the Android docs for more info. An example:</p> <pre><code>&lt;application android:name="my.application.MyApp" android:icon="..." android:label="..."&gt; &lt;/application&gt; </code></pre> <p><strong>NOTE 2:</strong> user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would interact with my solution. If someone does have an answer to this, I am willing to credit them and put the information in this post for maximum visibility.</p> <p><strong>ADDENDUM:</strong></p> <p>As some people have noted, this is <strong>not</strong> a solution for <strong>persistent</strong> state, something I perhaps should have emphasized more in the original answer. I.e. this is not meant to be a solution for saving user or other information that is meant to be persisted across application lifetimes. Thus, I consider most criticism below related to Applications being killed at any time, etc..., moot, as anything that ever needed to be persisted to disk should not be stored through an Application subclass. It is meant to be a solution for storing temporary, easily re-creatable application state (whether a user is logged in for example) and components which are single instance (application network manager for example) (<strong>NOT</strong> singleton!) in nature.</p> <p>Dayerman has been kind enough to point out an interesting <a href="https://plus.google.com/u/0/117230458394250799679/posts/DsfpW51Vvow" rel="noreferrer">conversation with Reto Meier and Dianne Hackborn</a> in which use of Application subclasses is discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn't see it at the time. Because of Reto and Dianne's roles in maintaining the Android platform, I cannot in good faith recommend ignoring their advice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over Application subclasses. In my disagreement I will be making use of concepts best explained in <a href="https://softwareengineering.stackexchange.com/a/40610/98638">this StackExchange explanation of the Singleton design pattern</a>, so that I do not have to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:</p> <p>Dianne states, "There is no reason to subclass from Application. It is no different than making a singleton..." This first claim is incorrect. There are two main reasons for this. 1) The Application class provides a better lifetime guarantee for an application developer; it is guaranteed to have the lifetime of the application. A singleton is not EXPLICITLY tied to the lifetime of the application (although it is effectively). This may be a non-issue for your average application developer, but I would argue this is exactly the type of contract the Android API should be offering, and it provides much more flexibility to the Android system as well, by minimizing the lifetime of associated data. 2) The Application class provides the application developer with a single instance holder for state, which is very different from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.</p> <p>Dianne continues, "...just likely to be something you regret in the future as you find your Application object becoming this big tangled mess of what should be independent application logic." This is certainly not incorrect, but this is not a reason for choosing Singleton over Application subclass. None of Diane's arguments provide a reason that using a Singleton is better than an Application subclass, all she attempts to establish is that using a Singleton is no worse than an Application subclass, which I believe is false.</p> <p>She continues, "And this leads more naturally to how you should be managing these things -- initializing them on demand." This ignores the fact that there is no reason you cannot initialize on demand using an Application subclass as well. Again there is no difference.</p> <p>Dianne ends with "The framework itself has tons and tons of singletons for all the little shared data it maintains for the app, such as caches of loaded resources, pools of objects, etc. It works great." I am not arguing that using Singletons cannot work fine or are not a legitimate alternative. I am arguing that Singletons do not provide as strong a contract with the Android system as using an Application subclass, and further that using Singletons generally points to inflexible design, which is not easily modified, and leads to many problems down the road. IMHO, the strong contract the Android API offers to developer applications is one of the most appealing and pleasing aspects of programming with Android, and helped lead to early developer adoption which drove the Android platform to the success it has today. Suggesting using Singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android framework.</p> <p>Dianne has commented below as well, mentioning an additional downside to using Application subclasses, they may encourage or make it easier to write less performance code. This is very true, and I have edited this answer to emphasize the importance of considering perf here, and taking the correct approach if you're using Application subclassing. As Dianne states, it is important to remember that your Application class will be instantiated every time your process is loaded (could be multiple times at once if your application runs in multiple processes!) even if the process is only being loaded for a background broadcast event. It is therefore important to use the Application class more as a repository for pointers to shared components of your application rather than as a place to do any processing!</p> <p>I leave you with the following list of downsides to Singletons, as stolen from the earlier StackExchange link:</p> <ul> <li>Inability to use abstract or interface classes;</li> <li>Inability to subclass;</li> <li>High coupling across the application (difficult to modify);</li> <li>Difficult to test (can't fake/mock in unit tests);</li> <li>Difficult to parallelize in the case of mutable state (requires extensive locking);</li> </ul> <p>and add my own:</p> <ul> <li>Unclear and unmanageable lifetime contract unsuited for Android (or most other) development;</li> </ul>
{ "question_id": 708012, "question_date": "2009-04-02T01:54:30.160Z", "question_score": 607, "tags": "android|singleton|global-variables|state", "answer_id": 708317, "answer_date": "2009-04-02T04:34:27.543Z", "answer_score": 965 }
Please answer the following Stack Overflow question: Title: UTF-8, UTF-16, and UTF-32 <p>What are the differences between UTF-8, UTF-16, and UTF-32?</p> <p>I understand that they will all store Unicode, and that each uses a different number of bytes to represent a character. Is there an advantage to choosing one over the other?</p>
<p>UTF-8 has an advantage in the case where ASCII characters represent the majority of characters in a block of text, because UTF-8 encodes these into 8 bits (like ASCII). It is also advantageous in that a UTF-8 file containing only ASCII characters has the same encoding as an ASCII file.</p> <p>UTF-16 is better where ASCII is not predominant, since it uses 2 bytes per character, primarily. UTF-8 will start to use 3 or more bytes for the higher order characters where UTF-16 remains at just 2 bytes for most characters.</p> <p>UTF-32 will cover all possible characters in 4 bytes. This makes it pretty bloated. I can't think of any advantage to using it.</p>
{ "question_id": 496321, "question_date": "2009-01-30T17:05:59.810Z", "question_score": 607, "tags": "unicode|utf-8|utf-16|utf|utf-32", "answer_id": 496361, "answer_date": "2009-01-30T17:15:19.197Z", "answer_score": 476 }
Please answer the following Stack Overflow question: Title: Git - Difference Between 'assume-unchanged' and 'skip-worktree' <p>I have local changes to a file that I don't want to commit to my repository. It is a configuration file for building the application on a server, but I want to build locally with different settings. Naturally, the file always shows up when I do 'git status' as something to be staged. I would like to hide this particular change and not commit it. I won't make any other changes to the file.</p> <p>To clarify, using .gitignore is not what I want since that only prevents new files from being added. I want to ignore changes to a file already in the repository.</p> <p>After some digging around, I see 2 options: <code>assume-unchanged</code> and <code>skip-worktree</code>. A previous question <a href="https://stackoverflow.com/questions/6138076/git-assume-unchanged-vs-skip-worktree">here</a> talks about them but doesn't really explain their differences.</p> <p>How are the two commands different? Why would someone use one or the other?</p>
<p>You want <code>skip-worktree</code>.</p> <p><code>assume-unchanged</code> is designed for cases where it is expensive to check whether a group of files have been modified; when you set the bit, <code>git</code> (of course) assumes the files corresponding to that portion of the index have not been modified in the working copy. So it avoids a mess of <code>stat</code> calls. This bit is lost whenever the file's entry in the index changes (so, when the file is changed upstream).</p> <p><code>skip-worktree</code> is more than that: even where <code>git</code> <em>knows</em> that the file has been modified (or needs to be modified by a <code>reset --hard</code> or the like), it will pretend it has not been, using the version from the index instead. This persists until the index is discarded.</p> <p>There is a good summary of the ramifications of this difference and the typical use cases here: <a href="http://fallengamer.livejournal.com/93321.html" rel="noreferrer">http://fallengamer.livejournal.com/93321.html</a> .</p> <p>From that article:</p> <ul> <li><code>--assume-unchanged</code> assumes that a developer <strong>shouldn’t</strong> change a file. This flag is meant for <strong>improving performance</strong> for not-changing folders like SDKs. </li> <li><code>--skip-worktree</code> is useful when you instruct git not to touch a specific file ever because developers <strong>should</strong> change it. For example, if the main repository upstream hosts some production-ready <strong>configuration files</strong> and you don’t want to accidentally commit changes to those files, <code>--skip-worktree</code> is exactly what you want.</li> </ul>
{ "question_id": 13630849, "question_date": "2012-11-29T17:00:25.543Z", "question_score": 607, "tags": "git|git-index", "answer_id": 13631525, "answer_date": "2012-11-29T17:39:42.173Z", "answer_score": 869 }
Please answer the following Stack Overflow question: Title: Split string on whitespace in Python <p>I'm looking for the Python equivalent of </p> <pre><code>String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] </code></pre>
<p>The <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="noreferrer"><code>str.split()</code></a> method without an argument splits on whitespace:</p> <pre><code>&gt;&gt;&gt; &quot;many fancy word \nhello \thi&quot;.split() ['many', 'fancy', 'word', 'hello', 'hi'] </code></pre>
{ "question_id": 8113782, "question_date": "2011-11-13T18:46:11.853Z", "question_score": 606, "tags": "python|regex|string|split|whitespace", "answer_id": 8113787, "answer_date": "2011-11-13T18:46:54.657Z", "answer_score": 1115 }
Please answer the following Stack Overflow question: Title: SHA-1 fingerprint of keystore certificate <p>Is the method for getting an SHA-1 fingerprint the same as the method of getting the fingerprint? Previously, I was running this command:</p> <p><img src="https://i.stack.imgur.com/SRb3A.jpg" alt="Windows Command Prompt running keytool.exe" /></p> <p>It's not clear to me if the result I'm getting is the SHA-1 fingerprint. Can somebody clarify this?</p>
<p>Follow <a href="http://android-er.blogspot.in/2012/12/displaying-sha1-certificate-fingerprint.html" rel="noreferrer">this</a> tutorial for creating SHA1 fingerprint for Google Map v2</p> <p>For Debug mode:</p> <pre><code>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android </code></pre> <p>for Release mode:</p> <pre><code>keytool -list -v -keystore {keystore_name} -alias {alias_name} </code></pre> <p>example:</p> <pre><code>keytool -list -v -keystore C:\Users\MG\Desktop\test.jks -alias test </code></pre> <blockquote> <p>On windows, when <strong>keytool command is not found</strong>, Go to your installed JDK Directory e.g. <code>&lt;YourJDKPath&gt;\Java\jdk1.8.0_231\bin\</code>, open command line and try the above commands for debug/release mode.</p> </blockquote> <p>Another way of getting your SHA1 OR SHA-256 use <code>./gradlew signingReport</code></p> <p>For more detailed info visit <a href="https://developers.google.com/android/guides/client-auth#using_gradles_signing_report" rel="noreferrer">Using Gradle's Signing Report</a></p>
{ "question_id": 15727912, "question_date": "2013-03-31T08:55:13.833Z", "question_score": 606, "tags": "android|google-maps|google-plus|sha1|android-keystore", "answer_id": 15727931, "answer_date": "2013-03-31T08:59:06.633Z", "answer_score": 1141 }
Please answer the following Stack Overflow question: Title: How can I remove a package from Laravel using PHP Composer? <p>What is the correct way to remove a package from Laravel using PHP Composer?</p> <p>So far I've tried:</p> <ol> <li>Remove declaration from file <em>composer.json</em> (in the &quot;require&quot; section)</li> <li>Remove any <em>class aliases</em> from file <em>app.php</em></li> <li>Remove any references to the package from my code :-)</li> <li>Run <code>composer update</code></li> <li>Run <code>composer dump-autoload</code></li> </ol> <p>None of these options are working! What am I missing?</p>
<h2>Composer 1.x and 2.x</h2> <p>Running the following command will remove the package from vendor (or wherever you install packages), <em>composer.json</em> and <em>composer.lock</em>. Change vendor/package appropriately.</p> <pre><code>composer remove vendor/package </code></pre> <p>Obviously you'll need to remove references to that package within your app.</p> <p>I'm currently running the following version of Composer:</p> <pre><code>Composer version 1.0-dev (7b13507dd4d3b93578af7d83fbf8be0ca686f4b5) 2014-12-11 21:52:29 </code></pre> <h2>Documentation</h2> <p><a href="https://getcomposer.org/doc/03-cli.md#remove" rel="noreferrer">https://getcomposer.org/doc/03-cli.md#remove</a></p> <h3>Updates</h3> <ul> <li>26/10/2020 - Updated answer to assert command works for v1.x and v2.x of Composer</li> </ul>
{ "question_id": 23126562, "question_date": "2014-04-17T06:59:26.300Z", "question_score": 606, "tags": "laravel|laravel-4|package|composer-php|uninstallation", "answer_id": 27440198, "answer_date": "2014-12-12T09:09:08.087Z", "answer_score": 964 }
Please answer the following Stack Overflow question: Title: Selenium using Python - Geckodriver executable needs to be in PATH <p>I'm new to programming and started with Python about two months ago and am going over Sweigart's <em>Automate the Boring Stuff with Python</em> text. I'm using <a href="https://en.wikipedia.org/wiki/IDLE" rel="noreferrer">IDLE</a> and already installed the Selenium module and the Firefox browser.</p> <p>Whenever I tried to run the webdriver function, I get this:</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() </code></pre> <p>Exception:</p> <pre class="lang-none prettyprint-override"><code>Exception ignored in: &lt;bound method Service.__del__ of &lt;selenium.webdriver.firefox.service.Service object at 0x00000249C0DA1080&gt;&gt; Traceback (most recent call last): File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 163, in __del__ self.stop() File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 135, in stop if self.process is None: AttributeError: 'Service' object has no attribute 'process' Exception ignored in: &lt;bound method Service.__del__ of &lt;selenium.webdriver.firefox.service.Service object at 0x00000249C0E08128&gt;&gt; Traceback (most recent call last): File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 163, in __del__ self.stop() File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 135, in stop if self.process is None: AttributeError: 'Service' object has no attribute 'process' Traceback (most recent call last): File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 64, in start stdout=self.log_file, stderr=self.log_file) File &quot;C:\Python\Python35\lib\subprocess.py&quot;, line 947, in __init__ restore_signals, start_new_session) File &quot;C:\Python\Python35\lib\subprocess.py&quot;, line 1224, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified </code></pre> <p>During handling of the above exception, another exception occurred:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;&lt;pyshell#11&gt;&quot;, line 1, in &lt;module&gt; browser = webdriver.Firefox() File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py&quot;, line 135, in __init__ self.service.start() File &quot;C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py&quot;, line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. </code></pre> <p>I think I need to set the path for <code>geckodriver</code>, but I am not sure how, so how would I do this?</p>
<blockquote> <p>selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.</p> </blockquote> <p><a href="https://www.google.co.in/amp/www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/amp/?client=ms-android-motorola" rel="noreferrer">First of all you will need to download latest executable geckodriver from here to run latest Firefox using Selenium</a></p> <p>Actually, the Selenium client bindings tries to locate the <code>geckodriver</code> executable from the system <code>PATH</code>. You will need to add the directory containing the executable to the system path.</p> <ul> <li><p>On Unix systems you can do the following to append it to your system’s search path, if you’re using a Bash-compatible shell:</p> <pre><code> export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/step </code></pre> </li> <li><p>On Windows you will need to update the <strong>Path system variable to add the full directory path to the executable geckodriver</strong> <a href="https://www.google.co.in/amp/www.howtogeek.com/118594/how-to-edit-your-system-path-for-easy-command-line-access/amp/?client=ms-android-motorola" rel="noreferrer">manually</a> or <a href="https://www.windows-commandline.com/set-path-command-line/" rel="noreferrer">command line</a>** (don't forget to restart your system after adding executable geckodriver into system PATH to take effect)**. The principle is the same as on Unix.</p> </li> </ul> <p>Now you can run your code same as you're doing as below :-</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() </code></pre> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line</p> </blockquote> <p>The exception clearly states you have installed Firefox some other location while Selenium is trying to find Firefox and launch from the default location, but it couldn't find it. You need to provide explicitly Firefox installed binary location to launch Firefox as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('path/to/installed firefox binary') browser = webdriver.Firefox(firefox_binary=binary) </code></pre> <p><a href="https://github.com/mozilla/geckodriver/releases" rel="noreferrer">https://github.com/mozilla/geckodriver/releases</a></p> <p>For Windows:</p> <p>Download the file from GitHub, extract it, and paste it in Python file. It worked for me.</p> <p><a href="https://github.com/mozilla/geckodriver/releases" rel="noreferrer">https://github.com/mozilla/geckodriver/releases</a></p> <p>For me, my path path is:</p> <pre><code>C:\Users\MYUSERNAME\AppData\Local\Programs\Python\Python39 </code></pre>
{ "question_id": 40208051, "question_date": "2016-10-23T21:39:13.953Z", "question_score": 606, "tags": "python|selenium|firefox|selenium-firefoxdriver|geckodriver", "answer_id": 40208762, "answer_date": "2016-10-23T23:16:01.527Z", "answer_score": 444 }
Please answer the following Stack Overflow question: Title: How to do associative array/hashing in JavaScript <p>I need to store some statistics using JavaScript in a way like I'd do it in C#: </p> <pre><code>Dictionary&lt;string, int&gt; statistics; statistics["Foo"] = 10; statistics["Goo"] = statistics["Goo"] + 1; statistics.Add("Zoo", 1); </code></pre> <p>Is there an <code>Hashtable</code> or something like <code>Dictionary&lt;TKey, TValue&gt;</code> in JavaScript?<br> How could I store values in such a way?</p>
<p>Use <a href="http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/" rel="noreferrer">JavaScript objects as associative arrays</a>.</p> <blockquote> <p>Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.</p> </blockquote> <p>Create an object with</p> <pre><code>var dictionary = {}; </code></pre> <blockquote> <p>JavaScript allows you to add properties to objects by using the following syntax:</p> </blockquote> <pre><code>Object.yourProperty = value; </code></pre> <p>An alternate syntax for the same is:</p> <pre><code>Object[&quot;yourProperty&quot;] = value; </code></pre> <p>If you can, also create key-to-value object maps with the following syntax:</p> <pre><code>var point = { x:3, y:2 }; point[&quot;x&quot;] // returns 3 point.y // returns 2 </code></pre> <blockquote> <p>You can iterate through an associative array using the for..in loop construct as follows</p> </blockquote> <pre><code>for(var key in Object.keys(dict)){ var value = dict[key]; /* use key/value for intended purpose */ } </code></pre>
{ "question_id": 1208222, "question_date": "2009-07-30T17:52:56.350Z", "question_score": 606, "tags": "javascript|dictionary|hashtable", "answer_id": 1208272, "answer_date": "2009-07-30T18:01:12.183Z", "answer_score": 592 }
Please answer the following Stack Overflow question: Title: How do I uninstall a Windows service if the files do not exist anymore? <p>How do I uninstall a .NET Windows Service if the service files do not exist anymore?</p> <p>I installed a .NET Windows Service using InstallUtil. I have since deleted the files but forgot to run</p> <pre><code> InstallUtil /u </code></pre> <p>first, so the service is still listed in the Services MMC.</p> <p>Do I have to go into the registry? Or is there a better way?</p>
<p>You have at least three options. I have presented them in order of usage preference.</p> <p><strong>Method 1</strong> - You can use the <a href="http://support.microsoft.com/kb/251192" rel="noreferrer">SC tool</a> (Sc.exe) included in the Resource Kit. (included with Windows 7/8)</p> <p>Open a Command Prompt and enter</p> <pre><code>sc delete &lt;service-name&gt; </code></pre> <p>Tool help snippet follows:</p> <pre><code>DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. delete----------Deletes a service (from the registry). </code></pre> <p><strong>Method 2</strong> - use delserv</p> <p><a href="http://support.microsoft.com/kb/927229" rel="noreferrer">Download</a> and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.</p> <p><strong>Method 3</strong> - manually delete registry entries <strong>(Note that this backfires in Windows 7/8)</strong></p> <p>Windows services are registered under the following registry key.</p> <pre><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services </code></pre> <p>Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)</p>
{ "question_id": 197876, "question_date": "2008-10-13T14:59:03.923Z", "question_score": 606, "tags": "windows|windows-services|installation", "answer_id": 197941, "answer_date": "2008-10-13T15:14:12.770Z", "answer_score": 1196 }
Please answer the following Stack Overflow question: Title: CSS text-overflow in a table cell? <p>I want to use CSS <code>text-overflow</code> in a table cell, such that if the text is too long to fit on one line, it will clip with an ellipsis instead of wrapping to multiple lines. Is this possible?</p> <p>I tried this:</p> <pre><code>td { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } </code></pre> <p>But the <code>white-space: nowrap</code> seems to make the text (and its cell) continually expand out to the right, pushing the total width of the table beyond the width of its container. Without it, however, the text continues to wrap to multiple lines when it hits the edge of the cell.</p>
<p>To clip text with an ellipsis when it overflows a table cell, you will need to set the <code>max-width</code> CSS property on each <code>td</code> class for the overflow to work. No extra layout <code>div</code> elements are required:</p> <pre><code>td { max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } </code></pre> <p>For responsive layouts; use the <code>max-width</code> CSS property to specify the effective minimum width of the column, or just use <code>max-width: 0;</code> for unlimited flexibility. Also, the containing table will need a specific width, typically <code>width: 100%;</code>, and the columns will typically have their width set as percentage of the total width</p> <pre><code>table {width: 100%;} td { max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } td.column_a {width: 30%;} td.column_b {width: 70%;} </code></pre> <p>Historical: For IE 9 (or less) you need to have this in your HTML, to fix an IE-specific rendering issue</p> <pre><code>&lt;!--[if IE]&gt; &lt;style&gt; table {table-layout: fixed; width: 100px;} &lt;/style&gt; &lt;![endif]--&gt; </code></pre>
{ "question_id": 9789723, "question_date": "2012-03-20T15:27:12.387Z", "question_score": 606, "tags": "css|overflow", "answer_id": 11877033, "answer_date": "2012-08-09T04:58:33.497Z", "answer_score": 1093 }
Please answer the following Stack Overflow question: Title: What does ^M character mean in Vim? <p>I keep getting <code>^M</code> character in my vimrc and it breaks my configuration. </p>
<p>Unix uses 0xA for a newline character. Windows uses a combination of two characters: 0xD 0xA. 0xD is the carriage return character. <code>^M</code> happens to be the way vim displays 0xD (0x0D = 13, M is the 13th letter in the English alphabet).</p> <p>You can remove all the <code>^M</code> characters by running the following: </p> <pre><code>:%s/^M//g </code></pre> <p>Where <code>^M</code> is entered by holding down <kbd>Ctrl</kbd> and typing <kbd>v</kbd> followed by <kbd>m</kbd>, and then releasing <kbd>Ctrl</kbd>. This is sometimes abbreviated as <code>^V^M</code>, but note that you must enter it as described in the previous sentence, rather than typing it out literally.</p> <p>This expression will replace all occurrences of <code>^M</code> with the empty string (i.e. nothing). I use this to get rid of <code>^M</code> in files copied from Windows to Unix (Solaris, Linux, OSX).</p>
{ "question_id": 5843495, "question_date": "2011-04-30T17:37:24.557Z", "question_score": 606, "tags": "unix|vim", "answer_id": 5843561, "answer_date": "2011-04-30T17:47:50.200Z", "answer_score": 651 }
Please answer the following Stack Overflow question: Title: Looping through array and removing items, without breaking for loop <p>I have the following for loop, and when I use <code>splice()</code> to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do this. The desire is to simply delete an item and keep on going. </p> <pre><code>for (i = 0, len = Auction.auctions.length; i &lt; len; i++) { auction = Auction.auctions[i]; Auction.auctions[i]['seconds'] --; if (auction.seconds &lt; 0) { Auction.auctions.splice(i, 1); } } </code></pre>
<p>The array is being re-indexed when you do a <code>.splice()</code>, which means you'll skip over an index when one is removed, and your cached <code>.length</code> is obsolete.</p> <p>To fix it, you'd either need to decrement <code>i</code> after a <code>.splice()</code>, or simply iterate in reverse...</p> <pre><code>var i = Auction.auctions.length while (i--) { ... if (...) { Auction.auctions.splice(i, 1); } } </code></pre> <p>This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.</p>
{ "question_id": 9882284, "question_date": "2012-03-27T01:44:07.757Z", "question_score": 606, "tags": "javascript|loops", "answer_id": 9882349, "answer_date": "2012-03-27T01:50:52.353Z", "answer_score": 1026 }
Please answer the following Stack Overflow question: Title: What does jQuery.fn mean? <p>What does the <code>fn</code> here mean?</p> <pre><code>jQuery.fn.jquery </code></pre>
<p>In jQuery, the <code>fn</code> property is just an alias to the <code>prototype</code> property.</p> <p>The <code>jQuery</code> identifier (or <code>$</code>) is just a <em>constructor function</em>, and all instances created with it, inherit from the constructor's prototype.</p> <p>A simple constructor function:</p> <pre><code>function Test() { this.a = 'a'; } Test.prototype.b = 'b'; var test = new Test(); test.a; // "a", own property test.b; // "b", inherited property </code></pre> <p>A simple structure that resembles the architecture of jQuery:</p> <pre><code>(function() { var foo = function(arg) { // core constructor // ensure to use the `new` operator if (!(this instanceof foo)) return new foo(arg); // store an argument for this example this.myArg = arg; //.. }; // create `fn` alias to `prototype` property foo.fn = foo.prototype = { init: function () {/*...*/} //... }; // expose the library window.foo = foo; })(); // Extension: foo.fn.myPlugin = function () { alert(this.myArg); return this; // return `this` for chainability }; foo("bar").myPlugin(); // alerts "bar" </code></pre>
{ "question_id": 4083351, "question_date": "2010-11-03T00:46:59.460Z", "question_score": 606, "tags": "javascript|jquery", "answer_id": 4083362, "answer_date": "2010-11-03T00:49:08.607Z", "answer_score": 878 }
Please answer the following Stack Overflow question: Title: What's the difference between HEAD, working tree and index, in Git? <p>Can someone tell me the difference between HEAD, working tree and index, in Git?</p> <p>From what I understand, they are all names for different branches. Is my assumption correct?</p> <p>I found this:</p> <blockquote> <p>A single git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the &quot;current&quot; or &quot;checked out&quot; branch), and HEAD points to that branch.</p> </blockquote> <p>Does this mean that HEAD and working tree are always the same?</p>
<p>A few other good references on those topics:</p> <ul> <li><a href="http://blog.osteele.com/2008/05/my-git-workflow/" rel="noreferrer">My Git Workflow</a></li> </ul> <p><a href="https://i.stack.imgur.com/cZkcV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cZkcV.jpg" alt="workflow" /></a></p> <blockquote> <p>I use the index as a <em>checkpoint</em>.</p> </blockquote> <blockquote> <p>When I'm about to make a change that might go awry — when I want to explore some direction that I'm not sure if I can follow through on or even whether it's a good idea, such as a conceptually demanding refactoring or changing a representation type — I checkpoint my work into the index.</p> <p>If this is the first change I've made since my last commit, then I can use the local repository as a checkpoint, but often I've got one conceptual change that I'm implementing as a set of little steps.<br /> I want to checkpoint after each step, but save the commit until I've gotten back to working, tested code.</p> </blockquote> <blockquote> <p>Notes:</p> <ol> <li><p>the <strong>workspace</strong> is the directory tree of (source) files that you see and edit.</p> </li> <li><p>The <strong>index</strong> is a single, large, binary file in <code>&lt;baseOfRepo&gt;/.git/index</code>, which lists all files in the current branch, their <em>sha1</em> checksums, time stamps and the file name -- it is not another directory with a copy of files in it.</p> </li> <li><p>The <strong>local repository</strong> is a hidden directory (<code>.git</code>) including an <code>objects</code> directory containing all versions of every file in the repo (local branches and copies of remote branches) as a compressed &quot;blob&quot; file.</p> </li> </ol> <p>Don't think of the four 'disks' represented in the image above as separate copies of the repo files.</p> </blockquote> <ul> <li><a href="http://web.archive.org/web/20090210020404id_/http://whygitisbetterthanx.com/#the-staging-area" rel="noreferrer">Why Git is better than X</a></li> </ul> <p><a href="https://i.stack.imgur.com/CYO5D.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CYO5D.jpg" alt="3 states" /></a></p> <ul> <li><a href="http://hades.github.io/2010/01/git-your-friend-not-foe-vol-3-refs-and-index/" rel="noreferrer">Git Is Your Friend not a Foe Vol. 3: Refs and Index</a></li> </ul> <blockquote> <p>They are basically named references for Git commits. There are two major types of refs: tags and heads.</p> <ul> <li>Tags are fixed references that mark a specific point in history, for example v2.6.29.</li> <li>On the contrary, heads are always moved to reflect the current position of project development.</li> </ul> <p><a href="https://i.stack.imgur.com/ipLiO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ipLiO.jpg" alt="commits" /></a></p> </blockquote> <p>(note: as <a href="https://stackoverflow.com/questions/3689838/difference-between-head-working-tree-index-in-git/3690796?noredirect=1#comment52738133_3690796">commented</a> by <a href="https://stackoverflow.com/users/175071/timo-huovinen">Timo Huovinen</a>, those arrows are not what the commits point to, it's the <strong>workflow order</strong>, basically showing arrows as <code>1 -&gt; 2 -&gt; 3 -&gt; 4</code> where <code>1</code> is the first commit and <code>4</code> is the last)</p> <blockquote> <p>Now we know what is happening in the project.<br /> But to know what is happening right here, right now there is a special reference called HEAD. It serves two major purposes:</p> <ul> <li>it tells Git which commit to take files from when you checkout, and</li> <li>it tells Git where to put new commits when you commit.</li> </ul> <p>When you run <code>git checkout ref</code> it points <code>HEAD</code> to the ref you’ve designated and extracts files from it. When you run <code>git commit</code> it creates a new commit object, which becomes a child of current <code>HEAD</code>. Normally <code>HEAD</code> points to one of the heads, so everything works out just fine.</p> <p><a href="https://i.stack.imgur.com/u2kuU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/u2kuU.jpg" alt="checkout" /></a></p> </blockquote>
{ "question_id": 3689838, "question_date": "2010-09-11T04:53:04.530Z", "question_score": 606, "tags": "git", "answer_id": 3690796, "answer_date": "2010-09-11T11:26:05.560Z", "answer_score": 697 }
Please answer the following Stack Overflow question: Title: Change first commit of project with Git? <p>I want to change something in the first commit of my project with out losing all subsequent commits. Is there any way to do this?</p> <p>I accidentally listed my raw email in a comment within the source code, and I'd like to change it as I'm getting spammed from bots indexing GitHub.</p>
<p>As mentioned by <a href="https://stackoverflow.com/users/656927/ecdpalma">ecdpalma</a> <a href="https://stackoverflow.com/a/14629246/6309">below</a>, <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.7.12.txt" rel="noreferrer">git 1.7.12+</a> (August 2012) has enhanced the option <code>--root</code> for <code>git rebase</code>:</p> <p>"<code>git rebase [-i] --root $tip</code>" can now be used to rewrite all the history leading to "<code>$tip</code>" down to the root commit.</p> <p>That new behavior was initially <a href="http://git.661346.n2.nabble.com/Editing-the-root-commit-td7561714.html" rel="noreferrer">discussed here</a>:</p> <blockquote> <p>I personally think "<code>git rebase -i --root</code>" should be made to just work without requiring "<code>--onto</code>" and let you "edit" even the first one in the history.<br> It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise. </p> </blockquote> <p>The <a href="http://git.661346.n2.nabble.com/Editing-the-root-commit-tp7561714p7562167.html" rel="noreferrer">patch followed</a>.</p> <hr> <p>(original answer, February 2010)</p> <p>As mentioned in the <a href="http://git.wiki.kernel.org/index.php/GitTips#How_to_change_commits_deeper_in_history" rel="noreferrer">Git FAQ</a> (and this <a href="https://stackoverflow.com/questions/2119480/changing-the-message-of-the-first-commit-git">SO question</a>), the idea is:</p> <ol> <li>Create new temporary branch </li> <li>Rewind it to the commit you want to change using <code>git reset --hard</code></li> <li>Change that commit (it would be top of current HEAD, and you can modify the content of any file)</li> <li><p>Rebase branch on top of changed commit, using:</p> <pre><code>git rebase --onto &lt;tmp branch&gt; &lt;commit after changed&gt; &lt;branch&gt;` </code></pre></li> </ol> <p>The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use <a href="http://git-scm.com/docs/git-filter-branch" rel="noreferrer"><code>filter-branch --tree-filter</code></a> to make sure the content of that file does not contain in any commit the sensible information.</p> <p>In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite. </p>
{ "question_id": 2246208, "question_date": "2010-02-11T17:17:53.490Z", "question_score": 606, "tags": "git|rebase|git-filter-branch", "answer_id": 2309391, "answer_date": "2010-02-22T07:20:36.677Z", "answer_score": 921 }
Please answer the following Stack Overflow question: Title: How to trigger a file download when clicking an HTML button or JavaScript <p>This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer.</p> <p>I want a simple file download, that would do the same as this:</p> <pre><code>&lt;a href="file.doc"&gt;Download!&lt;/a&gt; </code></pre> <p>But I want to use an HTML button, e.g. either of these:</p> <pre><code>&lt;input type="button" value="Download!"&gt; &lt;button&gt;Download!&lt;/button&gt; </code></pre> <p>Likewise, is it possible to trigger a simple download via JavaScript?</p> <pre><code>$("#fileRequest").click(function(){ /* code to download? */ }); </code></pre> <p>I'm definitely <em>not</em> looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.</p>
<p>For the button you can do</p> <pre><code>&lt;form method="get" action="file.doc"&gt; &lt;button type="submit"&gt;Download!&lt;/button&gt; &lt;/form&gt; </code></pre>
{ "question_id": 11620698, "question_date": "2012-07-23T21:22:08.437Z", "question_score": 605, "tags": "javascript|html|download", "answer_id": 11620761, "answer_date": "2012-07-23T21:26:19.057Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: How to change to an older version of Node.js <p>I am running Node.js version <code>v0.5.9-pre</code> on Ubuntu 10.10.</p> <p>I would like to be using version <code>v0.5.0-pre</code>.</p> <p>How do I roll back to the older version of node? </p>
<p>One way is to use NVM, the Node Version Manager.</p> <p>Use following command to get nvm</p> <pre><code>curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash </code></pre> <p>You can find it at <a href="https://github.com/creationix/nvm" rel="noreferrer">https://github.com/creationix/nvm</a> </p> <p>It allows you to easily install and manage multiple versions of node. Here's a snippet from the help:</p> <pre><code>Usage: nvm install &lt;version&gt; Download and install a &lt;version&gt; nvm use &lt;version&gt; Modify PATH to use &lt;version&gt; nvm ls List versions (installed versions are blue) </code></pre>
{ "question_id": 7718313, "question_date": "2011-10-10T20:30:08.083Z", "question_score": 605, "tags": "node.js", "answer_id": 7718438, "answer_date": "2011-10-10T20:43:33.980Z", "answer_score": 618 }
Please answer the following Stack Overflow question: Title: How to replace NaN values by Zeroes in a column of a Pandas Dataframe? <p>I have a Pandas Dataframe as below:</p> <pre><code> itm Date Amount 67 420 2012-09-30 00:00:00 65211 68 421 2012-09-09 00:00:00 29424 69 421 2012-09-16 00:00:00 29877 70 421 2012-09-23 00:00:00 30990 71 421 2012-09-30 00:00:00 61303 72 485 2012-09-09 00:00:00 71781 73 485 2012-09-16 00:00:00 NaN 74 485 2012-09-23 00:00:00 11072 75 485 2012-09-30 00:00:00 113702 76 489 2012-09-09 00:00:00 64731 77 489 2012-09-16 00:00:00 NaN </code></pre> <p>When I try to apply a function to the Amount column, I get the following error:</p> <pre><code>ValueError: cannot convert float NaN to integer </code></pre> <p>I have tried applying a function using .isnan from the Math Module I have tried the pandas .replace attribute I tried the .sparse data attribute from pandas 0.9 I have also tried if NaN == NaN statement in a function. I have also looked at this article <a href="https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-r">How do I replace NA values with zeros in an R dataframe?</a> whilst looking at some other articles. All the methods I have tried have not worked or do not recognise NaN. Any Hints or solutions would be appreciated.</p>
<p>I believe <code>DataFrame.fillna()</code> will do this for you.</p> <p>Link to Docs for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="noreferrer">a dataframe</a> and for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="noreferrer">a Series</a>. </p> <p>Example: </p> <pre><code>In [7]: df Out[7]: 0 1 0 NaN NaN 1 -0.494375 0.570994 2 NaN NaN 3 1.876360 -0.229738 4 NaN NaN In [8]: df.fillna(0) Out[8]: 0 1 0 0.000000 0.000000 1 -0.494375 0.570994 2 0.000000 0.000000 3 1.876360 -0.229738 4 0.000000 0.000000 </code></pre> <p>To fill the NaNs in only one column, select just that column. in this case I'm using inplace=True to actually change the contents of df. </p> <pre><code>In [12]: df[1].fillna(0, inplace=True) Out[12]: 0 0.000000 1 0.570994 2 0.000000 3 -0.229738 4 0.000000 Name: 1 In [13]: df Out[13]: 0 1 0 NaN 0.000000 1 -0.494375 0.570994 2 NaN 0.000000 3 1.876360 -0.229738 4 NaN 0.000000 </code></pre> <p><strong>EDIT:</strong></p> <p>To avoid a <code>SettingWithCopyWarning</code>, use the built in column-specific functionality:</p> <pre><code>df.fillna({1:0}, inplace=True) </code></pre>
{ "question_id": 13295735, "question_date": "2012-11-08T18:50:39.703Z", "question_score": 605, "tags": "python|pandas|dataframe|nan", "answer_id": 13295801, "answer_date": "2012-11-08T18:54:27.467Z", "answer_score": 941 }
Please answer the following Stack Overflow question: Title: Passing data to a bootstrap modal <p>I've got a couple of hyperlinks that each have an ID attached. When I click on this link, I want to open a modal ( <a href="http://twitter.github.com/bootstrap/javascript.html#modals" rel="noreferrer">http://twitter.github.com/bootstrap/javascript.html#modals</a> ), and pass this ID to the modal. I searched on google, but I couldn't find anything that could help me.</p> <p>This is the code:</p> <pre><code>&lt;a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"&gt;&lt;/a&gt; </code></pre> <p>Which should open:</p> <pre><code>&lt;div class="modal hide" id="addBookDialog"&gt; &lt;div class="modal-body"&gt; &lt;input type="hidden" name="bookId" id="bookId" value=""/&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>With this piece of code: </p> <pre><code>$(document).ready(function () { $(".open-AddBookDialog").click(function () { $('#bookId').val($(this).data('id')); $('#addBookDialog').modal('show'); }); }); </code></pre> <p>However, when I click the hyperlink, nothing happens. When I give the hyperlink <code>&lt;a href="#addBookDialog" ...&gt;</code>, the modal opens just fine, but it does't contain any data.</p> <p>I followed this example: <a href="https://stackoverflow.com/questions/10379624/how-to-pass-values-arguments-to-modal-show-function-in-twitter-bootstrat">How to pass values arguments to modal.show() function in Bootstrap</a></p> <p>(and I also tried this: <a href="https://stackoverflow.com/questions/7845866/how-to-set-the-input-value-in-a-modal-dialogue">How to set the input value in a modal dialogue?</a>)</p>
<p>I think you can make this work using jQuery's <a href="http://api.jquery.com/on/" rel="nofollow noreferrer">.on</a> event handler.</p> <p>Here's a fiddle you can test; just make sure to expand the HTML frame in the fiddle as much as possible so you can view the modal.</p> <p><a href="http://jsfiddle.net/8c05pn1f/" rel="nofollow noreferrer">http://jsfiddle.net/8c05pn1f/</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;p&gt;Link 1&lt;/p&gt; &lt;a data-toggle=&quot;modal&quot; data-id=&quot;ISBN564541&quot; title=&quot;Add this item&quot; class=&quot;open-AddBookDialog btn btn-primary&quot; href=&quot;#addBookDialog&quot;&gt;test&lt;/a&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Link 2&lt;/p&gt; &lt;a data-toggle=&quot;modal&quot; data-id=&quot;ISBN-001122&quot; title=&quot;Add this item&quot; class=&quot;open-AddBookDialog btn btn-primary&quot; href=&quot;#addBookDialog&quot;&gt;test&lt;/a&gt; &lt;div class=&quot;modal hide&quot; id=&quot;addBookDialog&quot;&gt; &lt;div class=&quot;modal-header&quot;&gt; &lt;button class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;×&lt;/button&gt; &lt;h3&gt;Modal header&lt;/h3&gt; &lt;/div&gt; &lt;div class=&quot;modal-body&quot;&gt; &lt;p&gt;some content&lt;/p&gt; &lt;input type=&quot;text&quot; name=&quot;bookId&quot; id=&quot;bookId&quot; value=&quot;&quot;/&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>JAVASCRIPT</strong></p> <pre><code>$(document).on(&quot;click&quot;, &quot;.open-AddBookDialog&quot;, function () { var myBookId = $(this).data('id'); $(&quot;.modal-body #bookId&quot;).val( myBookId ); // As pointed out in comments, // it is unnecessary to have to manually call the modal. // $('#addBookDialog').modal('show'); }); </code></pre>
{ "question_id": 10626885, "question_date": "2012-05-16T21:19:11.900Z", "question_score": 605, "tags": "javascript|jquery|asp.net-mvc|twitter-bootstrap", "answer_id": 10635652, "answer_date": "2012-05-17T12:20:53.213Z", "answer_score": 594 }
Please answer the following Stack Overflow question: Title: How do I count the number of occurrences of a char in a String? <p>I have the string </p> <pre><code>a.b.c.d </code></pre> <p>I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.</p> <p>(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).</p>
<p>My 'idiomatic one-liner' for this is:</p> <pre><code>int count = StringUtils.countMatches("a.b.c.d", "."); </code></pre> <p>Why write it yourself when it's already in <a href="http://commons.apache.org/lang/" rel="noreferrer">commons lang</a>?</p> <p>Spring Framework's oneliner for this is:</p> <pre><code>int occurance = StringUtils.countOccurrencesOf("a.b.c.d", "."); </code></pre>
{ "question_id": 275944, "question_date": "2008-11-09T14:07:09.060Z", "question_score": 605, "tags": "java|string", "answer_id": 1816989, "answer_date": "2009-11-29T22:23:07.673Z", "answer_score": 774 }
Please answer the following Stack Overflow question: Title: How can I detect if this dictionary key exists in C#? <p>I am working with the Exchange Web Services Managed API, with contact data. I have the following code, which is <em>functional</em>, but not ideal:</p> <pre><code>foreach (Contact c in contactList) { string openItemUrl = "https://" + service.Url.Host + "/owa/" + c.WebClientReadFormQueryString; row = table.NewRow(); row["FileAs"] = c.FileAs; row["GivenName"] = c.GivenName; row["Surname"] = c.Surname; row["CompanyName"] = c.CompanyName; row["Link"] = openItemUrl; //home address try { row["HomeStreet"] = c.PhysicalAddresses[PhysicalAddressKey.Home].Street.ToString(); } catch (Exception e) { } try { row["HomeCity"] = c.PhysicalAddresses[PhysicalAddressKey.Home].City.ToString(); } catch (Exception e) { } try { row["HomeState"] = c.PhysicalAddresses[PhysicalAddressKey.Home].State.ToString(); } catch (Exception e) { } try { row["HomeZip"] = c.PhysicalAddresses[PhysicalAddressKey.Home].PostalCode.ToString(); } catch (Exception e) { } try { row["HomeCountry"] = c.PhysicalAddresses[PhysicalAddressKey.Home].CountryOrRegion.ToString(); } catch (Exception e) { } //and so on for all kinds of other contact-related fields... } </code></pre> <p>As I said, this code <em>works</em>. Now I want to make it suck <em>a little less</em>, if possible.</p> <p>I can't find any methods that allow me to check for the existence of the key in the dictionary before attempting to access it, and if I try to read it (with <code>.ToString()</code>) and it doesn't exist then an exception is thrown:</p> <blockquote> <p>500<br/> The given key was not present in the dictionary.</p> </blockquote> <p>How can I refactor this code to suck less (while still being functional)?</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/htszx2dy.aspx" rel="noreferrer"><code>ContainsKey</code></a>:</p> <pre><code>if (dict.ContainsKey(key)) { ... } </code></pre> <p>or <a href="http://msdn.microsoft.com/en-us/library/bb299639.aspx" rel="noreferrer"><code>TryGetValue</code></a>:</p> <pre><code>dict.TryGetValue(key, out value); </code></pre> <hr> <p><strong>Update</strong>: according to a comment the actual class here is not an <code>IDictionary</code> but a <a href="http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.physicaladdressdictionary%28EXCHG.80%29.aspx" rel="noreferrer"><code>PhysicalAddressDictionary</code></a>, so the methods are <a href="http://msdn.microsoft.com/en-us/library/dd634696%28EXCHG.80%29.aspx" rel="noreferrer"><code>Contains</code></a> and <a href="http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.physicaladdressdictionary.trygetvalue%28EXCHG.80%29.aspx" rel="noreferrer"><code>TryGetValue</code></a> but they work in the same way.</p> <p>Example usage:</p> <pre><code>PhysicalAddressEntry entry; PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street; if (c.PhysicalAddresses.TryGetValue(key, out entry)) { row["HomeStreet"] = entry; } </code></pre> <hr> <p><strong>Update 2:</strong> here is the working code (compiled by question asker)</p> <pre><code>PhysicalAddressEntry entry; PhysicalAddressKey key = PhysicalAddressKey.Home; if (c.PhysicalAddresses.TryGetValue(key, out entry)) { if (entry.Street != null) { row["HomeStreet"] = entry.Street.ToString(); } } </code></pre> <p>...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).</p>
{ "question_id": 2829873, "question_date": "2010-05-13T19:57:37.123Z", "question_score": 605, "tags": "c#|exchangewebservices|ews-managed-api", "answer_id": 2829903, "answer_date": "2010-05-13T20:01:29.333Z", "answer_score": 1055 }
Please answer the following Stack Overflow question: Title: Installing a local module using npm? <p>I have a downloaded module repo, I want to install it locally, not globally in another directory? </p> <p>What is an easy way to do this?</p>
<p>you just provide one <code>&lt;folder&gt;</code> argument to <a href="https://docs.npmjs.com/cli/install" rel="noreferrer"><code>npm install</code></a>, argument should point toward the local folder instead of the package name:</p> <pre><code>npm install /path </code></pre>
{ "question_id": 8088795, "question_date": "2011-11-11T01:53:29.993Z", "question_score": 605, "tags": "javascript|node.js|npm|package|npm-install", "answer_id": 8089029, "answer_date": "2011-11-11T02:35:07.743Z", "answer_score": 654 }
Please answer the following Stack Overflow question: Title: How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically? <p>I have ViewPager and below it I have 10 buttons. By clicking on button, for example #4, the pager goes immediately to page #4 by <code>mPager.setCurrentItem(3);</code>. But, I want to disable the paging by swiping with finger horizontally. Thus, the paging is done <strong>ONLY</strong> by clicking on the buttons. So, how I can disable the swiping with finger?</p>
<p>You need to subclass <code>ViewPager</code>. <code>onTouchEvent</code> has a lot of good things in it that you don't want to change like allowing child views to get touches. <code>onInterceptTouchEvent</code> is what you want to change. If you look at the code for <code>ViewPager</code>, you'll see the comment:</p> <pre><code> /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ </code></pre> <p>Here's a complete solution:</p> <p>First, add this class to your <code>src</code> folder:</p> <pre><code>import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.animation.DecelerateInterpolator; import android.widget.Scroller; import java.lang.reflect.Field; public class NonSwipeableViewPager extends ViewPager { public NonSwipeableViewPager(Context context) { super(context); setMyScroller(); } public NonSwipeableViewPager(Context context, AttributeSet attrs) { super(context, attrs); setMyScroller(); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { // Never allow swiping to switch between pages return false; } @Override public boolean onTouchEvent(MotionEvent event) { // Never allow swiping to switch between pages return false; } //down one is added for smooth scrolling private void setMyScroller() { try { Class&lt;?&gt; viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField("mScroller"); scroller.setAccessible(true); scroller.set(this, new MyScroller(getContext())); } catch (Exception e) { e.printStackTrace(); } } public class MyScroller extends Scroller { public MyScroller(Context context) { super(context, new DecelerateInterpolator()); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/); } } } </code></pre> <p>Next, make sure to use this class instead of the regular <code>ViewPager</code>, which you probably specified as <code>android.support.v4.view.ViewPager</code>. In your layout file, you'll want to specify it with something like:</p> <pre><code>&lt;com.yourcompany.NonSwipeableViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /&gt; </code></pre> <p>This particular example is in a <code>LinearLayout</code> and is meant to take up the entire screen, which is why <code>layout_weight</code> is 1 and <code>layout_height</code> is 0dp.</p> <p>And <strong><code>setMyScroller();</code></strong> method is for smooth transition</p>
{ "question_id": 9650265, "question_date": "2012-03-10T21:18:36.663Z", "question_score": 605, "tags": "android|android-viewpager", "answer_id": 9650884, "answer_date": "2012-03-10T22:49:18.267Z", "answer_score": 919 }
Please answer the following Stack Overflow question: Title: Nginx -- static file serving confusion with root & alias <p>I need to serve my app through my app server at <code>8080</code>, and my static files from a directory without touching the app server.</p> <pre><code> # app server on port 8080 # nginx listens on port 8123 server { listen 8123; access_log off; location /static/ { # root /var/www/app/static/; alias /var/www/app/static/; autoindex off; } location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } </code></pre> <p>Now, with this config, everything is working fine. Note that the <code>root</code> directive is commented out.</p> <p>If I activate <code>root</code> and deactivate the <code>alias</code>, it stops working. However, when I remove the trailing <code>/static/</code> from <code>root</code>, it starts working again.</p> <p>Can someone explain what's going on?</p>
<p>There is a very important difference between the <code>root</code> and the <code>alias</code> directives. This difference exists in the way the path specified in the <code>root</code> or the <code>alias</code> is processed.</p> <p><code>root</code></p> <ul> <li>the <code>location</code> part is appended to <code>root</code> part</li> <li>final path = <code>root</code> + <code>location</code></li> </ul> <p><code>alias</code></p> <ul> <li>the <code>location</code> part is replaced by the <code>alias</code> part</li> <li>final path = <code>alias</code></li> </ul> <p>To illustrate:</p> <p>Let's say we have the config</p> <pre><code>location /static/ { root /var/www/app/static/; autoindex off; } </code></pre> <p>In this case the final path that Nginx will derive will be</p> <pre><code>/var/www/app/static/static </code></pre> <p>This is going to return <code>404</code> since there is no <code>static/</code> within <code>static/</code></p> <p>This is because the location part is appended to the path specified in the <code>root</code>. Hence, with <code>root</code>, the correct way is</p> <pre><code>location /static/ { root /var/www/app/; autoindex off; } </code></pre> <p>On the other hand, with <code>alias</code>, the location part gets <strong>dropped</strong>. So for the config</p> <pre><code>location /static/ { alias /var/www/app/static/; autoindex off; ↑ } | pay attention to this trailing slash </code></pre> <p>the final path will correctly be formed as</p> <pre><code>/var/www/app/static </code></pre> <p>In a way this makes sense. The <code>alias</code> just lets you define a new path to represent an existing &quot;real&quot; path. The location part is that new path, and so it gets replaced with the real path. Think of it as a symlink.</p> <p>Root, on the other hand is not a new path, it contains some information that has to be collated with some other info to make the final path. And so, the location part is used, not dropped.</p> <h3><em>The case for trailing slash in <code>alias</code></em></h3> <p>There is no definitive guideline about whether a trailing slash is mandatory per <a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#alias" rel="noreferrer">Nginx documentation</a>, but a common observation by people here and elsewhere seems to indicate that it is.</p> <p>A few more places have discussed this, not conclusively though.</p> <p><a href="https://serverfault.com/questions/376162/how-can-i-create-a-location-in-nginx-that-works-with-and-without-a-trailing-slas">https://serverfault.com/questions/376162/how-can-i-create-a-location-in-nginx-that-works-with-and-without-a-trailing-slas</a></p> <p><a href="https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working">https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working</a></p>
{ "question_id": 10631933, "question_date": "2012-05-17T08:03:01.760Z", "question_score": 605, "tags": "nginx", "answer_id": 10647080, "answer_date": "2012-05-18T05:18:29.383Z", "answer_score": 1335 }
Please answer the following Stack Overflow question: Title: Make iframe automatically adjust height according to the contents without using scrollbar? <p>For example:</p> <pre><code>&lt;iframe name="Stack" src="http://stackoverflow.com/" width="740" frameborder="0" scrolling="no" id="iframe"&gt; ... &lt;/iframe&gt; </code></pre> <p>I want it to be able to adjust its height according to the contents inside it, without using scroll.</p>
<p>Add this to your <code>&lt;head&gt;</code> section:</p> <pre><code>&lt;script&gt; function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px'; } &lt;/script&gt; </code></pre> <p>And change your iframe to this:</p> <pre><code>&lt;iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" /&gt; </code></pre> <p>As found on <a href="https://www.sitepoint.com/community/t/auto-height-iframe-content-script/67843" rel="noreferrer">sitepoint discussion</a>.</p>
{ "question_id": 9975810, "question_date": "2012-04-02T11:45:38.360Z", "question_score": 604, "tags": "javascript|html|iframe|height|scrollbar", "answer_id": 9976309, "answer_date": "2012-04-02T12:20:22.937Z", "answer_score": 775 }
Please answer the following Stack Overflow question: Title: How to change the text of a button in jQuery? <p>How do you change the text value of a button in jQuery? Currently, my button has 'Add' as its text value, and upon being clicked I want it to change to 'Save'. I have tried this method below, but so far without success:</p> <pre><code>$("#btnAddProfile").attr('value', 'Save'); </code></pre>
<p>Depends on what type of button you are using</p> <pre><code>&lt;input type='button' value='Add' id='btnAddProfile'&gt; $("#btnAddProfile").attr('value', 'Save'); //versions older than 1.6 &lt;input type='button' value='Add' id='btnAddProfile'&gt; $("#btnAddProfile").prop('value', 'Save'); //versions newer than 1.6 &lt;!-- Different button types--&gt; &lt;button id='btnAddProfile' type='button'&gt;Add&lt;/button&gt; $("#btnAddProfile").html('Save'); </code></pre> <p>Your button could also be a link. You'll need to post some HTML for a more specific answer. </p> <p><strong>EDIT</strong> : These will work assuming you've wrapped it in a <code>.click()</code> call, of course</p> <p><strong>EDIT 2</strong> : Newer jQuery versions (from > 1.6) use <code>.prop</code> rather than <code>.attr</code></p> <p><strong>EDIT 3</strong> : If you're using jQuery UI, you need to use DaveUK's method (<a href="https://stackoverflow.com/a/8755696/295508">below</a>) of adjusting the text property </p>
{ "question_id": 5580616, "question_date": "2011-04-07T11:56:03.537Z", "question_score": 604, "tags": "jquery|jquery-ui", "answer_id": 5580652, "answer_date": "2011-04-07T11:59:14.027Z", "answer_score": 1014 }
Please answer the following Stack Overflow question: Title: How to send a PUT/DELETE request in jQuery? <p><code>GET</code>:<code>$.get(..)</code></p> <p><code>POST</code>:<code>$.post()..</code></p> <p>What about <code>PUT/DELETE</code>?</p>
<p>You could use the <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer">ajax</a> method:</p> <pre><code>$.ajax({ url: '/script.cgi', type: 'DELETE', success: function(result) { // Do something with the result } }); </code></pre>
{ "question_id": 2153917, "question_date": "2010-01-28T10:55:36.737Z", "question_score": 604, "tags": "jquery|httprequest|put", "answer_id": 2153931, "answer_date": "2010-01-28T10:58:15.060Z", "answer_score": 1000 }
Please answer the following Stack Overflow question: Title: How to get Git to clone into current directory <p>I'm doing:</p> <pre><code>git clone ssh://[email protected]/home/user/private/repos/project_hub.git ./ </code></pre> <p>I'm getting:</p> <blockquote> <p>Fatal: destination path '.' already exists and is not an empty directory.</p> </blockquote> <p>I know path . already exists. And I can assure that directory IS empty. (I do ls inside and I see nothing!)</p> <p><strong>What am I missing here in order to clone that project into the current directory ?</strong></p>
<p>The solution was using the <code>dot</code>, so:</p> <pre><code>rm -rf .* &amp;&amp; git clone ssh://[email protected]/home/user/private/repos/project_hub.git .` </code></pre> <p><code>rm -rf .* &amp;&amp;</code> may be omitted if we are absolutely sure that the directory is empty.</p> <p>Credits go to: @James McLaughlin on comments</p>
{ "question_id": 9864728, "question_date": "2012-03-25T22:39:14.523Z", "question_score": 604, "tags": "git|git-clone", "answer_id": 15965134, "answer_date": "2013-04-12T07:05:20.830Z", "answer_score": 13 }
Please answer the following Stack Overflow question: Title: How to reset the state of a Redux store? <p>I am using Redux for state management.<br> How do I reset the store to its initial state?</p> <p>For example, let’s say I have two user accounts (<code>u1</code> and <code>u2</code>).<br> Imagine the following sequence of events:</p> <ol> <li><p>User <code>u1</code> logs into the app and does something, so we cache some data in the store.</p></li> <li><p>User <code>u1</code> logs out.</p></li> <li><p>User <code>u2</code> logs into the app without refreshing the browser.</p></li> </ol> <p>At this point, the cached data will be associated with <code>u1</code>, and I would like to clean it up.</p> <p><strong>How can I reset the Redux store to its initial state when the first user logs out?</strong></p>
<p>One way to do that would be to write a root reducer in your application.</p> <p>The root reducer would normally delegate handling the action to the reducer generated by <code>combineReducers()</code>. However, whenever it receives <code>USER_LOGOUT</code> action, it returns the initial state all over again.</p> <p>For example, if your root reducer looked like this:</p> <pre><code>const rootReducer = combineReducers({ /* your app’s top-level reducers */ }) </code></pre> <p>You can rename it to <code>appReducer</code> and write a new <code>rootReducer</code> delegating to it:</p> <pre><code>const appReducer = combineReducers({ /* your app’s top-level reducers */ }) const rootReducer = (state, action) =&gt; { return appReducer(state, action) } </code></pre> <p>Now we just need to teach the new <code>rootReducer</code> to return the initial state in response to the <code>USER_LOGOUT</code> action. As we know, reducers are supposed to return the initial state when they are called with <code>undefined</code> as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated <code>state</code> as we pass it to <code>appReducer</code>:</p> <pre><code> const rootReducer = (state, action) =&gt; { if (action.type === 'USER_LOGOUT') { return appReducer(undefined, action) } return appReducer(state, action) } </code></pre> <p>Now, whenever <code>USER_LOGOUT</code> fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check <code>action.type</code> as well.</p> <p>To reiterate, the full new code looks like this:</p> <pre><code>const appReducer = combineReducers({ /* your app’s top-level reducers */ }) const rootReducer = (state, action) =&gt; { if (action.type === 'USER_LOGOUT') { return appReducer(undefined, action) } return appReducer(state, action) } </code></pre> <p>In case you are using <a href="https://github.com/rt2zz/redux-persist" rel="noreferrer">redux-persist</a>, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and the state copy will be loaded from there on refresh.</p> <p>First, you need to import the appropriate <a href="https://github.com/rt2zz/redux-persist#storage-engines" rel="noreferrer">storage engine</a> and then, to parse the state before setting it to <code>undefined</code> and clean each storage state key.</p> <pre><code>const rootReducer = (state, action) =&gt; { if (action.type === SIGNOUT_REQUEST) { // for all keys defined in your persistConfig(s) storage.removeItem('persist:root') // storage.removeItem('persist:otherKey') return appReducer(undefined, action); } return appReducer(state, action); }; </code></pre>
{ "question_id": 35622588, "question_date": "2016-02-25T09:00:38.117Z", "question_score": 604, "tags": "javascript|redux|store|redux-store", "answer_id": 35641992, "answer_date": "2016-02-26T01:54:44.990Z", "answer_score": 1297 }
Please answer the following Stack Overflow question: Title: *ngIf and *ngFor on same element causing error <p>I'm having a problem with trying to use Angular's <code>*ngFor</code> and <code>*ngIf</code> on the same element. </p> <p>When trying to loop through the collection in the <code>*ngFor</code>, the collection is seen as <code>null</code> and consequently fails when trying to access its properties in the template.</p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'shell', template: ` &lt;h3&gt;Shell&lt;/h3&gt;&lt;button (click)="toggle()"&gt;Toggle!&lt;/button&gt; &lt;div *ngIf="show" *ngFor="let thing of stuff"&gt; {{log(thing)}} &lt;span&gt;{{thing.name}}&lt;/span&gt; &lt;/div&gt; ` }) export class ShellComponent implements OnInit { public stuff:any[] = []; public show:boolean = false; constructor() {} ngOnInit() { this.stuff = [ { name: 'abc', id: 1 }, { name: 'huo', id: 2 }, { name: 'bar', id: 3 }, { name: 'foo', id: 4 }, { name: 'thing', id: 5 }, { name: 'other', id: 6 }, ] } toggle() { this.show = !this.show; } log(thing) { console.log(thing); } } </code></pre> <p>I know the easy solution is to move the <code>*ngIf</code> up a level but for scenarios like looping over list items in a <code>ul</code>, I'd end up with either an empty <code>li</code> if the collection is empty, or my <code>li</code>s wrapped in redundant container elements.</p> <p>Example at this <a href="http://plnkr.co/edit/C5tZ8mD3iWczVvWkWycH?p=preview" rel="noreferrer">plnkr</a>.</p> <p>Note the console error:</p> <pre><code>EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12] </code></pre> <p>Am I doing something wrong or is this a bug?</p>
<p>Angular v2 doesn't support more than one structural directive on the same element.<br> As a workaround use the <strong><code>&lt;ng-container&gt;</code></strong> element that allows you to use separate elements for each structural directive, but it is <strong>not stamped to the DOM</strong>.</p> <pre class="lang-html prettyprint-override"><code>&lt;ng-container *ngIf="show"&gt; &lt;div *ngFor="let thing of stuff"&gt; {{log(thing)}} &lt;span&gt;{{thing.name}}&lt;/span&gt; &lt;/div&gt; &lt;/ng-container&gt; </code></pre> <p><code>&lt;ng-template&gt;</code> (<code>&lt;template&gt;</code> before Angular v4) allows to do the same but with a different syntax which is confusing and no longer recommended </p> <pre class="lang-html prettyprint-override"><code>&lt;ng-template [ngIf]="show"&gt; &lt;div *ngFor="let thing of stuff"&gt; {{log(thing)}} &lt;span&gt;{{thing.name}}&lt;/span&gt; &lt;/div&gt; &lt;/ng-template&gt; </code></pre>
{ "question_id": 34657821, "question_date": "2016-01-07T14:37:30.993Z", "question_score": 604, "tags": "angular|ngfor|angular-ng-if", "answer_id": 39565934, "answer_date": "2016-09-19T05:27:39.663Z", "answer_score": 856 }
Please answer the following Stack Overflow question: Title: Giving UIView rounded corners <p>My login view has a subview which has a <code>UIActivityView</code> and a <code>UILabel</code> saying "Signing In…". This subview has corners which aren't rounded. How can I make them round?</p> <p>Is there any way to do it inside my xib?</p>
<p>Try this</p> <pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; // not necessary for 10 years now :) </code></pre> <p>...</p> <pre><code>view.layer.cornerRadius = 5; view.layer.masksToBounds = true; </code></pre> <p>Note: If you are trying to apply rounded corners to a <code>UIViewController</code>'s view, it should not be applied in the view controller's constructor, but rather in <code>-viewDidLoad</code>, after <code>view</code> is actually instantiated.</p>
{ "question_id": 1509547, "question_date": "2009-10-02T13:36:24.020Z", "question_score": 604, "tags": "ios|xcode|cocoa-touch|uiview|layer", "answer_id": 1509570, "answer_date": "2009-10-02T13:40:44.790Z", "answer_score": 1260 }
Please answer the following Stack Overflow question: Title: Python vs Cpython <p>What's all this fuss about Python and CPython <em>(Jython,IronPython)</em>, I don't get it:</p> <p><a href="http://www.python.org/" rel="noreferrer">python.org</a> mentions that CPython is:</p> <blockquote> <p><em>The "traditional" implementation of Python (nicknamed CPython)</em></p> </blockquote> <p><a href="https://stackoverflow.com/a/2324217/2425215">yet another Stack Overflow question</a> mentions that:</p> <blockquote> <p><em>CPython is the default byte-code interpreter of Python, which is written in C.</em></p> </blockquote> <p>Honestly I don't get what both of those explanations practically mean but what I thought was that, <em>if I use CPython does that mean when I run a sample python code, it compiles it to C language and then executes it as if it were C code</em></p> <p><strong>So what exactly is CPython and how does it differ when compared with python and should I probably use CPython over Python and if so what are its advantages?</strong></p>
<h2>So what is CPython?</h2> <p>CPython is the <em>original</em> Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python <em>programming language</em> itself.</p> <p>The latter part is where your confusion comes from; you need to keep Python-the-language separate from whatever <em>runs</em> the Python code.</p> <p>CPython <em>happens</em> to be implemented in C. That is just an implementation detail, really. CPython compiles your Python code into bytecode (transparently) and interprets that bytecode in a evaluation loop.</p> <p>CPython is also the first to implement new features; Python-the-language development uses CPython as the base; other implementations follow.</p> <h2>What about Jython, etc.?</h2> <p><a href="http://www.jython.org/" rel="noreferrer">Jython</a>, <a href="http://ironpython.net/" rel="noreferrer">IronPython</a> and <a href="https://pypy.org/" rel="noreferrer">PyPy</a> are the current &quot;other&quot; implementations of the Python programming language; these are implemented in Java, C# and RPython (a subset of Python), respectively. Jython compiles your Python code to <em>Java</em> bytecode, so your Python code can run on the JVM. IronPython lets you run Python on the <a href="https://docs.microsoft.com/en-us/dotnet/standard/clr" rel="noreferrer">Microsoft CLR</a>. And PyPy, being implemented in (a subset of) Python, lets you run Python code faster than CPython, which rightly should blow your mind. :-)</p> <h2>Actually compiling to C</h2> <p>So CPython does <strong>not</strong> translate your Python code to C by itself. Instead, it runs an interpreter loop. There <em>is</em> a project that <em>does</em> translate Python-ish code to C, and that is called <a href="http://cython.org/" rel="noreferrer">Cython</a>. Cython adds a few extensions to the Python language, and lets you compile your code to C extensions, code that plugs <em>into</em> the CPython interpreter.</p>
{ "question_id": 17130975, "question_date": "2013-06-16T07:00:18.383Z", "question_score": 604, "tags": "python|cpython", "answer_id": 17130986, "answer_date": "2013-06-16T07:02:38.503Z", "answer_score": 891 }
Please answer the following Stack Overflow question: Title: Use 'class' or 'typename' for template parameters? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates">C++ difference of keywords ‘typename’ and ‘class’ in templates</a> </p> </blockquote> <p>When defining a function template or class template in C++, one can write this:</p> <pre><code>template &lt;class T&gt; ... </code></pre> <p>or one can write this:</p> <pre><code>template &lt;typename T&gt; ... </code></pre> <p>Is there a good reason to prefer one over the other?</p> <hr> <p>I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."</p> <ul> <li>They are equivalent (except as noted below).</li> <li>Some people have reasons to always use <code>typename</code>.</li> <li>Some people have reasons to always use <code>class</code>.</li> <li>Some people have reasons to use both.</li> <li>Some people don't care which one they use.</li> </ul> <p>Note, however, that before C++17 in the case of <em>template template</em> parameters, use of <code>class</code> instead of <code>typename</code> was required. See <a href="https://stackoverflow.com/a/11311432/3964522">user1428839's answer</a> below. (But this particular case is not a matter of preference, it was a requirement of the language.)</p>
<p>Stan Lippman talked about this <a href="https://docs.microsoft.com/archive/blogs/slippman/why-c-supports-both-class-and-typename-for-type-parameters" rel="noreferrer">here</a>. I thought it was interesting.</p> <p><em>Summary</em>: Stroustrup originally used <code>class</code> to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword <code>typename</code> to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, <code>class</code> kept its overloaded meaning.</p>
{ "question_id": 213121, "question_date": "2008-10-17T17:43:59.173Z", "question_score": 604, "tags": "c++|templates", "answer_id": 213135, "answer_date": "2008-10-17T17:47:57.013Z", "answer_score": 434 }
Please answer the following Stack Overflow question: Title: How to move some files from one git repo to another (not a clone), preserving history <p>Our Git repositories started out as parts of a single monster SVN repository where the individual projects each had their own tree like so:</p> <pre><code>project1/branches /tags /trunk project2/branches /tags /trunk </code></pre> <p>Obviously, it was pretty easy to move files from one to another with <code>svn mv</code>. But in Git, each project is in its own repository, and today I was asked to move a subdirectory from <code>project2</code> to <code>project1</code>. I did something like this:</p> <pre><code>$ git clone project2 $ cd project2 $ git filter-branch --subdirectory-filter deeply/buried/java/source/directory/A -- --all $ git remote rm origin # so I don't accidentally overwrite the repo ;-) $ mkdir -p deeply/buried/different/java/source/directory/B $ for f in *.java; do &gt; git mv $f deeply/buried/different/java/source/directory/B &gt; done $ git commit -m "moved files to new subdirectory" $ cd .. $ $ git clone project1 $ cd project1 $ git remote add p2 ../project2 $ git fetch p2 $ git branch p2 remotes/p2/master $ git merge p2 # --allow-unrelated-histories for git 2.9+ $ git remote rm p2 $ git push </code></pre> <p>But that seems pretty convoluted. Is there a better way to do this sort of thing in general? Or have I adopted the right approach?</p> <p>Note that this involves merging the history into an existing repository, rather than simply creating a new standalone repository from part of another one (<a href="https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository">as in an earlier question</a>).</p>
<p>Yep, hitting on the <code>--subdirectory-filter</code> of <code>filter-branch</code> was key. The fact that you used it essentially proves there's no easier way - you had no choice but to rewrite history, since you wanted to end up with only a (renamed) subset of the files, and this by definition changes the hashes. Since none of the standard commands (e.g. <code>pull</code>) rewrite history, there's no way you could use them to accomplish this.</p> <p>You could refine the details, of course - some of your cloning and branching wasn't strictly necessary - but the overall approach is good! It's a shame it's complicated, but of course, the point of git isn't to make it easy to rewrite history.</p>
{ "question_id": 1365541, "question_date": "2009-09-02T02:04:31.177Z", "question_score": 604, "tags": "git|repository", "answer_id": 1365990, "answer_date": "2009-09-02T05:38:50.803Z", "answer_score": 62 }
Please answer the following Stack Overflow question: Title: NOT IN vs NOT EXISTS <p>Which of these queries is the faster?</p> <p>NOT EXISTS:</p> <pre><code>SELECT ProductID, ProductName FROM Northwind..Products p WHERE NOT EXISTS ( SELECT 1 FROM Northwind..[Order Details] od WHERE p.ProductId = od.ProductId) </code></pre> <p>Or NOT IN:</p> <pre><code>SELECT ProductID, ProductName FROM Northwind..Products p WHERE p.ProductID NOT IN ( SELECT ProductID FROM Northwind..[Order Details]) </code></pre> <p>The query execution plan says they both do the same thing. If that is the case, which is the recommended form?</p> <p>This is based on the NorthWind database.</p> <p>[Edit]</p> <p>Just found this helpful article: <a href="http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx" rel="noreferrer">http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx</a></p> <p>I think I'll stick with NOT EXISTS.</p>
<p>I always default to <code>NOT EXISTS</code>.</p> <p>The execution plans may be the same at the moment but if either column is altered in the future to allow <code>NULL</code>s the <code>NOT IN</code> version will need to do more work (even if no <code>NULL</code>s are actually present in the data) and the semantics of <code>NOT IN</code> if <code>NULL</code>s <em>are</em> present are unlikely to be the ones you want anyway.</p> <p>When neither <code>Products.ProductID</code> or <code>[Order Details].ProductID</code> allow <code>NULL</code>s the <code>NOT IN</code> will be treated identically to the following query.</p> <pre><code>SELECT ProductID, ProductName FROM Products p WHERE NOT EXISTS (SELECT * FROM [Order Details] od WHERE p.ProductId = od.ProductId) </code></pre> <p>The exact plan may vary but for my example data I get the following.</p> <p><img src="https://i.stack.imgur.com/lCTsG.png" alt="Neither NULL"></p> <p>A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.</p> <pre><code>/*Not valid syntax but better reflects the plan*/ SELECT p.ProductID, p.ProductName FROM Products p LEFT ANTI SEMI JOIN [Order Details] od ON p.ProductId = od.ProductId </code></pre> <p>If <code>[Order Details].ProductID</code> is <code>NULL</code>-able the query then becomes</p> <pre><code>SELECT ProductID, ProductName FROM Products p WHERE NOT EXISTS (SELECT * FROM [Order Details] od WHERE p.ProductId = od.ProductId) AND NOT EXISTS (SELECT * FROM [Order Details] WHERE ProductId IS NULL) </code></pre> <p>The reason for this is that the correct semantics if <code>[Order Details]</code> contains any <code>NULL</code> <code>ProductId</code>s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.</p> <p><img src="https://i.stack.imgur.com/mPYhd.png" alt="One NULL"></p> <p>If <code>Products.ProductID</code> is also changed to become <code>NULL</code>-able the query then becomes</p> <pre><code>SELECT ProductID, ProductName FROM Products p WHERE NOT EXISTS (SELECT * FROM [Order Details] od WHERE p.ProductId = od.ProductId) AND NOT EXISTS (SELECT * FROM [Order Details] WHERE ProductId IS NULL) AND NOT EXISTS (SELECT * FROM (SELECT TOP 1 * FROM [Order Details]) S WHERE p.ProductID IS NULL) </code></pre> <p>The reason for that one is because a <code>NULL</code> <code>Products.ProductId</code> should not be returned in the results <strong>except</strong> if the <code>NOT IN</code> sub query were to return no results at all (i.e. the <code>[Order Details]</code> table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.</p> <p><img src="https://i.stack.imgur.com/8XAh1.png" alt="Both NULL"></p> <p>The effect of this is shown in <a href="http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/" rel="noreferrer">the blog post already linked by Buckley</a>. In the example there the number of logical reads increase from around 400 to 500,000.</p> <p>Additionally the fact that a single <code>NULL</code> can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no <code>NULL</code> rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, <a href="https://dba.stackexchange.com/q/117306/3690">with inappropriate nested loops causing repeated execution of an expensive sub tree for example</a>. </p> <p>This is not the only possible execution plan for a <code>NOT IN</code> on a <code>NULL</code>-able column however. <a href="http://bradsruminations.blogspot.co.uk/2011/10/t-sql-tuesday-023-flip-side-of-join.html" rel="noreferrer">This article shows another one</a> for a query against the <code>AdventureWorks2008</code> database.</p> <p>For the <code>NOT IN</code> on a <code>NOT NULL</code> column or the <code>NOT EXISTS</code> against either a nullable or non nullable column it gives the following plan.</p> <p><img src="https://i.stack.imgur.com/nahUD.png" alt="Not EXists"></p> <p>When the column changes to <code>NULL</code>-able the <code>NOT IN</code> plan now looks like</p> <p><img src="https://i.stack.imgur.com/8o9PQ.png" alt="Not In - Null"></p> <p>It adds an extra inner join operator to the plan. This apparatus is <a href="https://dba.stackexchange.com/a/14812/3690">explained here</a>. It is all there to convert the previous single correlated index seek on <code>Sales.SalesOrderDetail.ProductID = &lt;correlated_product_id&gt;</code> to two seeks per outer row. The additional one is on <code>WHERE Sales.SalesOrderDetail.ProductID IS NULL</code>. </p> <p>As this is under an anti semi join if that one returns any rows the second seek will not occur. However if <code>Sales.SalesOrderDetail</code> does not contain any <code>NULL</code> <code>ProductID</code>s it will double the number of seek operations required.</p>
{ "question_id": 173041, "question_date": "2008-10-06T02:19:05.033Z", "question_score": 603, "tags": "sql|sql-server|notin", "answer_id": 11074428, "answer_date": "2012-06-17T20:10:17.887Z", "answer_score": 764 }
Please answer the following Stack Overflow question: Title: How to prompt for user input and read command-line arguments <p>How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?</p>
<p>To read user input you can try <a href="https://docs.python.org/dev/library/cmd.html" rel="noreferrer">the <code>cmd</code> module</a> for easily creating a mini-command line interpreter (with help texts and autocompletion) and <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="noreferrer"><code>raw_input</code></a> (<a href="https://docs.python.org/dev/library/functions.html#input" rel="noreferrer"><code>input</code></a> for Python 3+) for reading a line of text from the user.</p> <pre><code>text = raw_input("prompt") # Python 2 text = input("prompt") # Python 3 </code></pre> <p>Command line inputs are in <code>sys.argv</code>. Try this in your script:</p> <pre><code>import sys print (sys.argv) </code></pre> <p>There are two modules for parsing command line options: <a href="https://docs.python.org/dev/library/optparse.html" rel="noreferrer"><s><code>optparse</code></s></a> (deprecated since Python 2.7, use <a href="https://docs.python.org/dev/library/argparse.html" rel="noreferrer"><code>argparse</code></a> instead) and <a href="https://docs.python.org/dev/library/getopt.html" rel="noreferrer"><code>getopt</code></a>. If you just want to input files to your script, behold the power of <a href="https://docs.python.org/dev/library/fileinput.html" rel="noreferrer"><code>fileinput</code></a>.</p> <p>The <a href="https://docs.python.org/dev/library/" rel="noreferrer">Python library reference</a> is your friend.</p>
{ "question_id": 70797, "question_date": "2008-09-16T09:44:59.477Z", "question_score": 603, "tags": "python|input|command-line-arguments", "answer_id": 70833, "answer_date": "2008-09-16T09:50:40.990Z", "answer_score": 588 }
Please answer the following Stack Overflow question: Title: Why use def main()? <p>I've seen some code samples and tutorials that use</p> <pre><code>def main(): # my code here if __name__ == "__main__": main() </code></pre> <p>But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie</p> <pre><code>def my_function() # my code here def my_function_two() # my code here # some code # call function # print(something) </code></pre> <p>I just wonder if there is any rhyme to the main?</p>
<p>Without the main sentinel, the code would be executed even if the script were imported as a module.</p>
{ "question_id": 4041238, "question_date": "2010-10-28T08:54:21.037Z", "question_score": 603, "tags": "python|coding-style", "answer_id": 4041253, "answer_date": "2010-10-28T08:56:03.867Z", "answer_score": 663 }
Please answer the following Stack Overflow question: Title: How to make an Android Spinner with initial text "Select One"? <p>I want to use a Spinner that initially (when the user has not made a selection yet) displays the text "Select One". When the user clicks the spinner, the list of items is displayed and the user selects one of the options. After the user has made a selection, the selected item is displayed in the Spinner instead of "Select One".</p> <p>I have the following code to create a Spinner: </p> <pre><code>String[] items = new String[] {"One", "Two", "Three"}; Spinner spinner = (Spinner) findViewById(R.id.mySpinner); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); </code></pre> <p>With this code, initially the item "One" is displayed. I could just add a new item "Select One" to the items, but then "Select One" would also be displayed in the dropdown list as first item, which is not what I want.</p> <p>How can I fix this problem?</p>
<p>Here's a general solution that overrides the <code>Spinner</code> view. It overrides <code>setAdapter()</code> to set the initial position to -1, and proxies the supplied <code>SpinnerAdapter</code> to display the prompt string for position less than 0.</p> <p>This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private <code>AdapterView.setNextSelectedPositionInt()</code> and <code>AdapterView.setSelectedPositionInt()</code>, it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.</p> <p>Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.</p> <pre><code>/** * A modified Spinner that doesn't automatically select the first entry in the list. * * Shows the prompt if nothing is selected. * * Limitations: does not display prompt if the entry list is empty. */ public class NoDefaultSpinner extends Spinner { public NoDefaultSpinner(Context context) { super(context); } public NoDefaultSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setAdapter(SpinnerAdapter orig ) { final SpinnerAdapter adapter = newProxy(orig); super.setAdapter(adapter); try { final Method m = AdapterView.class.getDeclaredMethod( "setNextSelectedPositionInt",int.class); m.setAccessible(true); m.invoke(this,-1); final Method n = AdapterView.class.getDeclaredMethod( "setSelectedPositionInt",int.class); n.setAccessible(true); n.invoke(this,-1); } catch( Exception e ) { throw new RuntimeException(e); } } protected SpinnerAdapter newProxy(SpinnerAdapter obj) { return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance( obj.getClass().getClassLoader(), new Class[]{SpinnerAdapter.class}, new SpinnerAdapterProxy(obj)); } /** * Intercepts getView() to display the prompt if position &lt; 0 */ protected class SpinnerAdapterProxy implements InvocationHandler { protected SpinnerAdapter obj; protected Method getView; protected SpinnerAdapterProxy(SpinnerAdapter obj) { this.obj = obj; try { this.getView = SpinnerAdapter.class.getMethod( "getView",int.class,View.class,ViewGroup.class); } catch( Exception e ) { throw new RuntimeException(e); } } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { try { return m.equals(getView) &amp;&amp; (Integer)(args[0])&lt;0 ? getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) : m.invoke(obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException(e); } } protected View getView(int position, View convertView, ViewGroup parent) throws IllegalAccessException { if( position&lt;0 ) { final TextView v = (TextView) ((LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE)).inflate( android.R.layout.simple_spinner_item,parent,false); v.setText(getPrompt()); return v; } return obj.getView(position,convertView,parent); } } } </code></pre>
{ "question_id": 867518, "question_date": "2009-05-15T08:09:23.520Z", "question_score": 603, "tags": "android|android-spinner", "answer_id": 3427058, "answer_date": "2010-08-06T19:25:25.977Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Set EditText cursor color <p>I am having this issue where I am using the Android's Holo theme on a tablet project. However, I have a fragment on screen which has a white background. I am adding an <code>EditText</code> component on this fragment. I've tried to override the theme by setting the background of the Holo.Light theme resources. However, my text cursor (carat) remains white and hence, invisible on screen (I can spot it faintly in the edittext field..).</p> <p>Does anyone know how I can get EditText to use a darker cursor color? I've tried setting the style of the EditText to <code>"@android:style/Widget.Holo.Light.EditText"</code> with no positive result.</p>
<p>Setting the <code>android:textCursorDrawable</code> attribute to <code>@null</code> should result in the use of <code>android:textColor</code> as the cursor color.</p> <p>Attribute "textCursorDrawable" is available in API level 12 and higher </p>
{ "question_id": 7238450, "question_date": "2011-08-30T03:43:52.317Z", "question_score": 603, "tags": "android|android-edittext|android-styles", "answer_id": 9165217, "answer_date": "2012-02-06T18:29:10.673Z", "answer_score": 1328 }
Please answer the following Stack Overflow question: Title: SQLite - UPSERT *not* INSERT or REPLACE <p><a href="http://en.wikipedia.org/wiki/Upsert" rel="noreferrer">http://en.wikipedia.org/wiki/Upsert</a></p> <p><a href="https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server">Insert Update stored proc on SQL Server</a></p> <p>Is there some clever way to do this in SQLite that I have not thought of?</p> <p>Basically I want to update three out of four columns if the record exists, If it does not exists I want to INSERT the record with the default (NUL) value for the fourth column.</p> <p>The ID is a primary key so there will only ever be one record to UPSERT.</p> <p>(I am trying to avoid the overhead of SELECT in order to determine if I need to UPDATE or INSERT obviously)</p> <p>Suggestions?</p> <hr /> <p>I cannot confirm that Syntax on the SQLite site for TABLE CREATE. I have not built a demo to test it, but it doesn't seem to be supported.</p> <p>If it was, I have three columns so it would actually look like:</p> <pre><code>CREATE TABLE table1( id INTEGER PRIMARY KEY ON CONFLICT REPLACE, Blob1 BLOB ON CONFLICT REPLACE, Blob2 BLOB ON CONFLICT REPLACE, Blob3 BLOB ); </code></pre> <p>but the first two blobs will not cause a conflict, only the ID would So I assume Blob1 and Blob2 would not be replaced (as desired)</p> <hr /> <p>UPDATEs in SQLite when binding data are a complete transaction, meaning Each sent row to be updated requires: Prepare/Bind/Step/Finalize statements unlike the INSERT which allows the use of the reset function</p> <p>The life of a statement object goes something like this:</p> <ol> <li>Create the object using sqlite3_prepare_v2()</li> <li>Bind values to host parameters using sqlite3_bind_ interfaces.</li> <li>Run the SQL by calling sqlite3_step()</li> <li>Reset the statement using sqlite3_reset() then go back to step 2 and repeat.</li> <li>Destroy the statement object using sqlite3_finalize().</li> </ol> <p>UPDATE I am guessing is slow compared to INSERT, but how does it compare to SELECT using the Primary key?</p> <p>Perhaps I should use the select to read the 4th column (Blob3) and then use REPLACE to write a new record blending the original 4th Column with the new data for the first 3 columns?</p>
<p>Assuming three columns in the table: ID, NAME, ROLE</p> <hr /> <p><strong>BAD:</strong> This will insert or replace all columns with new values for ID=1:</p> <pre><code>INSERT OR REPLACE INTO Employee (id, name, role) VALUES (1, 'John Foo', 'CEO'); </code></pre> <hr /> <p><strong>BAD:</strong> This will insert or replace 2 of the columns... the NAME column will be set to NULL or the default value:</p> <pre><code>INSERT OR REPLACE INTO Employee (id, role) VALUES (1, 'code monkey'); </code></pre> <hr /> <p><strong>GOOD</strong>: Use SQLite On conflict clause <a href="https://www.sqlite.org/draft/lang_UPSERT.html" rel="noreferrer">UPSERT support in SQLite!</a> UPSERT syntax was added to SQLite with version 3.24.0!</p> <p>UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL.</p> <p><a href="https://i.stack.imgur.com/h475O.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/h475O.gif" alt="enter image description here" /></a></p> <p><strong>GOOD but tedious:</strong> This will update 2 of the columns. When ID=1 exists, the NAME will be unaffected. When ID=1 does not exist, the name will be the default (NULL).</p> <pre><code>INSERT OR REPLACE INTO Employee (id, role, name) VALUES ( 1, 'code monkey', (SELECT name FROM Employee WHERE id = 1) ); </code></pre> <p>This will update 2 of the columns. When ID=1 exists, the ROLE will be unaffected. When ID=1 does not exist, the role will be set to 'Benchwarmer' instead of the default value.</p> <pre><code>INSERT OR REPLACE INTO Employee (id, name, role) VALUES ( 1, 'Susan Bar', COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer') ); </code></pre>
{ "question_id": 418898, "question_date": "2009-01-07T01:47:23.903Z", "question_score": 603, "tags": "sql|sqlite|upsert", "answer_id": 4330694, "answer_date": "2010-12-02T00:55:15.833Z", "answer_score": 931 }
Please answer the following Stack Overflow question: Title: What is the difference between lock, mutex and semaphore? <p>I've heard these words related to concurrent programming, but what's the difference between lock, mutex and semaphore?</p>
<p>A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes.</p> <p>A mutex is the same as a lock but it can be system wide (shared by multiple processes).</p> <p>A <a href="https://stackoverflow.com/a/2350628/58553">semaphore</a> does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.</p> <p>For a more detailed post about the differences between mutex and semaphore read <a href="https://stackoverflow.com/a/40238/58553">here</a>.</p> <p>You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time.</p>
{ "question_id": 2332765, "question_date": "2010-02-25T09:03:19.433Z", "question_score": 603, "tags": "concurrency|locking|mutex|semaphore", "answer_id": 2332868, "answer_date": "2010-02-25T09:21:53.557Z", "answer_score": 725 }
Please answer the following Stack Overflow question: Title: What is an Android PendingIntent? <p>I am a newbie to Android. I read the Android Documentation but I still need some more clarification. Can anyone tell me what exactly a <code>PendingIntent</code> is?</p>
<p>A <code>PendingIntent</code> is a token that you give to a foreign application (e.g. <code>NotificationManager</code>, <code>AlarmManager</code>, Home Screen <code>AppWidgetManager</code>, or other 3rd party applications), which <strong>allows the foreign application to use your application's permissions to execute a predefined piece of code</strong>.</p> <p>If you give the foreign application an Intent, it will execute your <code>Intent</code> with its own permissions. But if you give the foreign application a <code>PendingIntent</code>, that application will execute your <code>Intent</code> using your application's permission.</p>
{ "question_id": 2808796, "question_date": "2010-05-11T07:30:04.477Z", "question_score": 603, "tags": "android|android-intent|android-pendingintent", "answer_id": 4812421, "answer_date": "2011-01-27T03:24:20.273Z", "answer_score": 987 }
Please answer the following Stack Overflow question: Title: Why fragments, and when to use fragments instead of activities? <p>In Android API 11+, Google has released a new class called <code>Fragment</code>.</p> <p>In the videos, Google suggests that whenever possible (<a href="https://www.youtube.com/watch?v=WGIU2JX1U5Y" rel="noreferrer">link1</a>, <a href="https://www.youtube.com/watch?v=sTx-5CGDvM8" rel="noreferrer">link2</a>), we should use fragments instead of activities, but they didn't explain exactly why.</p> <p>What's the purpose of fragments and some possible uses of them (other than some UI examples that can be easily be achieved by simple views/layouts)?</p> <p>My question is about fragments:</p> <ol> <li>What are the purposes of using a fragment?</li> <li>What are the advantages and disadvantages of using fragments compared to using activities/views/layouts?</li> </ol> <p>Bonus questions:</p> <ol start="3"> <li>Can you give some really interesting uses for fragments? Things that Google didn't mention in their videos?</li> <li>What's the best way to communicate between fragments and the activities that contain them?</li> <li>What are the most important things to remember when you use fragments? Any tips and warnings from your experience?</li> </ol>
<blockquote> <p>#1 &amp; #2 what are the purposes of using a fragment &amp; what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?</p> </blockquote> <p>Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;</p> <ul> <li><p>The <code>ActionBar</code>. If you want tabs up there to navigate your app, you quickly see that <code>ActionBar.TabListener</code> interface gives you a <code>FragmentTransaction</code> as an input argument to the <code>onTabSelected</code> method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.</p></li> <li><p>The <code>FragmentManager</code> handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state. </p></li> <li><p>You can use the cool <code>ViewPager</code> with a <code>FragmentPagerAdapter</code> to create swipe interfaces. The <code>FragmentPagerAdapter</code> code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.</p></li> <li><p>Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy. </p></li> <li><p>You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use <code>ActionBarSherlock</code> and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the <code>ActionBar</code>, with tabs, overflow, split action bar, viewpager etc.</p></li> </ul> <blockquote> <p>Bonus 2</p> </blockquote> <p>The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call <code>StartActivity()</code> with data on it. The intent is passed on to all fragments of the activity you launch.</p>
{ "question_id": 10478233, "question_date": "2012-05-07T07:23:36.650Z", "question_score": 603, "tags": "android|android-layout|android-fragments|android-activity|android-3.0-honeycomb", "answer_id": 10515807, "answer_date": "2012-05-09T12:11:32.057Z", "answer_score": 347 }
Please answer the following Stack Overflow question: Title: Should composer.lock be committed to version control? <p>I'm a little confused with <code>composer.lock</code> used in an application with a repository.</p> <p>I saw many people saying that we should not <code>.gitignore</code> <code>composer.lock</code> from the repository.</p> <p>If I update my libraries in my dev environment, I will have a new <code>composer.lock</code> but I will not be able to update them into production, will I ?</p> <p>Won't it generate conflicts on this file ?</p>
<p>If you update your libs, you want to commit the lockfile too. It basically states that your project is locked to those specific versions of the libs you are using.</p> <p>If you commit your changes, and someone pulls your code and updates the dependencies, the lockfile should be unmodified. If it is modified, it means that you have a new version of something.</p> <p>Having it in the repository assures you that each developer is using the same versions.</p>
{ "question_id": 12896780, "question_date": "2012-10-15T13:36:42.760Z", "question_score": 603, "tags": "git|version-control|composer-php", "answer_id": 12896850, "answer_date": "2012-10-15T13:39:22.363Z", "answer_score": 761 }
Please answer the following Stack Overflow question: Title: PHP, cURL, and HTTP POST example? <p>Can anyone show me how to do a PHP cURL with an HTTP POST?</p> <p>I want to send data like this:</p> <pre><code>username=user1, password=passuser1, gender=1 </code></pre> <p>To <code>www.example.com</code></p> <p>I expect the cURL to return a response like <code>result=OK</code>. Are there any examples?</p>
<pre><code>&lt;?php // // A very simple PHP example that sends a HTTP POST to a remote site // $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&amp;postvar2=value2&amp;postvar3=value3"); // In real life you should use something like: // curl_setopt($ch, CURLOPT_POSTFIELDS, // http_build_query(array('postvar1' =&gt; 'value1'))); // Receive server response ... curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); curl_close ($ch); // Further processing ... if ($server_output == "OK") { ... } else { ... } ?&gt; </code></pre>
{ "question_id": 2138527, "question_date": "2010-01-26T09:39:35.703Z", "question_score": 602, "tags": "php|http|curl|http-post", "answer_id": 2138534, "answer_date": "2010-01-26T09:40:44.407Z", "answer_score": 1013 }
Please answer the following Stack Overflow question: Title: How can I check if an element exists in the visible DOM? <p>How do you test an element for existence without the use of the <code>getElementById</code> method?</p> <p>I have set up a <a href="http://jsbin.com/apawi5/3" rel="noreferrer">live demo</a> for reference. I will also print the code on here as well:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script&gt; var getRandomID = function (size) { var str = "", i = 0, chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ"; while (i &lt; size) { str += chars.substr(Math.floor(Math.random() * 62), 1); i++; } return str; }, isNull = function (element) { var randomID = getRandomID(12), savedID = (element.id)? element.id : null; element.id = randomID; var foundElm = document.getElementById(randomID); element.removeAttribute('id'); if (savedID !== null) { element.id = savedID; } return (foundElm) ? false : true; }; window.onload = function () { var image = document.getElementById("demo"); console.log('undefined', (typeof image === 'undefined') ? true : false); // false console.log('null', (image === null) ? true : false); // false console.log('find-by-id', isNull(image)); // false image.parentNode.removeChild(image); console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true? console.log('null', (image === null) ? true : false); // false ~ should be true? console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this? }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="demo"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Basically the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.</p> <p>The <code>isNull</code> function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.</p> <p>PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.</p>
<p>It seems some people are landing here, and simply want to know if an element <em>exists</em> (a little bit different to the original question).</p> <p>That's as simple as using any of the browser's selecting method, and checking it for a <em>truthy</em> value (generally).</p> <p>For example, if my element had an <code>id</code> of <code>"find-me"</code>, I could simply use...</p> <pre><code>var elementExists = document.getElementById("find-me"); </code></pre> <p>This is specified to either return a reference to the element or <code>null</code>. If you must have a Boolean value, simply toss a <code>!!</code> before the method call.</p> <p>In addition, you can use some of the many other methods that exist for finding elements, such as (all living off <code>document</code>):</p> <ul> <li><code>querySelector()</code>/<code>querySelectorAll()</code></li> <li><code>getElementsByClassName()</code></li> <li><code>getElementsByName()</code></li> </ul> <p>Some of these methods return a <code>NodeList</code>, so be sure to check its <code>length</code> property, because a <code>NodeList</code> is an object, and therefore <em>truthy</em>.</p> <hr> <p>For actually determining if an element exists as part of the visible DOM (like the question originally asked), <a href="https://stackoverflow.com/questions/5629684/how-can-i-check-if-an-element-exists-in-the-visible-dom/16820058#16820058">Csuwldcat provides a better solution than rolling your own</a> (as this answer used to contain). That is, to use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node.contains" rel="noreferrer">the <code>contains()</code></a> method on DOM elements.</p> <p>You could use it like so...</p> <pre><code>document.body.contains(someReferenceToADomElement); </code></pre>
{ "question_id": 5629684, "question_date": "2011-04-12T02:19:05.483Z", "question_score": 602, "tags": "javascript|dom|variables|element|exists", "answer_id": 5629730, "answer_date": "2011-04-12T02:26:02.617Z", "answer_score": 756 }
Please answer the following Stack Overflow question: Title: How to set the text color of TextView in code? <p>In XML, we can set a text color by the <code>textColor</code> attribute, like <code>android:textColor="#FF0000"</code>. But how do I change it by coding?</p> <p>I tried something like:</p> <pre><code>holder.text.setTextColor(R.color.Red); </code></pre> <p>Where <code>holder</code> is just a class and <code>text</code> is of type <code>TextView</code>. Red is an RGB value (#FF0000) set in strings.</p> <p>But it shows a different color rather than red. What kind of parameter can we pass in setTextColor()? In documentation, it says <code>int</code>, but is it a resource reference value or anything else?</p>
<p>You should use:</p> <pre><code>holder.text.setTextColor(Color.RED); </code></pre> <hr> <p>You can use various functions from the <code>Color</code> class to get the same effect of course. </p> <ul> <li><p><code>Color.parseColor</code> <a href="http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)" rel="noreferrer">(Manual)</a> (like LEX uses)</p> <pre><code>text.setTextColor(Color.parseColor("#FFFFFF")); </code></pre></li> <li><p><code>Color.rgb</code> and <code>Color.argb</code> (<a href="http://developer.android.com/reference/android/graphics/Color.html#rgb%28int,%20int,%20int%29%29" rel="noreferrer">Manual rgb</a>) (<a href="http://developer.android.com/reference/android/graphics/Color.html#argb%28int,%20int,%20int,%20int%29" rel="noreferrer">Manual argb</a>) (like Ganapathy uses)</p> <pre><code>holder.text.setTextColor(Color.rgb(200,0,0)); holder.text.setTextColor(Color.argb(0,200,0,0)); </code></pre></li> <li><p>And of course, if you want to define your color in an <code>XML</code> file, you can do this:</p> <pre><code>&lt;color name="errorColor"&gt;#f00&lt;/color&gt; </code></pre> <p>because the <code>getColor()</code> function is deprecated<sup>1</sup>, you need to use it like so:</p> <pre><code>ContextCompat.getColor(context, R.color.your_color); </code></pre></li> <li><p>You can also insert plain HEX, like so:</p> <pre><code>myTextView.setTextColor(0xAARRGGBB); </code></pre> <p>Where you have an alpha-channel first, then the color value.</p></li> </ul> <p>Check out the complete manual of course, <em><a href="http://developer.android.com/reference/android/graphics/Color.html" rel="noreferrer">public class Color extends Object</a></em>.</p> <hr> <p><sup>1</sup>This code used to be in here as well:</p> <pre><code>textView.setTextColor(getResources().getColor(R.color.errorColor)); </code></pre> <p>This method is now deprecated in Android M. You can however use it from the <a href="https://stackoverflow.com/questions/31590714/getcolorint-id-deprecated-on-android-6-0-marshmallow-api-23">contextCompat in the support library</a>, as the example now shows.</p>
{ "question_id": 4602902, "question_date": "2011-01-05T10:14:58.967Z", "question_score": 602, "tags": "android|colors|textview", "answer_id": 4602929, "answer_date": "2011-01-05T10:17:31.963Z", "answer_score": 1358 }
Please answer the following Stack Overflow question: Title: How can I upgrade specific packages using pip and a requirements file? <p>I'm using pip with a requirements file, in a virtualenv, for my Django projects. I'm trying to upgrade some packages, notably Django itself, and I'm getting an error about source code conflicts:</p> <blockquote> <p>Source in <code>&lt;virtualenv</code>&gt;/build/Django has version 1.2.3 that conflicts with Django==1.2.4 (from -r requirements/apps.txt (line 3))</p> </blockquote> <p>That's after updating the version number of Django from 1.2.3 to 1.2.4 in my requirements file. I'm using this command to actually do the upgrade:</p> <pre><code>pip --install --upgrade -E `&lt;virtualenv dir`&gt; --requirement `&lt;requirements file`&gt; </code></pre> <p>I can't find any flag that triggers a total package re-download. I even tried running an uninstall command first, and then the install, but no dice. Am I missing something?</p>
<p>First make sure you have checked <a href="https://stackoverflow.com/a/10440459/2436175">the most voted answer</a>.</p> <hr/> <p>I'm not sure if it's exactly your problem, but in my case, I wasn't able to upgrade Django to 1.2.4 - I was always finishing with 1.2.3 version, so I uninstalled Django with:</p> <pre><code>&lt;virtualenv&gt;/bin/pip uninstall Django </code></pre> <p>Then I removed <code>&lt;virtualenv&gt;/build/Django</code> directory and finally I installed the proper version with:</p> <pre><code>&lt;virtualenv&gt;/bin/pip install Django </code></pre>
{ "question_id": 4536103, "question_date": "2010-12-27T00:57:01.790Z", "question_score": 602, "tags": "django|virtualenv|pip", "answer_id": 4583509, "answer_date": "2011-01-03T09:56:19.153Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: How to "test" NoneType in python? <p>I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use <strong><em>if</em></strong> method, for example</p> <pre><code>if not new: new = '#' </code></pre> <p>I know that is the wrong way and I hope you understand what I meant.</p>
<blockquote> <p>So how can I question a variable that is a NoneType?</p> </blockquote> <p>Use <code>is</code> operator, like this</p> <pre><code>if variable is None: </code></pre> <p><strong>Why this works?</strong></p> <p>Since <a href="https://docs.python.org/2/library/constants.html#None"><code>None</code></a> is the sole singleton object of <a href="https://docs.python.org/2/library/types.html#types.NoneType"><code>NoneType</code></a> in Python, we can use <code>is</code> operator to check if a variable has <code>None</code> in it or not.</p> <p>Quoting from <a href="https://docs.python.org/2/reference/expressions.html#is"><code>is</code> docs</a>,</p> <blockquote> <p>The operators <code>is</code> and <code>is not</code> test for object identity: <code>x is y</code> is true if and only if <code>x</code> and <code>y</code> are the same object. <code>x is not y</code> yields the inverse truth value.</p> </blockquote> <p>Since there can be only one instance of <code>None</code>, <code>is</code> would be the preferred way to check <code>None</code>.</p> <hr> <p><strong>Hear it from the horse's mouth</strong></p> <p>Quoting <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations">Python's Coding Style Guidelines - PEP-008</a> (jointly defined by Guido himself),</p> <blockquote> <p>Comparisons to singletons like <strong><code>None</code> should always be done with <code>is</code> or <code>is not</code></strong>, <strong>never the equality operators</strong>.</p> </blockquote>
{ "question_id": 23086383, "question_date": "2014-04-15T14:16:07.193Z", "question_score": 602, "tags": "python|nonetype", "answer_id": 23086405, "answer_date": "2014-04-15T14:16:46.977Z", "answer_score": 910 }
Please answer the following Stack Overflow question: Title: Update all objects in a collection using LINQ <p>Is there a way to do the following using LINQ?</p> <pre><code>foreach (var c in collection) { c.PropertyToSet = value; } </code></pre> <p>To clarify, I want to iterate through each object in a collection and then update a property on each object.</p> <p>My use case is I have a bunch of comments on a blog post, and I want to iterate through each comment on a blog post and set the datetime on the blog post to be +10 hours. I could do it in SQL, but I want to keep it in the business layer.</p>
<p>While you can use a <code>ForEach</code> extension method, if you want to use just the framework you can do</p> <pre><code>collection.Select(c =&gt; {c.PropertyToSet = value; return c;}).ToList(); </code></pre> <p>The <code>ToList</code> is needed in order to evaluate the select immediately due to <em>lazy evaluation</em>.</p>
{ "question_id": 398871, "question_date": "2008-12-29T22:15:23.800Z", "question_score": 602, "tags": "c#|.net|linq|foreach", "answer_id": 399073, "answer_date": "2008-12-29T23:28:54.650Z", "answer_score": 967 }
Please answer the following Stack Overflow question: Title: Combination of async function + await + setTimeout <p>I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:</p> <pre><code> async function asyncGenerator() { // other code while (goOn) { // other code var fileList = await listFiles(nextPageToken); var parents = await requestParents(fileList); // other code } // other code } function listFiles(token) { return gapi.client.drive.files.list({ 'maxResults': sizeResults, 'pageToken': token, 'q': query }); } </code></pre> <p>The problem is, that my while loop runs too fast and the script sends too many requests per second to the google API. Therefore I would like to build a sleep function which delays the request. Thus I could also use this function to delay other requests. If there is another way to delay the request, please let me know.</p> <p>Anyway, this is my new code which does not work. The response of the request is returned to the anonymous async function within the setTimeout, but I just do not know how I can return the response to the sleep function resp. to the initial asyncGenerator function.</p> <pre><code> async function asyncGenerator() { // other code while (goOn) { // other code var fileList = await sleep(listFiles, nextPageToken); var parents = await requestParents(fileList); // other code } // other code } function listFiles(token) { return gapi.client.drive.files.list({ 'maxResults': sizeResults, 'pageToken': token, 'q': query }); } async function sleep(fn, par) { return await setTimeout(async function() { await fn(par); }, 3000, fn, par); } </code></pre> <p>I have already tried some options: storing the response in a global variable and return it from the sleep function, callback within the anonymous function, etc.</p>
<p>Your <code>sleep</code> function does not work because <code>setTimeout</code> does not (yet?) return a promise that could be <code>await</code>ed. You will need to promisify it manually:</p> <pre><code>function timeout(ms) { return new Promise(resolve =&gt; setTimeout(resolve, ms)); } async function sleep(fn, ...args) { await timeout(3000); return fn(...args); } </code></pre> <p>Btw, to slow down your loop you probably don't want to use a <code>sleep</code> function that takes a callback and defers it like this. I recommend:</p> <pre><code>while (goOn) { // other code var [parents] = await Promise.all([ listFiles(nextPageToken).then(requestParents), timeout(5000) ]); // other code } </code></pre> <p>which lets the computation of <code>parents</code> take at least 5 seconds.</p>
{ "question_id": 33289726, "question_date": "2015-10-22T20:04:42.143Z", "question_score": 602, "tags": "javascript|async-await|settimeout|ecmascript-2017", "answer_id": 33292942, "answer_date": "2015-10-23T00:21:15.763Z", "answer_score": 1025 }
Please answer the following Stack Overflow question: Title: What is the common header format of Python files? <p>I came across the following header format for Python source files in a document about Python coding guidelines:</p> <pre><code>#!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" </code></pre> <p>Is this the standard format of headers in the Python world? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)</p>
<p>Its all metadata for the <code>Foobar</code> module.</p> <p>The first one is the <code>docstring</code> of the module, that is already explained in <a href="https://stackoverflow.com/questions/1523427/python-what-is-the-common-header-format/1523435#1523435">Peter's answer</a>.</p> <blockquote> <h2><a href="http://web.archive.org/web/20111010053227/http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting" rel="noreferrer">How do I organize my modules (source files)? (Archive)</a></h2> <p><strong>The first line of each file shoud be <code>#!/usr/bin/env python</code>.</strong> This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.</p> <p><em><strong>Next should be the docstring with a description.</strong></em> If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.</p> <p><strong>All code, including import statements, should follow the docstring.</strong> Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through <code>obj.__doc__</code>) or when generating documentation with automated tools.</p> <p><strong>Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules.</strong> Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.</p> <p><strong>Next should be authorship information.</strong> This information should follow this format:</p> <pre><code>__author__ = &quot;Rob Knight, Gavin Huttley, and Peter Maxwell&quot; __copyright__ = &quot;Copyright 2007, The Cogent Project&quot; __credits__ = [&quot;Rob Knight&quot;, &quot;Peter Maxwell&quot;, &quot;Gavin Huttley&quot;, &quot;Matthew Wakefield&quot;] __license__ = &quot;GPL&quot; __version__ = &quot;1.0.1&quot; __maintainer__ = &quot;Rob Knight&quot; __email__ = &quot;[email protected]&quot; __status__ = &quot;Production&quot; </code></pre> <p>Status should typically be one of &quot;Prototype&quot;, &quot;Development&quot;, or &quot;Production&quot;. <code>__maintainer__</code> should be the person who will fix bugs and make improvements if imported. <code>__credits__</code> differs from <code>__author__</code> in that <code>__credits__</code> includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.</p> </blockquote> <p><a href="http://epydoc.sourceforge.net/manual-fields.html#module-metadata-variables" rel="noreferrer">Here</a> you have more information, listing <code>__author__</code>, <code>__authors__</code>, <code>__contact__</code>, <code>__copyright__</code>, <code>__license__</code>, <code>__deprecated__</code>, <code>__date__</code> and <code>__version__</code> as recognized metadata.</p>
{ "question_id": 1523427, "question_date": "2009-10-06T03:23:14.477Z", "question_score": 602, "tags": "python|header|comments", "answer_id": 1523456, "answer_date": "2009-10-06T03:34:00.013Z", "answer_score": 667 }
Please answer the following Stack Overflow question: Title: Declare a const array <p>Is it possible to write something similar to the following?</p> <pre><code>public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" }; </code></pre>
<p>Yes, but you need to declare it <code>readonly</code> instead of <code>const</code>:</p> <pre><code>public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" }; </code></pre> <p>The reason is that <code>const</code> can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.</p> <p>Declaring it <code>readonly</code> solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).</p> <p>Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:</p> <pre><code>public enum Titles { German, Spanish, Corrects, Wrongs }; </code></pre>
{ "question_id": 5142349, "question_date": "2011-02-28T13:04:56.917Z", "question_score": 602, "tags": "c#|.net|arrays|constants|readonly", "answer_id": 5142378, "answer_date": "2011-02-28T13:07:46.990Z", "answer_score": 873 }
Please answer the following Stack Overflow question: Title: Merging dictionaries in C# <p>What's the best way to merge 2 or more dictionaries (<code>Dictionary&lt;T1,T2&gt;</code>) in C#? (3.0 features like LINQ are fine).</p> <p>I'm thinking of a method signature along the lines of:</p> <pre><code>public static Dictionary&lt;TKey,TValue&gt; Merge&lt;TKey,TValue&gt;(Dictionary&lt;TKey,TValue&gt;[] dictionaries); </code></pre> <p>or</p> <pre><code>public static Dictionary&lt;TKey,TValue&gt; Merge&lt;TKey,TValue&gt;(IEnumerable&lt;Dictionary&lt;TKey,TValue&gt;&gt; dictionaries); </code></pre> <p><strong>EDIT:</strong> Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.</p>
<p>This partly depends on what you want to happen if you run into duplicates. For instance, you could do:</p> <pre><code>var result = dictionaries.SelectMany(dict =&gt; dict) .ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value); </code></pre> <p>That will throw an exception if you get any duplicate keys.</p> <p>EDIT: If you use ToLookup then you'll get a lookup which can have multiple values per key. You <em>could</em> then convert that to a dictionary:</p> <pre><code>var result = dictionaries.SelectMany(dict =&gt; dict) .ToLookup(pair =&gt; pair.Key, pair =&gt; pair.Value) .ToDictionary(group =&gt; group.Key, group =&gt; group.First()); </code></pre> <p>It's a bit ugly - and inefficient - but it's the quickest way to do it in terms of code. (I haven't tested it, admittedly.)</p> <p>You could write your own ToDictionary2 extension method of course (with a better name, but I don't have time to think of one now) - it's not terribly hard to do, just overwriting (or ignoring) duplicate keys. The important bit (to my mind) is using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany" rel="noreferrer"><code>SelectMany</code></a>, and realising that a dictionary supports iteration over its key/value pairs.</p>
{ "question_id": 294138, "question_date": "2008-11-16T17:39:56.440Z", "question_score": 602, "tags": "c#|dictionary|merge", "answer_id": 294145, "answer_date": "2008-11-16T17:46:11.527Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: What are Unwind segues for and how do you use them? <p>iOS 6 and Xcode 4.5 has a new feature referred to as "Unwind Segue":</p> <blockquote> <p>Unwind segues can allow transitioning to existing instances of scenes in a storyboard</p> </blockquote> <p>In addition to this brief entry in Xcode 4.5's release notes, UIViewController now seem to have a couple of new methods:</p> <pre><code>- (BOOL)canPerformUnwindSegueAction:(SEL)action fromViewController:(UIViewController *)fromViewController withSender:(id)sender - (UIViewController *)viewControllerForUnwindSegueAction:(SEL)action fromViewController:(UIViewController *)fromViewController withSender:(id)sender - (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController fromViewController:(UIViewController *)fromViewController identifier:(NSString *)identifier </code></pre> <p>How do unwind segues work and what they can be used for?</p>
<h1>In a Nutshell</h1> <p>An <strong>unwind segue</strong> (sometimes called <strong>exit segue</strong>) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.</p> <p>When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.</p> <p><em>Objective-C:</em></p> <pre><code>- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue { } </code></pre> <p><em>Swift:</em></p> <pre><code>@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) { } </code></pre> <p>The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed <code>UIStoryboardSegue</code> parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the <code>prepareForSegue:</code> method of <code>UIViewController</code>.</p> <p><strong>iOS 8 update:</strong> Unwind segues also work with iOS 8's adaptive segues, such as <em>Show</em> and <em>Show Detail</em>.</p> <h1>An Example</h1> <p>Let us have a storyboard with a navigation controller and three child view controllers:</p> <p><img src="https://i.stack.imgur.com/gyLe3.png" alt="enter image description here"></p> <p>From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:</p> <p><em>Objective-C:</em></p> <pre><code>@implementation RedViewController - (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue { } @end </code></pre> <p><em>Swift:</em></p> <pre><code>@IBAction func unwindToRed(segue: UIStoryboardSegue) { } </code></pre> <p>After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:</p> <p><img src="https://i.stack.imgur.com/rOlfW.png" alt="enter image description here"></p> <p>You must select the action which is defined in the view controller you want to unwind to:</p> <p><img src="https://i.stack.imgur.com/H03n7.png" alt="enter image description here"></p> <p>You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.</p> <p>Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:</p> <p><em>Objective-C:</em></p> <pre><code>- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue { UIViewController* sourceViewController = unwindSegue.sourceViewController; if ([sourceViewController isKindOfClass:[BlueViewController class]]) { NSLog(@"Coming from BLUE!"); } else if ([sourceViewController isKindOfClass:[GreenViewController class]]) { NSLog(@"Coming from GREEN!"); } } </code></pre> <p><em>Swift:</em></p> <pre><code>@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) { if let blueViewController = unwindSegue.sourceViewController as? BlueViewController { println("Coming from BLUE") } else if let redViewController = unwindSegue.sourceViewController as? RedViewController { println("Coming from RED") } } </code></pre> <p>Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:</p> <p><img src="https://i.stack.imgur.com/oWb8u.png" alt="enter image description here"></p> <h1>Unwinding from Code</h1> <p>When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:</p> <p><img src="https://i.stack.imgur.com/7Wx7u.png" alt="enter image description here"></p> <p>Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:</p> <p><img src="https://i.stack.imgur.com/dsqQh.png" alt="enter image description here"></p> <p>After this, the unwind segue can be performed from code just like any other segue:</p> <p><em>Objective-C:</em></p> <pre><code>[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self]; </code></pre> <p><em>Swift:</em></p> <pre><code>performSegueWithIdentifier("UnwindToRedSegueID", sender: self) </code></pre>
{ "question_id": 12561735, "question_date": "2012-09-24T08:57:08.877Z", "question_score": 602, "tags": "ios|ios6|uistoryboard", "answer_id": 15839298, "answer_date": "2013-04-05T16:49:38.447Z", "answer_score": 1287 }
Please answer the following Stack Overflow question: Title: How can I update npm on Windows? <p>I tried <a href="http://davidwalsh.name/upgrade-nodejs" rel="noreferrer">this</a>:</p> <pre><code>sudo npm cache clean -f sudo npm install -g n sudo n stable </code></pre> <p>...but it didn't work.</p> <p>How do I do this on Windows?</p>
<p>Note: The question is specifically asking how to upgrade npm, not Node.js. If you want to update Node.js over a CLI on windows, I recommend using <a href="https://community.chocolatey.org/packages/nodejs-lts" rel="noreferrer">chocolatey</a> for that.</p> <h2>What method should I choose to update NPM?</h2> <ul> <li>Node.js v16 or higher? <ul> <li><code>npm install -g npm</code></li> </ul> </li> <li>Node.js v14 or below? <ul> <li>Consider updating to latest LTS release of Node.js</li> <li><code>npm-windows-upgrade</code></li> </ul> </li> </ul> <h3><a href="https://github.com/felixrieseberg/npm-windows-upgrade" rel="noreferrer">Upgrade with npm-windows-upgrade</a></h3> <p>Run PowerShell as Administrator</p> <pre><code>Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force npm install -g npm-windows-upgrade npm-windows-upgrade </code></pre> <p>Note: if you run the Node.js installer, it will replace the Node.js version.</p> <ul> <li>Upgrades npm in-place, where Node.js installed it.</li> <li>Does not modify the default path.</li> <li>Does not change the default global package location.</li> <li>Allows easy upgrades and downgrades and to install a specific version.</li> <li>A list of versions matched between NPM and Node.js (<a href="https://nodejs.org/en/download/releases/" rel="noreferrer">https://nodejs.org/en/download/releases/</a>) - but you will need to download the <em>Node.js installer</em> and run that to update Node.js (<a href="https://nodejs.org/en/" rel="noreferrer">https://nodejs.org/en/</a>)</li> </ul> <h3>Upgrade with npm</h3> <pre><code>npm install -g npm </code></pre> <p>Note: some users still report issues updating npm with npm, but I haven't had that experience with v16+.</p>
{ "question_id": 18412129, "question_date": "2013-08-23T21:26:57.850Z", "question_score": 601, "tags": "windows|node.js|npm|package-managers", "answer_id": 31520672, "answer_date": "2015-07-20T15:37:28.240Z", "answer_score": 2417 }
Please answer the following Stack Overflow question: Title: Return multiple values to a method caller <p>I read the <a href="https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function">C++ version of this question</a> but didn't really understand it.</p> <p>Can someone please explain clearly if it can be done in C#, and how?</p>
<p>In C# 7 and above, see <a href="https://stackoverflow.com/a/36436255/316760">this answer</a>.</p> <p>In previous versions, you can use <a href="http://msdn.microsoft.com/en-us/library/system.tuple.aspx" rel="noreferrer">.NET 4.0+'s Tuple</a>:</p> <p>For Example:</p> <pre><code>public Tuple&lt;int, int&gt; GetMultipleValue() { return Tuple.Create(1,2); } </code></pre> <p>Tuples with two values have <code>Item1</code> and <code>Item2</code> as properties.</p>
{ "question_id": 748062, "question_date": "2009-04-14T15:11:57.660Z", "question_score": 601, "tags": "c#|return", "answer_id": 10278769, "answer_date": "2012-04-23T10:24:13.400Z", "answer_score": 752 }
Please answer the following Stack Overflow question: Title: OS X: equivalent of Linux's wget <p>How can I do an HTTP GET from a Un*x shell script on a stock OS X system? (installing third-party software is not an option, for this has to run on a lot of different systems which I don't have control on).</p> <p>For example if I start the Mercurial server locally doing a <em>hg serve</em>:</p> <pre><code>... $ hg serve </code></pre> <p>And then, from a Linux that has the <em>wget</em> command I do a wget:</p> <pre><code>... $ wget http://127.0.0.1:8000 --2010-12-31 22:18:25-- http://127.0.0.1:8000/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 200 Script output follows Length: unspecified [text/html] Saving to: `index.html </code></pre> <p>And on the terminal in which I launched the <em>"hg serve"</em> command, I can indeed see that an HTTP GET made its way:</p> <pre><code>127.0.0.1 - - [30/Dec/2010 22:18:17] "GET / HTTP/1.0" 200 - </code></pre> <p>So on Linux one way to do an HTTP GET from a shell script is to use <em>wget</em> (if that command is installed of course).</p> <p>What other ways are there to do the equivalent of a <em>wget</em>? I'm looking, in particular, for something that would work on stock OS X installs.</p>
<p>I'm going to have to say <code>curl http://127.0.0.1:8000 -o outfile</code></p>
{ "question_id": 4572153, "question_date": "2010-12-31T20:19:54.737Z", "question_score": 601, "tags": "macos|shell|unix|http-get", "answer_id": 4572158, "answer_date": "2010-12-31T20:21:26.373Z", "answer_score": 851 }
Please answer the following Stack Overflow question: Title: How do I run a program with commandline arguments using GDB within a Bash script? <p>When running a program on GDB, usually, the arguments for the program are given at the <code>run</code> command. Is there a way to run the program using GDB and as well as give arguments within a shell script?</p> <p>I saw an answer in a related question, mentioning that we can attach GDB to the program after the script starts executing. But then I will have to 'wait' the program.</p> <p>Is there another way to do this?</p>
<p>You can run gdb with <code>--args</code> parameter:</p> <pre><code>gdb --args executablename arg1 arg2 arg3 </code></pre> <p>If you are doing this often (e.g. when running GDB from a script), you might want to consider the following arguments to automate things further. First, you can place your GDB commands (such as 'run') in a text file and provide the filename to the <code>-x</code> argument. Second, you can have GDB exit after running your commands by providing the <code>--batch</code> argument. A full example:</p> <pre><code>gdb -x commands.txt --batch --args executablename arg1 arg2 arg3 </code></pre>
{ "question_id": 6121094, "question_date": "2011-05-25T07:42:00.587Z", "question_score": 601, "tags": "gdb|command-line-arguments", "answer_id": 6121299, "answer_date": "2011-05-25T08:00:28.050Z", "answer_score": 856 }
Please answer the following Stack Overflow question: Title: Is there a simple way to remove multiple spaces in a string? <p>Suppose this string:</p> <pre class="lang-none prettyprint-override"><code>The fox jumped over the log. </code></pre> <p>Turning into:</p> <pre class="lang-none prettyprint-override"><code>The fox jumped over the log. </code></pre> <p>What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?</p>
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(' +', ' ', 'The quick brown fox') 'The quick brown fox' </code></pre>
{ "question_id": 1546226, "question_date": "2009-10-09T21:48:37.197Z", "question_score": 601, "tags": "python|regex|string", "answer_id": 1546244, "answer_date": "2009-10-09T21:52:29.810Z", "answer_score": 809 }
Please answer the following Stack Overflow question: Title: Adding multiple class using ng-class <p>Can we have multiple expression to add multiple ng-class ?</p> <p>for eg.</p> <pre><code>&lt;div ng-class="{class1: expressionData1, class2: expressionData2}"&gt;&lt;/div&gt; </code></pre> <p>If yes can anyone put up the example to do so.</p> <p>.</p>
<p>To apply different classes when different expressions evaluate to <code>true</code>:</p> <pre><code>&lt;div ng-class="{class1 : expression1, class2 : expression2}"&gt; Hello World! &lt;/div&gt; </code></pre> <p>To apply multiple classes when an expression holds true:</p> <pre><code>&lt;!-- notice expression1 used twice --&gt; &lt;div ng-class="{class1 : expression1, class2 : expression1}"&gt; Hello World! &lt;/div&gt; </code></pre> <p>or quite simply:</p> <pre><code>&lt;div ng-class="{'class1 class2' : expression1}"&gt; Hello World! &lt;/div&gt; </code></pre> <p>Notice the single quotes surrounding css classes. </p>
{ "question_id": 18871277, "question_date": "2013-09-18T11:40:59.903Z", "question_score": 601, "tags": "angularjs|ng-class", "answer_id": 18871805, "answer_date": "2013-09-18T12:05:06.040Z", "answer_score": 1078 }
Please answer the following Stack Overflow question: Title: What is related_name used for? <p>What is the <code>related_name</code> argument useful for on <code>ManyToManyField</code> and <code>ForeignKey</code> fields? For example, given the following code, what is the effect of <code>related_name='maps'</code>?</p> <pre><code>class Map(db.Model): members = models.ManyToManyField(User, related_name='maps', verbose_name=_('members')) </code></pre>
<p>The <code>related_name</code> attribute specifies the name of the reverse relation from the <code>User</code> model back to your model.</p> <p>If you don't specify a <code>related_name</code>, Django automatically creates one using the name of your model with the suffix <code>_set</code>, for instance <code>User.map_set.all()</code>. </p> <p>If you <em>do</em> specify, e.g. <code>related_name=maps</code> on the <code>User</code> model, <code>User.map_set</code> will still work, but the <code>User.maps.</code> syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object <code>current_user</code>, you could use <code>current_user.maps.all()</code> to get all instances of your <code>Map</code> model that have a relation to <code>current_user</code>. </p> <p>The <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects" rel="noreferrer">Django documentation</a> has more details.</p>
{ "question_id": 2642613, "question_date": "2010-04-15T03:51:43.117Z", "question_score": 601, "tags": "python|django|foreign-keys|many-to-many", "answer_id": 2642645, "answer_date": "2010-04-15T04:02:01.153Z", "answer_score": 809 }
Please answer the following Stack Overflow question: Title: Checking if a variable is defined? <p>How can I check whether a variable is defined in Ruby? Is there an <code>isset</code>-type method available?</p>
<p>Use the <code>defined?</code> keyword (<a href="http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F" rel="noreferrer">documentation</a>). It will return a String with the kind of the item, or <code>nil</code> if it doesn’t exist.</p> <pre><code>&gt;&gt; a = 1 =&gt; 1 &gt;&gt; defined? a =&gt; "local-variable" &gt;&gt; defined? b =&gt; nil &gt;&gt; defined? nil =&gt; "nil" &gt;&gt; defined? String =&gt; "constant" &gt;&gt; defined? 1 =&gt; "expression" </code></pre> <p>As skalee commented: "It is worth noting that variable which is set to nil is initialized."</p> <pre><code>&gt;&gt; n = nil &gt;&gt; defined? n =&gt; "local-variable" </code></pre>
{ "question_id": 288715, "question_date": "2008-11-13T23:14:05.657Z", "question_score": 601, "tags": "ruby|reflection", "answer_id": 288726, "answer_date": "2008-11-13T23:22:27.870Z", "answer_score": 806 }
Please answer the following Stack Overflow question: Title: UIScrollView Scrollable Content Size Ambiguity <p>Fellow devs, I am having trouble with AutoLayout in Interface Builder (Xcode 5 / iOS 7). It's very basic and important so I think everyone should know how this properly works. If this is a bug in Xcode, it is a critical one!</p> <p>So, whenever I have a view hierarchy such as this I run into trouble:</p> <pre><code>&gt;UIViewController &gt;&gt; UIView &gt;&gt;&gt;UIScrollView &gt;&gt;&gt;&gt;UILabel (or any other comparable UIKit Element) </code></pre> <p>The UIScrollView has solid constraints, e.g., 50 px from every side (no problem). Then I add a Top Space constraint to the UILabel (no problem) (and I can even pin height / width of the label, changes nothing, but should be unneccessary due to the Label's intrinsic size)</p> <p><strong>The trouble starts when I add a trailing constraint to the UILabel:</strong></p> <p>E.g., Trailing Space to: Superview Equals: 25</p> <p>Now two warnings occur - and I don't understand why:</p> <p><strong>A)</strong> Scrollable Content Size Ambiguity (Scroll View has ambiguous scrollable content height/width)</p> <p><strong>B)</strong> Misplaced Views (Label Expected: x= -67 Actual: x= 207</p> <p>I did this minimal example in a freshly new project which you can download and I attached a screenshot. As you can see, Interface Builder expects the Label to sit outside of the UIScrollView's boundary (the orange dashed rectangle). Updating the Label's frame with the Resolve Issues Tool moves it right there.</p> <p>Please note: If you replace the UIScrollView with a UIView, the behaviour is as expected (the Label's frame is correct and according to the constraint). So there seems to either be an issue with UIScrollView or I am missing out on something important.</p> <p>When I run the App without updating the Label's frame as suggested by IB it is positioned just fine, exactly where it's supposed to be and the UIScrollView is scrollable. If I DO update the frame the Label is out of sight and the UIScrollView does not scroll.</p> <p><strong>Help me Obi-Wan Kenobi! Why the ambiguous layout? Why the misplaced view?</strong></p> <p>You can download the sample project here and try if you can figure out what's going on: <a href="https://github.com/Wirsing84/AutoLayoutProblem" rel="noreferrer">https://github.com/Wirsing84/AutoLayoutProblem</a></p> <p><img src="https://i.stack.imgur.com/eqoUh.png" alt="Illustration of the problem in Interface Builder"></p>
<h2>Updated</h2> <p>Nowadays, Apple realized the problem we solved many years ago (lol_face) and provides <em>Content Layout Guide</em> and <em>Frame Layout Guide</em> as part of the <code>UIScrollView</code>. Therefore you need to go through the following steps:</p> <ol> <li><p>Same as original response below;</p> </li> <li><p>For this <code>contentView</code>, <strong>set top, bottom, left, and right margins to 0</strong> pinning them to the <em>Content Layout Guide</em> of the scroll view;</p> </li> <li><p>Now set the <code>contentView</code>'s height equal to the <em>Frame Layout Guide</em>'s height. Do the same for the width;</p> </li> <li><p>Finally, set the priority of the equal height constraints to <em>250</em> (if you need the view to scroll vertically, the width to scroll horizzontally).</p> </li> </ol> <p><strong>Finished</strong>.</p> <p>Now you can add all your views in that <code>contentView</code>, and the <code>contentSize</code> of the <code>scrollView</code> will be automatically resized according with the <code>contentView</code>.</p> <p><strong>Don't forget to set the constraint from the bottom of the last object in your <code>contentView</code> to the <code>contentView</code>'s margin.</strong></p> <h2>Original [Deprecated]</h2> So I just sorted out in this way: <ol> <li><p>Inside the <code>UIScrollView</code> <strong>add</strong> a <code>UIView</code> (we can call that <code>contentView</code>);</p> </li> <li><p>In this <code>contentView</code>, <strong>set top, bottom, left and right margins to 0</strong> (of course from the <code>scrollView</code> which is the <code>superView</code>); <strong>Set also align center horizontally and vertically</strong>;</p> </li> </ol>
{ "question_id": 19036228, "question_date": "2013-09-26T18:45:38.340Z", "question_score": 601, "tags": "ios|swift|uiscrollview|autolayout|interface-builder", "answer_id": 27227174, "answer_date": "2014-12-01T11:14:54.527Z", "answer_score": 1210 }
Please answer the following Stack Overflow question: Title: What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG? <p>When should certain image file types be used when building websites or interfaces, etc?</p> <p>What are their points of strength and weakness?</p> <p>I know that PNG &amp; GIF are lossless, while JPEG is lossy.<br> But what is the main difference between PNG &amp; GIF?<br> Why should I prefer one over the other? What is SVG and when should I use it?</p> <p>If you don't care about each and every pixel, should you always use JPEG since it's the "lightest" one?</p>
<p>You should be aware of a few key factors... </p> <p>First, there are two types of compression: <a href="http://en.wikipedia.org/wiki/Lossless_data_compression" rel="noreferrer">Lossless</a> and <a href="http://en.wikipedia.org/wiki/Lossy_compression" rel="noreferrer">Lossy</a>. </p> <ul> <li><strong>Lossless</strong> means that the image is made smaller, but at no detriment to the quality. </li> <li><strong>Lossy</strong> means the image is made (even) smaller, but at a detriment to the quality. If you saved an image in a Lossy format over and over, the image quality would get progressively worse and worse.</li> </ul> <p>There are also different colour depths (palettes): <a href="http://en.wikipedia.org/wiki/Indexed_color" rel="noreferrer">Indexed color</a> and <a href="http://en.wikipedia.org/wiki/Color_depth#Direct_color" rel="noreferrer">Direct color</a>. </p> <ul> <li><strong>Indexed</strong> means that the image can only store a limited number of colours (usually 256), controlled by the author, in something called a Color Map</li> <li><strong>Direct</strong> means that you can store many <em>thousands</em> of colours that have not been directly chosen by the author</li> </ul> <hr> <p><strong>BMP</strong> - Lossless / Indexed and Direct </p> <p>This is an old format. It is Lossless (no image data is lost on save) but there's also little to no compression at all, meaning saving as BMP results in VERY large file sizes. It can have palettes of both Indexed and Direct, but that's a small consolation. The file sizes are so unnecessarily large that nobody ever really uses this format.</p> <p>Good for: Nothing really. There isn't anything BMP excels at, or isn't done better by other formats.</p> <p><img src="https://i.stack.imgur.com/J1EEX.png" alt="BMP vs GIF"></p> <hr> <p><strong>GIF</strong> - Lossless / Indexed only </p> <p>GIF uses lossless compression, meaning that you can save the image over and over and never lose any data. The file sizes are much smaller than BMP, because good compression is actually used, but it can only store an Indexed palette. This means that <a href="https://webmasters.stackexchange.com/a/39904/7654">for most use cases</a>, there can only be a maximum of 256 different colours in the file. That sounds like quite a small amount, and it is.</p> <p>GIF images can also be animated and have transparency.</p> <p>Good for: Logos, line drawings, and other simple images that need to be small. Only really used for websites.</p> <p><img src="https://i.stack.imgur.com/F7VtM.png" alt="GIF vs JPEG"></p> <hr> <p><strong>JPEG</strong> - Lossy / Direct </p> <p>JPEGs images were designed to make detailed photographic images as small as possible by removing information that the human eye won't notice. As a result it's a Lossy format, and saving the same file over and over will result in more data being lost over time. It has a palette of thousands of colours and so is great for photographs, but the lossy compression means it's bad for logos and line drawings: Not only will they look fuzzy, but such images will also have a larger file-size compared to GIFs!</p> <p>Good for: Photographs. Also, gradients.</p> <p><img src="https://i.stack.imgur.com/aNqf7.png" alt="JPEG vs GIF"></p> <hr> <p><strong>PNG-8</strong> - Lossless / Indexed </p> <p>PNG is a newer format, and PNG-8 (the indexed version of PNG) is really a good replacement for GIFs. Sadly, however, it has a few drawbacks: Firstly it cannot support animation like GIF can (well it can, but only Firefox seems to support it, unlike GIF animation which is supported by every browser). Secondly it has some support issues with older browsers like IE6. Thirdly, important software like Photoshop have very poor implementation of the format. (Damn you, Adobe!) PNG-8 can only store 256 colours, like GIFs.</p> <p>Good for: The main thing that PNG-8 does better than GIFs is having support for Alpha Transparency.</p> <p><img src="https://i.stack.imgur.com/B09oZ.png" alt="PNG-8 vs GIF"></p> <hr> <p><strong>PNG-24</strong> - Lossless / Direct</p> <p>PNG-24 is a great format that combines Lossless encoding with Direct color (thousands of colours, just like JPEG). It's very much like BMP in that regard, except that PNG actually compresses images, so it results in much smaller files. Unfortunately PNG-24 files will still be bigger than JPEGs (for photos), and GIFs/PNG-8s (for logos and graphics), so you still need to consider if you really want to use one.</p> <p>Even though PNG-24s allow thousands of colours while having compression, they are not intended to replace JPEG images. A photograph saved as a PNG-24 will likely be at least 5 times larger than a equivalent JPEG image, with very little improvement in visible quality. (Of course, this may be a desirable outcome if you're not concerned about filesize, and want to get the best quality image you can.)</p> <p>Just like PNG-8, PNG-24 supports alpha-transparency, too.</p> <hr> <p><strong>SVG</strong> - Lossless / Vector</p> <p>A filetype that is currently growing in popularity is SVG, which is different than all the above in that it's a <a href="https://en.wikipedia.org/wiki/Vector_graphics" rel="noreferrer">vector</a> file format (the above are all <a href="https://en.wikipedia.org/wiki/Raster_graphics" rel="noreferrer">raster</a>). This means that it's actually comprised of lines and curves instead of pixels. When you zoom in on a vector image, you still see a curve or a line. When you zoom in on a raster image, you will see pixels.</p> <p>For example:</p> <p><a href="https://i.stack.imgur.com/Cnaf5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cnaf5.png" alt="PNG vs SVG"></a></p> <p><a href="https://i.stack.imgur.com/UydAT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UydAT.png" alt="SVG vs PNG"></a></p> <p>This means SVG is perfect for logos and icons you wish to retain sharpness on Retina screens or at different sizes. It also means a small SVG logo can be used at a much larger (bigger) size without degradation in image quality -- something that would require a separate larger (in terms of filesize) file with raster formats.</p> <p>SVG file sizes are often tiny, even if they're visually very large, which is great. It's worth bearing in mind, however, that it does depend on the complexity of the shapes used. SVGs require more computing power than raster images because mathematical calculations are involved in drawing the curves and lines. If your logo is especially complicated it could slow down a user's computer, and even have a very large file size. It's important that you simplify your vector shapes as much as possible.</p> <p>Additionally, SVG files are written in XML, and so can be opened and edited in a text editor(!). This means its values can be manipulated on the fly. For example, you could use JavaScript to change the colour of an SVG icon on a website, much like you would some text (ie. no need for a second image), or even animate them.</p> <p>In all, they are best for simple flat shapes like logos or graphs.</p> <p>I hope that helps!</p>
{ "question_id": 2336522, "question_date": "2010-02-25T18:21:24.923Z", "question_score": 601, "tags": "image|svg|png|jpeg|gif", "answer_id": 7752936, "answer_date": "2011-10-13T10:45:33.467Z", "answer_score": 1447 }
Please answer the following Stack Overflow question: Title: Why does one use dependency injection? <p>I'm trying to understand <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injections</a> (DI), and once again I failed. It just seems silly. My code is never a mess; I hardly write virtual functions and interfaces (although I do once in a blue moon) and all my configuration is magically serialized into a class using json.net (sometimes using an XML serializer).</p> <p>I don't quite understand what problem it solves. It looks like a way to say: "hi. When you run into this function, return an object that is of this type and uses these parameters/data."<br> But... why would I ever use that? Note I have never needed to use <code>object</code> as well, but I understand what that is for.</p> <p>What are some real situations in either building a website or desktop application where one would use DI? I can come up with cases easily for why someone may want to use interfaces/virtual functions in a game, but it's extremely rare (rare enough that I can't remember a single instance) to use that in non-game code.</p>
<p>First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:</p> <blockquote> <p>Interfaces are adjectives; classes are nouns.</p> </blockquote> <p>(Actually, there are interfaces that are nouns as well, but I want to generalize here.)</p> <p>So, e.g. an interface may be something such as <code>IDisposable</code>, <code>IEnumerable</code> or <code>IPrintable</code>. A class is an actual implementation of one or more of these interfaces: <code>List</code> or <code>Map</code> may both be implementations of <code>IEnumerable</code>.</p> <p>To get the point: Often your classes depend on each other. E.g. you could have a <code>Database</code> class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class <code>Logger</code>, then <code>Database</code> has a dependency to <code>Logger</code>.</p> <p>So far, so good.</p> <p>You can model this dependency inside your <code>Database</code> class with the following line:</p> <pre><code>var logger = new Logger(); </code></pre> <p>and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...</p> <p>And of course you do <em>NOT</em> want to change all your code (meanwhile you have gazillions of it) and replace all lines</p> <pre><code>var logger = new Logger(); </code></pre> <p>by:</p> <pre><code>var logger = new TcpLogger(); </code></pre> <p>First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?</p> <p>Obviously it's a quite good idea to introduce an interface <code>ICanLog</code> (or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:</p> <pre><code>ICanLog logger = new Logger(); </code></pre> <p>Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have <code>new Logger()</code> over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:</p> <pre><code>ICanLog logger = LoggerFactory.Create(); </code></pre> <p>The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it <em>once</em>: Inside the factory.</p> <p>Now, of course, you can generalize this factory, and make it work for any type:</p> <pre><code>ICanLog logger = TypeFactory.Create&lt;ICanLog&gt;(); </code></pre> <p>Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!</p> <p>To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.</p> <p>And now, when you replace names a little bit, you end up with a simple implementation of a <em>Service Locator</em>, which is one of two patterns for <em>Inversion of Control</em> (since you invert control over who decides what exact class to instantiate).</p> <p>All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.</p> <p><em>Dependency injection</em> is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.</p> <p>With dependency injection, your <code>Database</code> class now has a constructor that requires a parameter of type <code>ICanLog</code>:</p> <pre><code>public Database(ICanLog logger) { ... } </code></pre> <p>Now your database always has a logger to use, but it does not know any more where this logger comes from.</p> <p>And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the <code>Application</code> class requires an <code>ICanPersistData</code> implementation, an instance of <code>Database</code> is injected - but for that it must first create an instance of the kind of logger which is configured for <code>ICanLog</code>. And so on ...</p> <p>So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).</p> <p>In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.</p> <p>But basically, that's it.</p> <p>P.S.: What I described here is a technique called <em>constructor injection</em>, there is also <em>property injection</em> where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.</p>
{ "question_id": 14301389, "question_date": "2013-01-13T06:59:56.097Z", "question_score": 601, "tags": "dependency-injection", "answer_id": 14301496, "answer_date": "2013-01-13T07:21:33.747Z", "answer_score": 907 }
Please answer the following Stack Overflow question: Title: Check if at least two out of three booleans are true <p>An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.</p> <p>My solution follows:</p> <pre><code>boolean atLeastTwo(boolean a, boolean b, boolean c) { if ((a &amp;&amp; b) || (b &amp;&amp; c) || (a &amp;&amp; c)) { return true; } else{ return false; } } </code></pre> <p>He said that this can be improved further, but how?</p>
<p>Rather than writing:</p> <pre><code>if (someExpression) { return true; } else { return false; } </code></pre> <p>Write:</p> <pre><code>return someExpression; </code></pre> <hr> <p>As for the expression itself, something like this:</p> <pre><code>boolean atLeastTwo(boolean a, boolean b, boolean c) { return a ? (b || c) : (b &amp;&amp; c); } </code></pre> <p>or this (whichever you find easier to grasp):</p> <pre><code>boolean atLeastTwo(boolean a, boolean b, boolean c) { return a &amp;&amp; (b || c) || (b &amp;&amp; c); } </code></pre> <p>It tests <code>a</code> and <code>b</code> exactly once, and <code>c</code> at most once.</p> <h3>References</h3> <ul> <li><a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25" rel="noreferrer">JLS 15.25 Conditional Operator ? :</a></li> </ul>
{ "question_id": 3076078, "question_date": "2010-06-19T15:46:02.063Z", "question_score": 601, "tags": "java|boolean|boolean-logic", "answer_id": 3076081, "answer_date": "2010-06-19T15:46:35.290Z", "answer_score": 841 }
Please answer the following Stack Overflow question: Title: Is there a NumPy function to return the first index of something in an array? <p>I know there is a method for a Python list to return the first index of something:</p> <pre><code>&gt;&gt;&gt; xs = [1, 2, 3] &gt;&gt;&gt; xs.index(2) 1 </code></pre> <p>Is there something like that for NumPy arrays?</p>
<p>Yes, given an array, <code>array</code>, and a value, <code>item</code> to search for, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a> as:</p> <pre><code>itemindex = numpy.where(array == item) </code></pre> <p>The result is a tuple with first all the row indices, then all the column indices.</p> <p>For example, if an array is two dimensions and it contained your item at two locations then</p> <pre><code>array[itemindex[0][0]][itemindex[1][0]] </code></pre> <p>would be equal to your item and so would be:</p> <pre><code>array[itemindex[0][1]][itemindex[1][1]] </code></pre>
{ "question_id": 432112, "question_date": "2009-01-11T01:21:39.640Z", "question_score": 600, "tags": "python|arrays|numpy", "answer_id": 432289, "answer_date": "2009-01-11T03:12:03.070Z", "answer_score": 663 }
Please answer the following Stack Overflow question: Title: Align an element to bottom with flexbox <p>I have a <code>div</code> with some children:</p> <pre><code>&lt;div class="content"&gt; &lt;h1&gt;heading 1&lt;/h1&gt; &lt;h2&gt;heading 2&lt;/h2&gt; &lt;p&gt;Some more or less text&lt;/p&gt; &lt;a href="/" class="button"&gt;Click me&lt;/a&gt; &lt;/div&gt; </code></pre> <p>and I want the following layout:</p> <pre><code> ------------------- |heading 1 | |heading 2 | |paragraph text | |can have many | |rows | | | | | | | |link-button | ------------------- </code></pre> <p>Regardless how much text is in the <code>p</code> I want to stick the <code>.button</code> always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.</p>
<p>You can use <a href="http://www.w3.org/TR/css-flexbox-1/#auto-margins">auto margins</a></p> <blockquote> <p>Prior to alignment via <a href="http://www.w3.org/TR/css-flexbox-1/#propdef-justify-content"><code>justify-content</code></a> and <a href="http://www.w3.org/TR/css-flexbox-1/#propdef-align-self"><code>align-self</code></a>, any positive free space is distributed to auto margins in that dimension.</p> </blockquote> <p>So you can use one of these (or both):</p> <pre class="lang-css prettyprint-override"><code>p { margin-bottom: auto; } /* Push following elements to the bottom */ a { margin-top: auto; } /* Push it and following elements to the bottom */ </code></pre> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { height: 200px; border: 1px solid; display: flex; flex-direction: column; } h1, h2 { margin: 0; } a { margin-top: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="content"&gt; &lt;h1&gt;heading 1&lt;/h1&gt; &lt;h2&gt;heading 2&lt;/h2&gt; &lt;p&gt;Some text more or less&lt;/p&gt; &lt;a href="/" class="button"&gt;Click me&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Alternatively, you can make the element before the <code>a</code> grow to fill the available space:</p> <pre class="lang-css prettyprint-override"><code>p { flex-grow: 1; } /* Grow to fill available space */ </code></pre> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { height: 200px; border: 1px solid; display: flex; flex-direction: column; } h1, h2 { margin: 0; } p { flex-grow: 1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="content"&gt; &lt;h1&gt;heading 1&lt;/h1&gt; &lt;h2&gt;heading 2&lt;/h2&gt; &lt;p&gt;Some text more or less&lt;/p&gt; &lt;a href="/" class="button"&gt;Click me&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 31000885, "question_date": "2015-06-23T10:56:13.790Z", "question_score": 600, "tags": "html|css|flexbox", "answer_id": 31006659, "answer_date": "2015-06-23T15:11:20.557Z", "answer_score": 923 }
Please answer the following Stack Overflow question: Title: How to initialize private static members in C++? <p>What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:</p> <pre><code>class foo { private: static int i; }; int foo::i = 0; </code></pre> <p>I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?</p>
<p>The class declaration should be in the header file (Or in the source file if not shared).<br> File: foo.h</p> <pre><code>class foo { private: static int i; }; </code></pre> <p>But the initialization should be in source file.<br> File: foo.cpp</p> <pre><code>int foo::i = 0; </code></pre> <p>If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the <code>static int i</code> must be done outside of any function.</p> <p><b>Note:</b> Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of <a href="https://en.cppreference.com/w/cpp/language/types" rel="noreferrer">const integer type</a> (<em><code>bool</code>, <code>char</code>, <code>char8_t</code> [since C++20], <code>char16_t</code>, <code>char32_t</code>, <code>wchar_t</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.</em>). You can then declare and initialize the member variable directly inside the class declaration in the header file:</p> <pre><code>class foo { private: static int const i = 42; }; </code></pre>
{ "question_id": 185844, "question_date": "2008-10-09T03:34:35.193Z", "question_score": 600, "tags": "c++|initialization|static-members", "answer_id": 185848, "answer_date": "2008-10-09T03:36:11.197Z", "answer_score": 633 }
Please answer the following Stack Overflow question: Title: JPA JoinColumn vs mappedBy <p>What is the difference between:</p> <pre><code>@Entity public class Company { @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY) @JoinColumn(name = &quot;companyIdRef&quot;, referencedColumnName = &quot;companyId&quot;) private List&lt;Branch&gt; branches; ... } </code></pre> <p>and</p> <pre><code>@Entity public class Company { @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = &quot;companyIdRef&quot;) private List&lt;Branch&gt; branches; ... } </code></pre>
<p><strong><code>@JoinColumn</code> could be used on both sides of the relationship.</strong> The question was about using <code>@JoinColumn</code> on the <code>@OneToMany</code> side (rare case). And the point here is in <em>physical information duplication</em> (column name) along with <em>not optimized SQL query that will produce some additional <code>UPDATE</code> statements</em>.</p> <p>According to <a href="http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/" rel="noreferrer">documentation</a>:</p> <p>Since <strong>many to one are</strong> (almost) always the <strong>owner side</strong> of a bidirectional relationship in the JPA spec, the one to many association is annotated by <code>@OneToMany(mappedBy=...)</code></p> <pre><code>@Entity public class Troop { @OneToMany(mappedBy="troop") public Set&lt;Soldier&gt; getSoldiers() { ... } @Entity public class Soldier { @ManyToOne @JoinColumn(name="troop_fk") public Troop getTroop() { ... } </code></pre> <p><code>Troop</code> has a bidirectional one to many relationship with <code>Soldier</code> through the troop property. You don't have to (must not) define any physical mapping in the <code>mappedBy</code> side.</p> <p>To map a bidirectional one to many, with the <strong>one-to-many side as the owning side</strong>, you have to remove the <code>mappedBy</code> element and set the many to one <code>@JoinColumn</code> as <code>insertable</code> and <code>updatable</code> to false. This solution is not optimized and will produce some additional <code>UPDATE</code> statements.</p> <pre><code>@Entity public class Troop { @OneToMany @JoinColumn(name="troop_fk") //we need to duplicate the physical information public Set&lt;Soldier&gt; getSoldiers() { ... } @Entity public class Soldier { @ManyToOne @JoinColumn(name="troop_fk", insertable=false, updatable=false) public Troop getTroop() { ... } </code></pre>
{ "question_id": 11938253, "question_date": "2012-08-13T16:17:29.470Z", "question_score": 600, "tags": "java|hibernate|jpa|orm", "answer_id": 11939045, "answer_date": "2012-08-13T17:10:55.900Z", "answer_score": 257 }
Please answer the following Stack Overflow question: Title: What is the size of column of int(11) in mysql in bytes? <p>What is the size of column of <code>int(11)</code> in mysql in bytes?</p> <p>And Maximum value that can be stored in this columns?</p>
<p>An <code>INT</code> will always be 4 bytes no matter what length is specified.</p> <ul> <li><code>TINYINT</code> = 1 byte (8 bit)</li> <li><code>SMALLINT</code> = 2 bytes (16 bit)</li> <li><code>MEDIUMINT</code> = 3 bytes (24 bit)</li> <li><code>INT</code> = 4 bytes (32 bit)</li> <li><code>BIGINT</code> = 8 bytes (64 bit).</li> </ul> <p>The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as <code>int(3)</code> will still show as 12345, but if it was stored as <code>int(10)</code> it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added <code>ZEROFILL</code> it would display as 0000012345.</p> <p>... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)</p>
{ "question_id": 5634104, "question_date": "2011-04-12T10:58:36.167Z", "question_score": 600, "tags": "mysql|types|int", "answer_id": 5634147, "answer_date": "2011-04-12T11:02:03.180Z", "answer_score": 854 }
Please answer the following Stack Overflow question: Title: Copy the entire contents of a directory in C# <p>I want to copy the entire contents of a directory from one location to another in C#.</p> <p>There doesn't appear to be a way to do this using <code>System.IO</code> classes without lots of recursion.</p> <p>There is a method in VB that we can use if we add a reference to <code>Microsoft.VisualBasic</code>:</p> <pre><code>new Microsoft.VisualBasic.Devices.Computer(). FileSystem.CopyDirectory( sourceFolder, outputFolder ); </code></pre> <p>This seems like a rather ugly hack. Is there a better way?</p>
<p>Much easier</p> <pre><code>private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePath, &quot;*&quot;, SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } //Copy all the files &amp; Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePath, &quot;*.*&quot;,SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } } </code></pre>
{ "question_id": 58744, "question_date": "2008-09-12T11:38:52.607Z", "question_score": 600, "tags": "c#|.net|directory|copy", "answer_id": 3822913, "answer_date": "2010-09-29T15:03:50.057Z", "answer_score": 627 }
Please answer the following Stack Overflow question: Title: Choose folders to be ignored during search in VS Code <p>Right now when I use <kbd>⌘</kbd>+<kbd>O</kbd> to search for files, the fuzzy matching appears to operate over all files in the current project. Unfortunately, this includes a number of files from build and vendor directories. So, for instance, if I want to search for all JavaScript files and do <kbd>⌘</kbd>+<kbd>O</kbd> and type <code>.js</code> in, the file and symbol results include around 1500 hits and all of them except the two ones are complete noise.</p> <p>Is there a way to specify certain directories to be ignored for purpose of search?</p>
<p><strong>Temporary Exclusions</strong></p> <p>From the search function, click the ellipsis to show the <code>files to include</code> and <code>files to exclude</code> text boxes. Enter any files and folder to exclude (separated by commas).</p> <p><a href="https://i.stack.imgur.com/48uW5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/48uW5.png" alt="Picture of temporarily excluding files/folders by entering them in to the files to exclude text box." /></a></p> <p><strong>Persistent Exclusions</strong></p> <p>From menu choose <code>File ➡️ Preferences ➡️ Settings ➡️ User/Workspace Settings</code> and filter default settings to <code>search</code>.</p> <ul> <li><code>User</code> settings will apply to all workspaces</li> <li><code>Workspace</code> settings will apply only to this workspace</li> </ul> <p>You can modify the <code>search.exclude</code> setting (copy from default setting to your user or workspace settings). That will apply only to searches. Note that settings from <code>files.exclude</code> will be automatically applied.</p> <p><strong>Toggling search exclusions</strong></p> <p>You can (sometimes accidentally) toggle if these exclusions are enabled or disabled when searching using the gear icon in the <code>files to exclude</code> text box. Click the ellipsis, then the gear icon to toggle.</p> <p><a href="https://i.stack.imgur.com/GJFax.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GJFax.png" alt="Picture of toggle instructions in the search field." /></a></p> <p><a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">Additional documentation on configuring settings in Visual Studio Code</a></p> <p><strong>If the settings don't work</strong></p> <p>You might also need to Clear Editor History (See: <a href="https://github.com/Microsoft/vscode/issues/6502" rel="noreferrer">https://github.com/Microsoft/vscode/issues/6502</a>).</p> <p><em><strong>Example</strong></em></p> <p>I am developing an EmberJS application which saves thousands of files under the <code>tmp</code> directory.</p> <p>If you select <code>WORKSPACE SETTINGS</code> on the right side of the search field, the search exclusion will only be applied to this particular project. And a corresponding <code>.vscode</code> folder will be added to the root folder containing <code>settings.json</code>.</p> <p>This is my example settings:</p> <pre><code>{ // ... &quot;search.exclude&quot;: { &quot;**/.git&quot;: true, &quot;**/node_modules&quot;: true, &quot;**/bower_components&quot;: true, &quot;**/tmp&quot;: true }, // ... } </code></pre> <p><strong>Note</strong>: Include a ** at the beginning of any search exclusion to cover the search term over any folders and sub-folders.</p> <p><em><strong>Picture of search before updating settings</strong></em>:</p> <p>Before updating the settings the search results are a mess.</p> <p><a href="https://i.stack.imgur.com/FrgRO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FrgRO.png" alt="Picture of search before updating settings" /></a></p> <p><em><strong>Picture of search after updating settings:</strong></em></p> <p>After updating the settings the search results are exactly what I want.</p> <p><a href="https://i.stack.imgur.com/PRsxF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PRsxF.png" alt="Picture of search after updating settings." /></a></p>
{ "question_id": 29971600, "question_date": "2015-04-30T15:20:35.970Z", "question_score": 600, "tags": "visual-studio-code", "answer_id": 33418660, "answer_date": "2015-10-29T15:40:34.917Z", "answer_score": 1068 }
Please answer the following Stack Overflow question: Title: Remove local git tags that are no longer on the remote repository <p>We use tags in git as part of our deployment process. From time to time, we want to clean up these tags by removing them from our remote repository.</p> <p>This is pretty straightforward. One user deletes the local tag and the remote tag in one set of commands. We have a little shell script that combines both steps.</p> <p>The 2nd (3rd, 4th,...) user now has local tags that are no longer reflected on the remote. </p> <p>I am looking for a command similar to <code>git remote prune origin</code> which cleans up locally tracking branches for which the remote branch has been deleted.</p> <p>Alternatively, a simple command to list remote tags could be used to compare to the local tags returned via <code>git tag -l</code>.</p>
<p>Good question. :) I don't have a complete answer...</p> <p>That said, you can get a list of remote tags via <code>git ls-remote</code>. To list the tags in the repository referenced by <code>origin</code>, you'd run:</p> <pre><code>git ls-remote --tags origin </code></pre> <p>That returns a list of hashes and friendly tag names, like:</p> <pre><code>94bf6de8315d9a7b22385e86e1f5add9183bcb3c refs/tags/v0.1.3 cc047da6604bdd9a0e5ecbba3375ba6f09eed09d refs/tags/v0.1.4 ... 2f2e45bedf67dedb8d1dc0d02612345ee5c893f2 refs/tags/v0.5.4 </code></pre> <p>You could certainly put together a bash script to compare the tags generated by this list with the tags you have locally. Take a look at <code>git show-ref --tags</code>, which generates the tag names in the same form as <code>git ls-remote</code>).</p> <hr> <p>As an aside, <code>git show-ref</code> has an option that does the opposite of what you'd like. The following command would list all the tags on the remote branch that you <em>don't</em> have locally:</p> <pre><code>git ls-remote --tags origin | git show-ref --tags --exclude-existing </code></pre>
{ "question_id": 1841341, "question_date": "2009-12-03T17:01:42.123Z", "question_score": 600, "tags": "git|git-tag", "answer_id": 1847797, "answer_date": "2009-12-04T15:43:17.487Z", "answer_score": 83 }
Please answer the following Stack Overflow question: Title: Templated check for the existence of a class member function? <p>Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?</p> <p>Here's a simple example of what I would want to write:</p> <pre><code>template&lt;class T&gt; std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T-&gt;toString)) return obj-&gt;toString(); else return "toString not defined"; } </code></pre> <p>So, if <code>class T</code> has <code>toString()</code> defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.</p>
<p>Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:</p> <pre><code>#include &lt;iostream&gt; struct Hello { int helloworld() { return 0; } }; struct Generic {}; // SFINAE test template &lt;typename T&gt; class has_helloworld { typedef char one; struct two { char x[2]; }; template &lt;typename C&gt; static one test( decltype(&amp;C::helloworld) ) ; template &lt;typename C&gt; static two test(...); public: enum { value = sizeof(test&lt;T&gt;(0)) == sizeof(char) }; }; int main(int argc, char *argv[]) { std::cout &lt;&lt; has_helloworld&lt;Hello&gt;::value &lt;&lt; std::endl; std::cout &lt;&lt; has_helloworld&lt;Generic&gt;::value &lt;&lt; std::endl; return 0; } </code></pre> <p>I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.</p>
{ "question_id": 257288, "question_date": "2008-11-02T20:10:47.673Z", "question_score": 600, "tags": "c++|templates|template-meta-programming|sfinae", "answer_id": 257382, "answer_date": "2008-11-02T21:15:01.180Z", "answer_score": 373 }
Please answer the following Stack Overflow question: Title: Why does C++ compilation take so long? <p>Compiling a C++ file takes a very long time when compared to C# and Java. It takes significantly longer to compile a C++ file than it would to run a normal size Python script. I'm currently using VC++ but it's the same with any compiler. Why is this?</p> <p>The two reasons I could think of were loading header files and running the preprocessor, but that doesn't seem like it should explain why it takes so long.</p>
<p>Several reasons</p> <h1>Header files</h1> <p>Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled. Every one of them typically has to be recompiled for every compilation unit, because the preprocessor ensures that the result of compiling a header <em>might</em> vary between every compilation unit. (A macro may be defined in one compilation unit which changes the content of the header).</p> <p>This is probably <em>the</em> main reason, as it requires huge amounts of code to be compiled for every compilation unit, and additionally, every header has to be compiled multiple times (once for every compilation unit that includes it).</p> <h1>Linking</h1> <p>Once compiled, all the object files have to be linked together. This is basically a monolithic process that can't very well be parallelized, and has to process your entire project.</p> <h1>Parsing</h1> <p>The syntax is extremely complicated to parse, depends heavily on context, and is very hard to disambiguate. This takes a lot of time.</p> <h1>Templates</h1> <p>In C#, <code>List&lt;T&gt;</code> is the only type that is compiled, no matter how many instantiations of List you have in your program. In C++, <code>vector&lt;int&gt;</code> is a completely separate type from <code>vector&lt;float&gt;</code>, and each one will have to be compiled separately.</p> <p>Add to this that templates make up a full Turing-complete "sub-language" that the compiler has to interpret, and this can become ridiculously complicated. Even relatively simple template metaprogramming code can define recursive templates that create dozens and dozens of template instantiations. Templates may also result in extremely complex types, with ridiculously long names, adding a lot of extra work to the linker. (It has to compare a lot of symbol names, and if these names can grow into many thousand characters, that can become fairly expensive).</p> <p>And of course, they exacerbate the problems with header files, because templates generally have to be defined in headers, which means far more code has to be parsed and compiled for every compilation unit. In plain C code, a header typically only contains forward declarations, but very little actual code. In C++, it is not uncommon for almost all the code to reside in header files.</p> <h1>Optimization</h1> <p>C++ allows for some very dramatic optimizations. C# or Java don't allow classes to be completely eliminated (they have to be there for reflection purposes), but even a simple C++ template metaprogram can easily generate dozens or hundreds of classes, all of which are inlined and eliminated again in the optimization phase.</p> <p>Moreover, a C++ program must be fully optimized by the compiler. A C# program can rely on the JIT compiler to perform additional optimizations at load-time, C++ doesn't get any such "second chances". What the compiler generates is as optimized as it's going to get.</p> <h1>Machine</h1> <p>C++ is compiled to machine code which may be somewhat more complicated than the bytecode Java or .NET use (especially in the case of x86). (This is mentioned out of completeness only because it was mentioned in comments and such. In practice, this step is unlikely to take more than a tiny fraction of the total compilation time).</p> <h1>Conclusion</h1> <p>Most of these factors are shared by C code, which actually compiles fairly efficiently. The parsing step is a lot more complicated in C++, and can take up significantly more time, but the main offender is probably templates. They're useful, and make C++ a far more powerful language, but they also take their toll in terms of compilation speed.</p>
{ "question_id": 318398, "question_date": "2008-11-25T18:25:14.347Z", "question_score": 600, "tags": "c++|performance|compilation", "answer_id": 318440, "answer_date": "2008-11-25T18:38:22.417Z", "answer_score": 866 }
Please answer the following Stack Overflow question: Title: "is" operator behaves unexpectedly with integers <p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
<p>Take a look at this:</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; id(a) 9987148 &gt;&gt;&gt; id(b) 9987148 &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; id(a) 11662816 &gt;&gt;&gt; id(b) 11662828 </code></pre> <p>Here's what I found in the Python 2 documentation, <a href="https://docs.python.org/2/c-api/int.html" rel="noreferrer">"Plain Integer Objects"</a> (It's the same for <a href="https://docs.python.org/3/c-api/long.html" rel="noreferrer">Python 3</a>):</p> <blockquote> <p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)</p> </blockquote>
{ "question_id": 306313, "question_date": "2008-11-20T18:21:16.603Z", "question_score": 600, "tags": "python|int|operators|identity|python-internals", "answer_id": 306353, "answer_date": "2008-11-20T18:30:20.017Z", "answer_score": 439 }
Please answer the following Stack Overflow question: Title: Uncatchable ChuckNorrisException <p>Is it possible to construct a snippet of code in <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29">Java</a> that would make a hypothetical <code>java.lang.ChuckNorrisException</code> uncatchable?</p> <p>Thoughts that came to mind are using for example interceptors or <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">aspect-oriented programming</a>.</p>
<p>I haven't tried this, so I don't know if the <a href="http://en.wikipedia.org/wiki/Java_virtual_machine" rel="noreferrer">JVM</a> would restrict something like this, but maybe you could compile code which throws <code>ChuckNorrisException</code>, but at runtime provide a class definition of <code>ChuckNorrisException</code> which <em>does not extend Throwable</em>.</p> <p>UPDATE:</p> <p>It doesn't work. It generates a verifier error:</p> <pre><code>Exception in thread "main" java.lang.VerifyError: (class: TestThrow, method: ma\ in signature: ([Ljava/lang/String;)V) Can only throw Throwable objects Could not find the main class: TestThrow. Program will exit. </code></pre> <p>UPDATE 2:</p> <p>Actually, you can get this to work if you disable the byte code verifier! (<code>-Xverify:none</code>)</p> <p>UPDATE 3:</p> <p>For those following from home, here is the full script:</p> <p>Create the following classes:</p> <pre><code>public class ChuckNorrisException extends RuntimeException // &lt;- Comment out this line on second compilation { public ChuckNorrisException() { } } public class TestVillain { public static void main(String[] args) { try { throw new ChuckNorrisException(); } catch(Throwable t) { System.out.println("Gotcha!"); } finally { System.out.println("The end."); } } } </code></pre> <p>Compile classes:</p> <pre><code>javac -cp . TestVillain.java ChuckNorrisException.java </code></pre> <p>Run:</p> <pre><code>java -cp . TestVillain Gotcha! The end. </code></pre> <p>Comment out "extends RuntimeException" and <em>recompile <code>ChuckNorrisException.java</code> only</em> :</p> <pre><code>javac -cp . ChuckNorrisException.java </code></pre> <p>Run:</p> <pre><code>java -cp . TestVillain Exception in thread "main" java.lang.VerifyError: (class: TestVillain, method: main signature: ([Ljava/lang/String;)V) Can only throw Throwable objects Could not find the main class: TestVillain. Program will exit. </code></pre> <p>Run without verification:</p> <pre><code>java -Xverify:none -cp . TestVillain The end. Exception in thread "main" </code></pre>
{ "question_id": 13883166, "question_date": "2012-12-14T17:05:39.320Z", "question_score": 600, "tags": "java|exception|exception-handling|aop", "answer_id": 13883510, "answer_date": "2012-12-14T17:27:27.823Z", "answer_score": 318 }
Please answer the following Stack Overflow question: Title: How can I create an empty file at the command line in Windows? <p>How can I create an empty file at the DOS/Windows command-line?</p> <p>I tried:</p> <pre><code>copy nul &gt; file.txt </code></pre> <p>But it always displays that a file was copied.</p> <p>Is there another method in the standard cmd?</p> <p>It should be a method that does not require the <a href="http://en.wikipedia.org/wiki/Touch_%28Unix%29" rel="noreferrer">touch</a> command from Cygwin or any other nonstandard commands. The command needs to run from a script, so keystrokes cannot be used.</p>
<p><em>Without</em> redirection, <a href="https://stackoverflow.com/users/5423827/luc-vu">Luc Vu</a> or <a href="https://stackoverflow.com/users/2474955/erik-konstantopoulos">Erik Konstantopoulos</a> <a href="https://stackoverflow.com/a/34460123/6309">point</a> <a href="https://stackoverflow.com/a/32296375/6309">out</a> to:</p> <pre><code>copy NUL EMptyFile.txt copy /b NUL EmptyFile.txt </code></pre> <hr /> <p>&quot;<a href="https://stackoverflow.com/q/210201/6309">How to create empty text file from a batch file?</a>&quot; (2008) also points to:</p> <pre><code>type NUL &gt; EmptyFile.txt # also echo. 2&gt;EmptyFile.txt copy nul file.txt &gt; nul # also in qid's answer below REM. &gt; empty.file fsutil file createnew file.cmd 0 # to create a file on a mapped drive </code></pre> <hr /> <p><a href="https://stackoverflow.com/users/3040932/nomad">Nomad</a> mentions <a href="https://stackoverflow.com/a/20237561/6309">an original one</a>:</p> <pre><code>C:\Users\VonC\prog\tests&gt;aaaa &gt; empty_file 'aaaa' is not recognized as an internal or external command, operable program or batch file. C:\Users\VonC\prog\tests&gt;dir Folder C:\Users\VonC\prog\tests 27/11/2013 10:40 &lt;REP&gt; . 27/11/2013 10:40 &lt;REP&gt; .. 27/11/2013 10:40 0 empty_file </code></pre> <p>In the same spirit, <a href="https://stackoverflow.com/users/840405/samuel">Samuel</a> suggests <a href="https://stackoverflow.com/questions/1702762/how-to-create-an-empty-file-at-the-command-line-in-windows/43677896#comment74402568_1702790">in the comments</a>:</p> <blockquote> <p>the shortest one I use is basically the one by Nomad:</p> </blockquote> <pre><code>.&gt;out.txt </code></pre> <p>It does give an error:</p> <pre><code>'.' is not recognized as an internal or external command </code></pre> <p>But this error is on stderr. And <code>&gt;</code> only redirects stdout, where <em>nothing</em> have been produced.<br /> Hence the creation of an <em>empty</em> file.<br /> The error message can be disregarded here. Or, as in <a href="https://stackoverflow.com/users/5999372/rain">Rain</a>'s <a href="https://stackoverflow.com/a/64419773/6309">answer</a>, redirected to <code>NUL</code>:</p> <pre><code>.&gt;out.txt 2&gt;NUL </code></pre> <hr /> <p>(Original answer, November 2009)</p> <pre><code>echo.&gt;filename </code></pre> <p>(<code>echo &quot;&quot;</code> would actually put &quot;&quot; in the file! And <code>echo</code> without the '.' would put &quot;<code>Command ECHO activated</code>&quot; in the file...)</p> <p>Note: the resulting file is not <em>empty</em> but includes a return line sequence: 2 bytes.</p> <hr /> <p>This <a href="http://groups.google.com/group/microsoft.public.win2000.cmdprompt.admin/msg/092e5cc12148ce2f?pli=1" rel="noreferrer">discussion</a> points to a true batch solution for a real <em>empty</em> file:</p> <pre><code> &lt;nul (set/p z=) &gt;filename dir filename 11/09/2009 19:45 0 filename 1 file(s) 0 bytes </code></pre> <blockquote> <p>The &quot;<code>&lt;nul</code>&quot; pipes a <code>nul</code> response to the <code>set/p</code> command, which will cause the variable used to remain unchanged. As usual with <code>set/p</code>, the string to the right of the equal sign is displayed as a prompt with no CRLF.</p> </blockquote> <p>Since here the &quot;string to the right of the equal sign&quot; is empty... the result is an empty file.</p> <hr /> <p>The difference with <code>cd. &gt; filename</code> (which is mentioned in <a href="https://stackoverflow.com/questions/1702762/how-to-create-an-empty-file-in-the-command-line/1703040#1703040">Patrick Cuff's answer</a> and does also produce a 0-byte-length file) is that this &quot;bit of redirection&quot; (the <code>&lt;nul...</code> trick) can be used to <strong>echo lines without any CR</strong>:</p> <pre><code>&lt;nul (set/p z=hello) &gt;out.txt &lt;nul (set/p z= world!) &gt;&gt;out.txt dir out.txt </code></pre> <blockquote> <p>The <code>dir</code> command should indicate the file size as 11 bytes: &quot;<code>helloworld!</code>&quot;.</p> </blockquote>
{ "question_id": 1702762, "question_date": "2009-11-09T18:18:14.920Z", "question_score": 599, "tags": "windows|file|cmd|command-line", "answer_id": 1702790, "answer_date": "2009-11-09T18:21:20.053Z", "answer_score": 678 }
Please answer the following Stack Overflow question: Title: Directory-tree listing in Python <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
<p>This is a way to traverse every file and directory in a directory tree:</p> <pre><code>import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git') </code></pre>
{ "question_id": 120656, "question_date": "2008-09-23T12:28:19.920Z", "question_score": 599, "tags": "python|file|directory|subdirectory|directory-tree", "answer_id": 120701, "answer_date": "2008-09-23T12:35:46.097Z", "answer_score": 629 }
Please answer the following Stack Overflow question: Title: Stop Excel from automatically converting certain text values to dates <p>Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?</p> <p>I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.</p>
<p>I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text.</p> <p>eg. ="2008-10-03",="more text"</p> <p><strong>EDIT (according to other posts)</strong>: because of the <a href="https://stackoverflow.com/a/4412775/684229">Excel 2007 bug noted by Jeffiekins</a> one should use the <a href="https://stackoverflow.com/a/6023847/684229">solution proposed by Andrew</a>: <code>"=""2008-10-03"""</code></p>
{ "question_id": 165042, "question_date": "2008-10-02T23:30:43.643Z", "question_score": 599, "tags": "excel|csv|import", "answer_id": 165052, "answer_date": "2008-10-02T23:33:21.123Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: How to encode the filename parameter of Content-Disposition header in HTTP? <p>Web applications that want to force a resource to be <em>downloaded</em> rather than directly <em>rendered</em> in a Web browser issue a <code>Content-Disposition</code> header in the HTTP response of the form:</p> <p><code>Content-Disposition: attachment; filename=<em>FILENAME</em></code></p> <p>The <code>filename</code> parameter can be used to suggest a name for the file into which the resource is downloaded by the browser. <a href="https://www.rfc-editor.org/rfc/rfc2183" rel="noreferrer">RFC 2183</a> (Content-Disposition), however, states in <a href="https://www.rfc-editor.org/rfc/rfc2183#section-2.3" rel="noreferrer">section 2.3</a> (The Filename Parameter) that the file name can only use US-ASCII characters:</p> <blockquote> <p>Current [RFC 2045] grammar restricts parameter values (and hence Content-Disposition filenames) to US-ASCII. We recognize the great desirability of allowing arbitrary character sets in filenames, but it is beyond the scope of this document to define the necessary mechanisms.</p> </blockquote> <p>There is empirical evidence, nevertheless, that most popular Web browsers today seem to permit non-US-ASCII characters yet (for the lack of a standard) disagree on the encoding scheme and character set specification of the file name. Question is then, what are the various schemes and encodings employed by the popular browsers if the file name “naïvefile” (without quotes and where the third letter is U+00EF) needed to be encoded into the Content-Disposition header?</p> <p>For the purpose of this question, <em>popular browsers</em> being:</p> <ul> <li>Google Chrome</li> <li>Safari</li> <li>Internet Explorer or Edge</li> <li>Firefox</li> <li>Opera</li> </ul>
<p>There is discussion of this, including links to browser testing and backwards compatibility, in the proposed <a href="https://www.rfc-editor.org/rfc/rfc5987" rel="nofollow noreferrer">RFC 5987</a>, &quot;Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters.&quot;</p> <p><a href="https://www.rfc-editor.org/rfc/rfc2183" rel="nofollow noreferrer">RFC 2183</a> indicates that such headers should be encoded according to <a href="https://www.rfc-editor.org/rfc/rfc2184" rel="nofollow noreferrer">RFC 2184</a>, which was obsoleted by <a href="https://www.rfc-editor.org/rfc/rfc2231" rel="nofollow noreferrer">RFC 2231</a>, covered by the draft RFC above.</p>
{ "question_id": 93551, "question_date": "2008-09-18T15:25:07.003Z", "question_score": 599, "tags": "browser|http-headers|specifications", "answer_id": 93688, "answer_date": "2008-09-18T15:39:58.607Z", "answer_score": 102 }
Please answer the following Stack Overflow question: Title: ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result" <p>Why does the following code raise the exception shown below?</p> <pre><code>BigDecimal a = new BigDecimal("1.6"); BigDecimal b = new BigDecimal("9.2"); a.divide(b) // results in the following exception. </code></pre> <p>Exception:</p> <pre><code>java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. </code></pre>
<p>From the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html" rel="noreferrer">Java 11 <code>BigDecimal</code> docs</a>:</p> <blockquote> <p>When a <code>MathContext</code> object is supplied with a precision setting of 0 (for example, <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/MathContext.html#UNLIMITED" rel="noreferrer"><code>MathContext.UNLIMITED</code></a>), arithmetic operations are exact, as are the arithmetic methods which take no <code>MathContext</code> object. (This is the only behavior that was supported in releases prior to 5.)</p> <p>As a corollary of computing the exact result, the rounding mode setting of a <code>MathContext</code> object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.</p> <p>If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an <code>ArithmeticException</code> is thrown. Otherwise, the exact result of the division is returned, as done for other operations.</p> </blockquote> <p><strong>To fix, you need to do something like this</strong>:</p> <pre><code>a.divide(b, 2, RoundingMode.HALF_UP) </code></pre> <p>where 2 is the scale and RoundingMode.HALF_UP is rounding mode</p> <p>For more details see <a href="http://jaydeepm.wordpress.com/2009/06/04/bigdecimal-and-non-terminating-decimal-expansion-error/" rel="noreferrer">this blog post</a>.</p>
{ "question_id": 4591206, "question_date": "2011-01-04T06:34:37.490Z", "question_score": 599, "tags": "java|bigdecimal|arithmeticexception", "answer_id": 4591216, "answer_date": "2011-01-04T06:37:35.633Z", "answer_score": 994 }
Please answer the following Stack Overflow question: Title: Proper way to make HTML nested list? <p>The W3 docs have a <a href="http://www.w3.org/TR/html401/struct/lists.html#h-10.2" rel="noreferrer">nested list example</a> prefixed by <code>DEPRECATED EXAMPLE:</code>, but they never corrected it with a non-deprecated example, nor explained exactly what is wrong with the example.</p> <p>So which of these ways is the correct way to write an HTML list?</p> <p><strong>Option 1</strong>: the nested <code>&lt;ul&gt;</code> is a child of the parent <code>&lt;ul&gt;</code></p> <pre><code>&lt;ul&gt; &lt;li&gt;List item one&lt;/li&gt; &lt;li&gt;List item two with subitems:&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Subitem 1&lt;/li&gt; &lt;li&gt;Subitem 2&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;Final list item&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>Option 2</strong>: the nested <code>&lt;ul&gt;</code> is a child of the <code>&lt;li&gt;</code> it belongs in</p> <pre><code>&lt;ul&gt; &lt;li&gt;List item one&lt;/li&gt; &lt;li&gt;List item two with subitems: &lt;ul&gt; &lt;li&gt;Subitem 1&lt;/li&gt; &lt;li&gt;Subitem 2&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Final list item&lt;/li&gt; &lt;/ul&gt; </code></pre>
<p><strong>Option 2</strong> is correct.</p> <p>The nested list should be <strong>inside a <code>&lt;li&gt;</code> element</strong> of the list in which it is nested.</p> <p>Link to the W3C Wiki on Lists (taken from comment below): <a href="https://www.w3.org/wiki/HTML_lists" rel="noreferrer">HTML Lists Wiki</a>.</p> <p>Link to the HTML5 W3C <code>ul</code> spec: <a href="https://www.w3.org/TR/html5/grouping-content.html#the-ul-element" rel="noreferrer">HTML5 ul</a>. Note that a <code>ul</code> element may contain exactly zero or more <code>li</code> elements. The same applies to <a href="https://www.w3.org/TR/html5/grouping-content.html#the-ol-element" rel="noreferrer">HTML5 ol</a>. The description list (<a href="https://www.w3.org/TR/html5/grouping-content.html#the-dl-element" rel="noreferrer">HTML5 dl</a>) is similar, but allows both <code>dt</code> and <code>dd</code> elements.</p> <p>More Notes:</p> <ul> <li><code>dl</code> = definition list.</li> <li><code>ol</code> = ordered list (numbers).</li> <li><code>ul</code> = unordered list (bullets).</li> </ul> <hr /> <p>Official <a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals#nesting_lists" rel="noreferrer">W3C link</a> (updated).</p>
{ "question_id": 5899337, "question_date": "2011-05-05T14:25:42.480Z", "question_score": 599, "tags": "html|html-lists|nested-lists", "answer_id": 5899394, "answer_date": "2011-05-05T14:28:46.587Z", "answer_score": 596 }
Please answer the following Stack Overflow question: Title: Should you commit .gitignore into the Git repos? <p>Do you think it is a good practice to commit <code>.gitignore</code> into a Git repo?</p> <p>Some people don't like it, but I think it is good as you can track the file's history. Isn't it?</p>
<p>Normally yes, <code>.gitignore</code> is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create <code>LOG</code> or something. In those cases you probably don't want to force that on anyone else.</p>
{ "question_id": 5765645, "question_date": "2011-04-23T17:08:02.490Z", "question_score": 599, "tags": "git|gitignore", "answer_id": 5765663, "answer_date": "2011-04-23T17:11:58.823Z", "answer_score": 580 }