input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Get a list of distinct values in List <p>In C#, say I have a class called <code>Note</code> with three string member variables.</p> <pre><code>public class Note { public string Title; public string Author; public string Text; } </code></pre> <p>And I have a list of type <code>Note</code>:</p> <pre><code>List&lt;Note&gt; Notes = new List&lt;Note&gt;(); </code></pre> <p>What would be the cleanest way to get a list of all distinct values in the Author column?</p> <p>I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.</p>
<pre><code>Notes.Select(x =&gt; x.Author).Distinct(); </code></pre> <p>This will return a sequence (<code>IEnumerable&lt;string&gt;</code>) of <code>Author</code> values -- one per unique value.</p>
{ "question_id": 10255121, "question_date": "2012-04-21T00:31:33.267Z", "question_score": 233, "tags": "c#|linq|list|distinct", "answer_id": 10255134, "answer_date": "2012-04-21T00:33:46.153Z", "answer_score": 429 }
Please answer the following Stack Overflow question: Title: How can I extract all values from a dictionary in Python? <p>I have a dictionary <code>d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}</code>.</p> <p>How do I extract all of the values of <code>d</code> into a list <code>l</code>?</p>
<p>If you only need the dictionary keys <code>1</code>, <code>2</code>, and <code>3</code> use: <code>your_dict.keys()</code>.</p> <p>If you only need the dictionary values <code>-0.3246</code>, <code>-0.9185</code>, and <code>-3985</code> use: <code>your_dict.values()</code>.</p> <p>If you want both keys and values use: <code>your_dict.items()</code> which returns a list of tuples <code>[(key1, value1), (key2, value2), ...]</code>.</p>
{ "question_id": 7002429, "question_date": "2011-08-09T20:22:14.280Z", "question_score": 233, "tags": "python|dictionary|extract", "answer_id": 7002449, "answer_date": "2011-08-09T20:23:55.933Z", "answer_score": 421 }
Please answer the following Stack Overflow question: Title: Format date in a specific timezone <p>I'm using <a href="http://momentjs.com/" rel="noreferrer">Moment.js</a> to parse and format dates in my web app. As part of a JSON object, my backend server sends dates as a number of milliseconds from the UTC epoch (Unix offset).</p> <p>Parsing dates <strong>in a specific timezone</strong> is easy -- just append the RFC 822 timezone identifier to the end of the string before parsing:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// response varies according to your timezone const m1 = moment('3/11/2012 13:00').utc().format("MM/DD HH:mm") // problem solved, always "03/11 17:00" const m2 = moment('3/11/2012 13:00 -0400').utc().format("MM/DD HH:mm") console.log({ m1, m2 })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>But how do I format a date <strong>in a specifc timezone</strong>?</p> <p>I want consistent results regardless of the browser's current time, but I don't want to display dates in UTC.</p>
<p>As pointed out in <a href="https://stackoverflow.com/a/32107411/687315">Manto's answer</a>, <a href="http://momentjs.com/docs/#/manipulating/utc-offset/" rel="noreferrer"><code>.utcOffset()</code></a> is the preferred method as of Moment 2.9.0. This function uses the real offset from UTC, not the reverse offset (e.g., -240 for New York during DST). Offset strings like "+0400" work the same as before:</p> <pre><code>// always "2013-05-23 00:55" moment(1369266934311).utcOffset(60).format('YYYY-MM-DD HH:mm') moment(1369266934311).utcOffset('+0100').format('YYYY-MM-DD HH:mm') </code></pre> <p>The older <a href="https://github.com/timrwood/moment/pull/671" rel="noreferrer"><code>.zone()</code> as a setter</a> was <strong>deprecated</strong> in Moment.js 2.9.0. It accepted a string containing a timezone identifier (e.g., "-0400" or "-04:00" for -4 hours) or a number representing minutes <em>behind</em> UTC (e.g., 240 for New York during DST).</p> <pre><code>// always "2013-05-23 00:55" moment(1369266934311).zone(-60).format('YYYY-MM-DD HH:mm') moment(1369266934311).zone('+0100').format('YYYY-MM-DD HH:mm') </code></pre> <hr> <p>To work with named timezones instead of numeric offsets, include <a href="http://momentjs.com/timezone/" rel="noreferrer">Moment Timezone</a> and use <code>.tz()</code> instead:</p> <pre><code>// determines the correct offset for America/Phoenix at the given moment // always "2013-05-22 16:55" moment(1369266934311).tz('America/Phoenix').format('YYYY-MM-DD HH:mm') </code></pre>
{ "question_id": 15347589, "question_date": "2013-03-11T20:05:51.597Z", "question_score": 233, "tags": "javascript|timezone|momentjs", "answer_id": 16703551, "answer_date": "2013-05-23T00:03:59.220Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: Loading basic HTML in Node.js <p>I'm trying to find out how to load and render a basic HTML file so I don't have to write code like:</p> <pre><code>response.write('...&lt;p&gt;blahblahblah&lt;/p&gt;...'); </code></pre>
<p>I just found <em>one</em> way using the <a href="http://nodejs.org/docs/v0.3.1/api/fs.html" rel="noreferrer">fs library</a>. I'm not certain if it's the cleanest though.</p> <pre><code>var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); }); </code></pre> <p>The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!</p>
{ "question_id": 4720343, "question_date": "2011-01-18T03:56:03.093Z", "question_score": 233, "tags": "html|node.js", "answer_id": 4720770, "answer_date": "2011-01-18T05:26:41.723Z", "answer_score": 264 }
Please answer the following Stack Overflow question: Title: Play/pause HTML 5 video using JQuery <p>I am trying to control HTML5 videos using JQuery. I have two clips in a tabbed interface, there are six tabs in total, the others just have images. I am trying to make the video clips play when their tab is clicked and then stop when any of the others are clicked.</p> <p>This must be a simple thing to do but I cant seem to get it to work, the code I am using to play the video is:</p> <pre><code>$('#playMovie1').click(function(){ $('#movie1').play(); }); </code></pre> <p>I have read that the video element needs to be exposed in a function to be able to control it but can't find an example. I am able to make it work using JS:</p> <pre><code>document.getElementById('movie1').play(); </code></pre> <p>Any advice would be great. Thanks</p>
<p>Your solution shows the issue here -- <code>play</code> is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element. You give an example of how to do this with the native DOM functions. The jQuery equivalent -- if you wanted to do this to fit in with an existing jQuery selection -- would be <code>$('#videoId').get(0).play()</code>. (<a href="http://api.jquery.com/get/" rel="noreferrer"><code>get</code></a> gets the native DOM element from the jQuery selection.)</p>
{ "question_id": 4646998, "question_date": "2011-01-10T12:50:46.347Z", "question_score": 233, "tags": "jquery|css|html|html5-video", "answer_id": 4647069, "answer_date": "2011-01-10T12:58:31.407Z", "answer_score": 394 }
Please answer the following Stack Overflow question: Title: Prompt for user input in PowerShell <p>I want to prompt the user for a series of inputs, including a password and a filename.</p> <p>I have an example of using <code>host.ui.prompt</code>, which seems sensible, but I can't understand the return.</p> <p>Is there a better way to get user input in PowerShell?</p>
<p><a href="http://technet.microsoft.com/en-us/library/hh849945.aspx" rel="noreferrer"><code>Read-Host</code></a> is a simple option for getting string input from a user.</p> <pre><code>$name = Read-Host 'What is your username?' </code></pre> <p>To hide passwords you can use:</p> <pre><code>$pass = Read-Host 'What is your password?' -AsSecureString </code></pre> <p>To convert the password to plain text:</p> <pre><code>[Runtime.InteropServices.Marshal]::PtrToStringAuto( [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass)) </code></pre> <p>As for the type returned by <code>$host.UI.Prompt()</code>, if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to <a href="http://technet.microsoft.com/en-us/library/hh849928.aspx" rel="noreferrer"><code>Get-Member</code></a> (for example, <code>$results | gm</code>). The result is a Dictionary where the key is the name of a <code>FieldDescription</code> object used in the prompt. To access the result for the first prompt in the linked example you would type: <code>$results['String Field']</code>.</p> <p>To access information without invoking a method, leave the parentheses off:</p> <pre><code>PS&gt; $Host.UI.Prompt MemberType : Method OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr ompt(string caption, string message, System.Collections.Ob jectModel.Collection[System.Management.Automation.Host.Fie ldDescription] descriptions)} TypeNameOfValue : System.Management.Automation.PSMethod Value : System.Collections.Generic.Dictionary[string,psobject] Pro mpt(string caption, string message, System.Collections.Obj ectModel.Collection[System.Management.Automation.Host.Fiel dDescription] descriptions) Name : Prompt IsInstance : True </code></pre> <p><code>$Host.UI.Prompt.OverloadDefinitions</code> will give you the definition(s) of the method. Each definition displays as <code>&lt;Return Type&gt; &lt;Method Name&gt;(&lt;Parameters&gt;)</code>.</p>
{ "question_id": 8184167, "question_date": "2011-11-18T14:41:54.453Z", "question_score": 233, "tags": "powershell", "answer_id": 8184861, "answer_date": "2011-11-18T15:35:22.490Z", "answer_score": 371 }
Please answer the following Stack Overflow question: Title: How do you represent a JSON array of strings? <p>This is all you need for valid JSON, right?</p> <pre><code>["somestring1", "somestring2"] </code></pre>
<p>I'll elaborate a bit more on <a href="https://stackoverflow.com/a/5293587/274502"><strong>ChrisR</strong> awesome answer</a> and bring images from his <a href="http://json.org/" rel="noreferrer">awesome reference</a>.</p> <p>A valid JSON always starts with either curly braces <code>{</code> or square brackets <code>[</code>, nothing else.</p> <h2><code>{</code> will start an <code>object</code>:</h2> <p><img src="https://i.stack.imgur.com/e5FEl.gif" alt="left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace" /></p> <pre><code>{ &quot;key&quot;: value, &quot;another key&quot;: value } </code></pre> <blockquote> <p><strong>Hint</strong>: although javascript accepts single quotes <code>'</code>, JSON only takes double ones <code>&quot;</code>.</p> </blockquote> <h2><code>[</code> will start an <code>array</code>:</h2> <p><img src="https://i.stack.imgur.com/PjlOm.gif" alt="left bracket followed by value, optional comma to add more value at will and finished with a right bracket" /></p> <pre><code>[value, value] </code></pre> <blockquote> <p><strong>Hint</strong>: spaces among elements are always ignored by any JSON parser.</p> </blockquote> <h2>And <code>value</code> is an <code>object</code>, <code>array</code>, <code>string</code>, <code>number</code>, <code>bool</code> or <code>null</code>:</h2> <p><img src="https://i.stack.imgur.com/NU8ua.gif" alt="Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null" /></p> <p>So yeah, <code>[&quot;a&quot;, &quot;b&quot;]</code> is a perfectly valid JSON, like you could <a href="http://jsonlint.com/" rel="noreferrer">try on the link Manish pointed</a>.</p> <p>Here are a few extra valid JSON examples, one per block:</p> <pre><code>{} [0] {&quot;__comment&quot;: &quot;json doesn't accept comments and you should not be commenting even in this way&quot;, &quot;avoid!&quot;: &quot;also, never add more than one key per line, like this&quot;} [{ &quot;why&quot;:null} ] { &quot;not true&quot;: [0, false], &quot;true&quot;: true, &quot;not null&quot;: [0, 1, false, true, { &quot;obj&quot;: null }, &quot;a string&quot;] } </code></pre>
{ "question_id": 5293555, "question_date": "2011-03-14T00:33:30.567Z", "question_score": 233, "tags": "json", "answer_id": 27425792, "answer_date": "2014-12-11T14:57:36.240Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: momentJS date string add 5 days <p>i have a start date string "20.03.2014" and i want to add 5 days to this with moment.js but i don't get the new date "25.03.2014" in the alert window.</p> <p>here my javascript Code:</p> <pre><code>startdate = "20.03.2014"; var new_date = moment(startdate, "DD-MM-YYYY").add("DD-MM-YYYY", 5); alert(new_date); </code></pre> <p>here my jsfiddle: <a href="http://jsfiddle.net/jbgUt/1/" rel="noreferrer">http://jsfiddle.net/jbgUt/1/</a></p> <p>How can i solve this ?</p> <p>I like this string format "25.03.2014"</p> <p>Hope someone can help me.</p>
<p>UPDATED: January 19, 2016</p> <p>As of moment 2.8.4 - use <code>.add(5, 'd')</code> (or <code>.add(5, 'days')</code>) instead of <code>.add('d', 5)</code></p> <pre><code>var new_date = moment(startdate, "DD-MM-YYYY").add(5, 'days'); </code></pre> <p>Thanks @Bala for the information.</p> <p>UPDATED: March 21, 2014</p> <p>This is what you'd have to do to get that format.</p> <p><a href="http://jsfiddle.net/VtoCorleone/jbgUt/2/" rel="noreferrer">Here's an updated fiddle</a></p> <pre><code>startdate = "20.03.2014"; var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5); var day = new_date.format('DD'); var month = new_date.format('MM'); var year = new_date.format('YYYY'); alert(day + '.' + month + '.' + year); </code></pre> <p>ORIGINAL: March 20, 2014</p> <p>You're not telling it how/what unit to add. Use -</p> <pre><code> var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5); </code></pre>
{ "question_id": 22547129, "question_date": "2014-03-20T23:15:30.610Z", "question_score": 233, "tags": "javascript|momentjs|add|days", "answer_id": 22547185, "answer_date": "2014-03-20T23:20:44.940Z", "answer_score": 485 }
Please answer the following Stack Overflow question: Title: How to get the response of XMLHttpRequest? <p>I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.</p> <p>Say, if I wanted to load and alert() the HTML of <a href="http://foo.com/bar.php" rel="noreferrer">http://foo.com/bar.php</a>, how would I do that?</p>
<p>You can get it by <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" rel="noreferrer"><code>XMLHttpRequest.responseText</code></a> in <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange" rel="noreferrer"><code>XMLHttpRequest.onreadystatechange</code></a> when <code>XMLHttpRequest.readyState</code> equals to <code>XMLHttpRequest.DONE</code>.</p> <p>Here's an example (not compatible with IE6/7).</p> <pre><code>var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { alert(xhr.responseText); } } xhr.open('GET', 'http://example.com', true); xhr.send(null); </code></pre> <p>For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use <a href="http://jquery.com" rel="noreferrer">jQuery</a>.</p> <pre><code>$.get('http://example.com', function(responseText) { alert(responseText); }); </code></pre> <p>Note that you've to take the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" rel="noreferrer">Same origin policy for JavaScript</a> into account when not running at localhost. You may want to consider to create a proxy script at your domain.</p>
{ "question_id": 3038901, "question_date": "2010-06-14T16:22:13.020Z", "question_score": 233, "tags": "javascript|xmlhttprequest", "answer_id": 3038972, "answer_date": "2010-06-14T16:30:01.763Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: How do I catch an Ajax query post error? <p>I would like to catch the error and show the appropriate message if the Ajax request fails.</p> <p>My code is like the following, but I could not manage to catch the failing Ajax request.</p> <pre><code>function getAjaxData(id) { $.post("status.ajax.php", {deviceId : id}, function(data){ var tab1; if (data.length&gt;0) { tab1 = data; } else { tab1 = "Error in Ajax"; } return tab1; }); } </code></pre> <p>I found out that, "Error in Ajax" is never executed when the Ajax request failed.</p> <p>How do I handle the Ajax error and show the appropriate message if it fails?</p>
<p>Since jQuery 1.5 you can use the deferred objects mechanism:</p> <pre><code>$.post('some.php', {name: 'John'}) .done(function(msg){ }) .fail(function(xhr, status, error) { // error handling }); </code></pre> <p>Another way is using <code>.ajax</code>:</p> <pre><code>$.ajax({ type: "POST", url: "some.php", data: "name=John&amp;location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("some error"); } }); </code></pre>
{ "question_id": 2833951, "question_date": "2010-05-14T12:07:35.050Z", "question_score": 233, "tags": "jquery|ajax|post|error-handling", "answer_id": 2833968, "answer_date": "2010-05-14T12:11:52.607Z", "answer_score": 349 }
Please answer the following Stack Overflow question: Title: Change URL parameters and specify defaults using JavaScript <p>I have this URL:</p> <pre><code>site.fwx?position=1&amp;archiveid=5000&amp;columns=5&amp;rows=20&amp;sorting=ModifiedTimeAsc </code></pre> <p>what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).</p>
<p>To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.</p> <p>You can use <a href="https://github.com/sindresorhus/query-string">query-string</a> as follows:</p> <pre><code>// parse the query string into an object var q = queryString.parse(location.search); // set the `row` property q.rows = 10; // convert the object to a query string // and overwrite the existing query string location.search = queryString.stringify(q); </code></pre>
{ "question_id": 1090948, "question_date": "2009-07-07T08:05:02.843Z", "question_score": 233, "tags": "javascript|url|query-string|url-parameters|url-parsing", "answer_id": 19965480, "answer_date": "2013-11-13T22:12:00.610Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: Java: Check if enum contains a given string? <p>Here's my problem - I'm looking for (if it even exists) the enum equivalent of <code>ArrayList.contains();</code>.</p> <p>Here's a sample of my code problem:</p> <pre><code>enum choices {a1, a2, b1, b2}; if(choices.???(a1)}{ //do this } </code></pre> <p>Now, I realize that an <code>ArrayList</code> of <code>Strings</code> would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.</p> <p>Assuming something like this doesn't exist, how could I go about doing it?</p>
<p>This should do it:</p> <pre><code>public static boolean contains(String test) { for (Choice c : Choice.values()) { if (c.name().equals(test)) { return true; } } return false; } </code></pre> <p>This way means you do not have to worry about adding additional enum values later, they are all checked.</p> <p><b>Edit:</b> If the enum is very large you could stick the values in a HashSet:</p> <pre><code>public static HashSet&lt;String&gt; getEnums() { HashSet&lt;String&gt; values = new HashSet&lt;String&gt;(); for (Choice c : Choice.values()) { values.add(c.name()); } return values; } </code></pre> <p>Then you can just do: <code>values.contains("your string")</code> which returns true or false.</p>
{ "question_id": 4936819, "question_date": "2011-02-08T18:27:05.030Z", "question_score": 233, "tags": "java|string|enums", "answer_id": 4936895, "answer_date": "2011-02-08T18:35:04.663Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: How to add directory to classpath in an application run profile in IntelliJ IDEA? <p>I'm trying to add a directory to the classpath of an application run profile</p> <p>If I override by using -cp x:target/classes in the VM settings, I get the following error:</p> <pre><code>java.lang.NoClassDefFoundError: com/intellij/rt/execution/application/AppMain </code></pre> <p>Any idea on how to add a directory to the classpath for my project?</p>
<p>In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:</p> <ol> <li>click on the Project view or unhide it by clicking on the "1: Project" button on the left border of the window or by pressing Alt + 1</li> <li>find your project or sub-module and click on it to highlight it, then press F4, or right click and choose "Open Module Settings" (on IntelliJ 14 it became F12)</li> <li>click on the dependencies tab</li> <li>Click the "+" button on the right and select "Jars or directories..."</li> <li>Find your path and click OK</li> <li>In the dialog with "Choose Categories of Selected File", choose <code>Classes</code> (even if it's properties), press OK and OK again</li> <li>You can now run your application and it will have the selected path in the class path </li> </ol>
{ "question_id": 854264, "question_date": "2009-05-12T18:51:03.943Z", "question_score": 233, "tags": "java|intellij-idea|classpath", "answer_id": 24843914, "answer_date": "2014-07-19T19:02:02.263Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: How to send an email with Python? <p>This code works and sends me an email just fine: </p> <pre><code>import smtplib #SERVER = "localhost" FROM = '[email protected]' TO = ["[email protected]"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP('myserver') server.sendmail(FROM, TO, message) server.quit() </code></pre> <p>However if I try to wrap it in a function like this:</p> <pre><code>def sendMail(FROM,TO,SUBJECT,TEXT,SERVER): import smtplib """this is some test documentation in the function""" message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() </code></pre> <p>and call it I get the following errors: </p> <pre><code> Traceback (most recent call last): File "C:/Python31/mailtest1.py", line 8, in &lt;module&gt; sendmail.sendMail(sender,recipients,subject,body,server) File "C:/Python31\sendmail.py", line 13, in sendMail server.sendmail(FROM, TO, message) File "C:\Python31\lib\smtplib.py", line 720, in sendmail self.rset() File "C:\Python31\lib\smtplib.py", line 444, in rset return self.docmd("rset") File "C:\Python31\lib\smtplib.py", line 368, in docmd return self.getreply() File "C:\Python31\lib\smtplib.py", line 345, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed </code></pre> <p>Can anyone help me understand why? </p>
<p>I recommend that you use the standard packages <a href="https://docs.python.org/3/library/email.html" rel="noreferrer"><code>email</code></a> and <a href="https://docs.python.org/3/library/smtplib.html" rel="noreferrer"><code>smtplib</code></a> together to send email. Please look at the following example (reproduced from the <a href="https://docs.python.org/3/library/email.examples.html" rel="noreferrer">Python documentation</a>). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.</p> <pre><code># Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. with open(textfile, 'rb') as fp: # Create a text/plain message msg = MIMEText(fp.read()) # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit() </code></pre> <p>For sending email to multiple destinations, you can also follow the example in the <a href="https://docs.python.org/3/library/email.examples.html" rel="noreferrer">Python documentation</a>:</p> <pre><code># Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = ', '.join(family) msg.preamble = 'Our family reunion' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. with open(file, 'rb') as fp: img = MIMEImage(fp.read()) msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(me, family, msg.as_string()) s.quit() </code></pre> <p>As you can see, the header <code>To</code> in the <code>MIMEText</code> object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the <code>sendmail</code> function must be a list of strings (each string is an email address).</p> <p>So, if you have three email addresses: <code>[email protected]</code>, <code>[email protected]</code>, and <code>[email protected]</code>, you can do as follows (obvious sections omitted):</p> <pre><code>to = ["[email protected]", "[email protected]", "[email protected]"] msg['To'] = ",".join(to) s.sendmail(me, to, msg.as_string()) </code></pre> <p>the <code>",".join(to)</code> part makes a single string out of the list, separated by commas.</p> <p>From your questions I gather that you have not gone through <a href="https://docs.python.org/3/tutorial/index.html" rel="noreferrer">the Python tutorial</a> - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.</p>
{ "question_id": 6270782, "question_date": "2011-06-07T19:48:05.047Z", "question_score": 233, "tags": "python|email|function|smtplib", "answer_id": 6270987, "answer_date": "2011-06-07T20:07:33.873Z", "answer_score": 240 }
Please answer the following Stack Overflow question: Title: MySQL Incorrect datetime value: '0000-00-00 00:00:00' <p>I've recently taken over an old project that was created 10 years ago. It uses MySQL 5.1.</p> <p>Among other things, I need to change the default character set from latin1 to utf8.</p> <p>As an example, I have tables such as this: </p> <pre><code> CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `first_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL, `last_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL, `username` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL, `email` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL, `pass` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL, `active` char(1) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'Y', `created` datetime NOT NULL, `last_login` datetime DEFAULT NULL, `author` varchar(1) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT 'N', `locked_at` datetime DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `ripple_token` varchar(36) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL, `ripple_token_expires` datetime DEFAULT '2014-10-31 08:03:55', `authentication_token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `index_users_on_reset_password_token` (`reset_password_token`), UNIQUE KEY `index_users_on_confirmation_token` (`confirmation_token`), UNIQUE KEY `index_users_on_unlock_token` (`unlock_token`), KEY `users_active` (`active`), KEY `users_username` (`username`), KEY `index_users_on_email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=1677 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC </code></pre> <p>I set up my own Mac to work on this. Without thinking too much about it, I ran "brew install mysql" which installed MySQL 5.7. So I have some version conflicts.</p> <p>I downloaded a copy of this database and imported it. </p> <p>If I try to run a query like this: </p> <pre><code> ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL </code></pre> <p>I get this error: </p> <pre><code> ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1 </code></pre> <p>I thought I could fix this with: </p> <pre><code> ALTER TABLE users MODIFY created datetime NULL DEFAULT '1970-01-01 00:00:00'; Query OK, 0 rows affected (0.06 sec) Records: 0 Duplicates: 0 Warnings: 0 </code></pre> <p>but I get: </p> <pre><code> ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ; ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1 </code></pre> <p>Do I have to update every value? </p>
<p>My suggestion if it is the case that the table is empty or not very very big is to export the create statements as a .sql file, rewrite them as you wish. Also do the same if you have any existing data, i.e. export insert statements (I recommend doing this in a separate file as the create statements). Finally, drop the table and execute first create statement and then inserts.</p> <p>You can use for that either <code>mysqldump</code> command, included in your MySQL installation or you can also install MySQL Workbench, which is a free graphical tool that includes also this option in a very customisable way without having to look for specific command options.</p>
{ "question_id": 35565128, "question_date": "2016-02-22T22:23:04.050Z", "question_score": 233, "tags": "mysql", "answer_id": 35565334, "answer_date": "2016-02-22T22:36:41.197Z", "answer_score": 9 }
Please answer the following Stack Overflow question: Title: Iterating over Typescript Map <p>I'm trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem.</p> <p>My code is:</p> <pre><code>myMap : Map&lt;string, boolean&gt;; for(let key of myMap.keys()) { console.log(key); } </code></pre> <p>And I get the Error:</p> <blockquote> <p>Type 'IterableIteratorShim&lt;[string, boolean]>' is not an array type or a string type.</p> </blockquote> <p>Full Stack Trace:</p> <pre><code> Error: Typescript found the following errors: /home/project/tmp/broccoli_type_script_compiler-input_base_path-q4GtzHgb.tmp/0/src/app/project/project-data.service.ts (21, 20): Type 'IterableIteratorShim&lt;[string, boolean]&gt;' is not an array type or a string type. at BroccoliTypeScriptCompiler._doIncrementalBuild (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:115:19) at BroccoliTypeScriptCompiler.build (/home/project/node_modules/angular-cli/lib/broccoli/broccoli-typescript.js:43:10) at /home/project/node_modules/broccoli-caching-writer/index.js:152:21 at lib$rsvp$$internal$$tryCatch (/home/project/node_modules/rsvp/dist/rsvp.js:1036:16) at lib$rsvp$$internal$$invokeCallback (/home/project/node_modules/rsvp/dist/rsvp.js:1048:17) at lib$rsvp$$internal$$publish (/home/project/node_modules/rsvp/dist/rsvp.js:1019:11) at lib$rsvp$asap$$flush (/home/project/node_modules/rsvp/dist/rsvp.js:1198:9) at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9) </code></pre> <p>I'm using angular-cli beta5 and typescript 1.8.10 and my target is es5. Has anyone had this Problem?</p>
<p>You could use <code>Map.prototype.forEach((value, key, map) =&gt; void, thisArg?) : void</code> instead</p> <p>Use it like this:</p> <pre><code>myMap.forEach((value: boolean, key: string) =&gt; { console.log(key, value); }); </code></pre>
{ "question_id": 37699320, "question_date": "2016-06-08T10:01:15.740Z", "question_score": 233, "tags": "typescript|iterator|maps", "answer_id": 37700588, "answer_date": "2016-06-08T10:57:59.783Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: Parsing HTML using Python <p>I'm looking for an HTML Parser module for Python that can help me get the tags in the form of Python lists/dictionaries/objects.</p> <p>If I have a document of the form:</p> <pre><code>&lt;html&gt; &lt;head&gt;Heading&lt;/head&gt; &lt;body attr1='val1'&gt; &lt;div class='container'&gt; &lt;div id='class'&gt;Something here&lt;/div&gt; &lt;div&gt;Something else&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>then it should give me a way to access the nested tags via the name or id of the HTML tag so that I can basically ask it to get me the content/text in the <code>div</code> tag with <code>class='container'</code> contained within the <code>body</code> tag, or something similar.</p> <p>If you've used Firefox's "Inspect element" feature (view HTML) you would know that it gives you all the tags in a nice nested manner like a tree.</p> <p>I'd prefer a built-in module but that might be asking a little too much.</p> <hr> <p>I went through a lot of questions on Stack Overflow and a few blogs on the internet and most of them suggest BeautifulSoup or lxml or HTMLParser but few of these detail the functionality and simply end as a debate over which one is faster/more efficent.</p>
<blockquote> <p>So that I can ask it to get me the content/text in the div tag with class='container' contained within the body tag, Or something similar.</p> </blockquote> <pre><code>try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup html = #the HTML code you've written above parsed_html = BeautifulSoup(html) print(parsed_html.body.find('div', attrs={'class':'container'}).text) </code></pre> <p>You don't need performance descriptions I guess - just read how BeautifulSoup works. Look at its <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer">official documentation</a>.</p>
{ "question_id": 11709079, "question_date": "2012-07-29T12:00:42.903Z", "question_score": 233, "tags": "python|xml-parsing|html-parsing", "answer_id": 11709155, "answer_date": "2012-07-29T12:12:15.873Z", "answer_score": 260 }
Please answer the following Stack Overflow question: Title: Adding a HTTP header to the Angular HttpClient doesn't send the header, why? <p>Here is my code: </p> <pre class="lang-js prettyprint-override"><code>import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; </code></pre> <hr> <pre class="lang-js prettyprint-override"><code>logIn(username: string, password: string) { const url = 'http://server.com/index.php'; const body = JSON.stringify({username: username, password: password}); const headers = new HttpHeaders(); headers.set('Content-Type', 'application/json; charset=utf-8'); this.http.post(url, body, {headers: headers}).subscribe( (data) =&gt; { console.log(data); }, (err: HttpErrorResponse) =&gt; { if (err.error instanceof Error) { console.log('Client-side error occured.'); } else { console.log('Server-side error occured.'); } } ); } </code></pre> <p>and here the network debug:</p> <pre><code>Request Method:POST Status Code:200 OK Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8 Cache-Control:no-cache Connection:keep-alive Content-Length:46 Content-Type:text/plain </code></pre> <p>and Data are stored in 'Request Payload' but in my server doesn't received the POST values:</p> <pre><code>print_r($_POST); Array ( ) </code></pre> <p>I believe the error comes from the header not set during the POST, what did I do wrong?</p>
<p>The instances of the new <code>HttpHeader</code> class are <strong>immutable</strong> objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:</p> <pre class="lang-js prettyprint-override"><code>let headers = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json; charset=utf-8'); </code></pre> <p>or</p> <pre class="lang-js prettyprint-override"><code>const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'}); </code></pre> <p><strong>Update: adding multiple headers</strong></p> <pre class="lang-js prettyprint-override"><code>let headers = new HttpHeaders(); headers = headers.set('h1', 'v1').set('h2','v2'); </code></pre> <p>or</p> <pre class="lang-js prettyprint-override"><code>const headers = new HttpHeaders({'h1':'v1','h2':'v2'}); </code></pre> <p><strong>Update: accept object map for HttpClient headers &amp; params</strong></p> <p>Since <a href="https://github.com/angular/angular/pull/18490" rel="noreferrer">5.0.0-beta.6</a> is now possible to skip the creation of a <code>HttpHeaders</code> object an directly pass an object map as argument. So now its possible to do the following:</p> <pre><code>http.get('someurl',{ headers: {'header1':'value1','header2':'value2'} }); </code></pre>
{ "question_id": 45286764, "question_date": "2017-07-24T17:38:53.683Z", "question_score": 233, "tags": "angular|http-headers|angular-httpclient", "answer_id": 45286959, "answer_date": "2017-07-24T17:50:49.970Z", "answer_score": 393 }
Please answer the following Stack Overflow question: Title: Configure Node.js to log to a file instead of the console <p>Can I configure <code>console.log</code> so that the logs are written on a file instead of being printed in the console?</p>
<p><strong><em>Update 2013 -</em></strong> This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend <a href="https://github.com/flatiron/winston" rel="noreferrer">Winston</a></p> <p><strong><em>Update Late 2013 -</em></strong> We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js <a href="https://gist.github.com/rtgibbons/7354879" rel="noreferrer">https://gist.github.com/rtgibbons/7354879</a></p> <hr> <p>Should be as simple as this. </p> <pre><code>var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' }) , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' }); // redirect stdout / stderr proc.stdout.pipe(access); proc.stderr.pipe(error); </code></pre>
{ "question_id": 8393636, "question_date": "2011-12-05T23:58:37.163Z", "question_score": 233, "tags": "node.js|logging|console.log", "answer_id": 8393841, "answer_date": "2011-12-06T00:28:20.197Z", "answer_score": 86 }
Please answer the following Stack Overflow question: Title: Turn off constraints temporarily (MS SQL) <p>I'm looking for a way to temporarily turn off all DB's constraints (eg table relationships).</p> <p>I need to copy (using INSERTs) one DB's tables to another DB. I know I can achieve that by executing commands in proper order (to not break relationships).</p> <p>But it would be easier if I could turn off checking constraints temporarily and turn it back on after the operation's finish.</p> <p>Is this possible?</p>
<p>You can disable FK and CHECK constraints <strike>only in SQL 2005+</strike>. See <a href="http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx" rel="noreferrer">ALTER TABLE</a></p> <pre><code>ALTER TABLE foo NOCHECK CONSTRAINT ALL </code></pre> <p>or</p> <pre><code>ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column </code></pre> <p>Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.</p>
{ "question_id": 737115, "question_date": "2009-04-10T09:04:51.507Z", "question_score": 233, "tags": "sql|sql-server|sql-server-2005|constraints|entity-relationship", "answer_id": 737167, "answer_date": "2009-04-10T09:36:55.737Z", "answer_score": 234 }
Please answer the following Stack Overflow question: Title: Is it possible to pull just one file in Git? <p>I am working on a Git branch that has some broken tests, and I would like to pull (merge changes, not just overwrite) these tests from another branch where they are already fixed.</p> <p>I know I can do</p> <pre><code>git pull origin that_other_branch </code></pre> <p>but this will attempt to merge lots of other files, for that I am not yet ready.</p> <p>Is it possible to pull and merge only the specified file (and not everything) from that another branch?</p> <p>This is not a duplicate of <em><a href="https://stackoverflow.com/questions/8421552/git-pull-request-for-just-one-file">Git pull request for just one file</a></em> as all answers to that question are how to revert the locally changed file to the repository version, without changing any branches.</p>
<p>You can fetch and then check out only one file in this way:</p> <pre><code>git fetch git checkout -m &lt;revision&gt; &lt;yourfilepath&gt; git add &lt;yourfilepath&gt; git commit </code></pre> <p><strong>Regarding the <code>git checkout</code> command:</strong></p> <ul> <li><code>&lt;revision&gt;</code> -- a branch name, i.e. <code>origin/master</code></li> <li><code>&lt;yourfilepath&gt;</code> does not include the repository name (that you can get from clicking <code>copy path</code> button on a file page on GitHub), i.e. <code>README.md</code></li> </ul>
{ "question_id": 16230838, "question_date": "2013-04-26T07:20:24.223Z", "question_score": 233, "tags": "git|git-merge|git-pull|git-fetch", "answer_id": 16230900, "answer_date": "2013-04-26T07:24:51.110Z", "answer_score": 210 }
Please answer the following Stack Overflow question: Title: How to check if a process id (PID) exists <p>In a bash script, I want to do the following (in pseudo-code):</p> <pre><code>if [ a process exists with $PID ]; then kill $PID fi </code></pre> <p>What's the appropriate expression for the conditional statement?</p>
<p>To check for the existence of a process, use</p> <pre><code>kill -0 $pid </code></pre> <p>But just as <a href="https://stackoverflow.com/a/3043991/4575793">@unwind said</a>, if you want it to terminate in any case, then just</p> <pre><code>kill $pid </code></pre> <p>Otherwise you will have a race condition, where the process might have disappeared after the first <code>kill -0</code>.</p> <p>If you want to ignore the text output of <code>kill</code> and do something based on the exit code, you can</p> <pre><code>if ! kill $pid &gt; /dev/null 2&gt;&amp;1; then echo &quot;Could not send SIGTERM to process $pid&quot; &gt;&amp;2 fi </code></pre>
{ "question_id": 3043978, "question_date": "2010-06-15T09:30:26.743Z", "question_score": 233, "tags": "bash|process|pid", "answer_id": 3044045, "answer_date": "2010-06-15T09:40:23.260Z", "answer_score": 206 }
Please answer the following Stack Overflow question: Title: Change the current directory from a Bash script <p>Is it possible to change current directory from a script?</p> <p>I want to create a utility for directory navigation in Bash. I have created a test script that looks like the following:</p> <pre><code>#!/bin/bash cd /home/artemb </code></pre> <p>When I execute the script from the Bash shell the current directory doesn't change. Is it possible at all to change the current shell directory from a script?</p>
<p>You need to convert your script to a shell function:</p> <pre><code>#!/bin/bash # # this script should not be run directly, # instead you need to source it from your .bashrc, # by adding this line: # . ~/bin/myprog.sh # function myprog() { A=$1 B=$2 echo "aaa ${A} bbb ${B} ccc" cd /proc } </code></pre> <p>The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.</p> <p>By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.</p>
{ "question_id": 874452, "question_date": "2009-05-17T11:58:01.867Z", "question_score": 233, "tags": "bash|environment", "answer_id": 874542, "answer_date": "2009-05-17T12:46:45.477Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: Recursive directory listing in DOS <p>How do we achieve a recursive directory listing in DOS?</p> <p>I'm looking for a command or a script in DOS which can give me the recursive directory listing similar to <code>ls -R</code> command in Unix.</p>
<p>You can use:</p> <pre><code>dir /s </code></pre> <p>If you need the list without all the header/footer information try this:</p> <pre><code>dir /s /b </code></pre> <p>(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)</p>
{ "question_id": 2376801, "question_date": "2010-03-04T04:03:25.173Z", "question_score": 233, "tags": "dos|directory-listing", "answer_id": 2376808, "answer_date": "2010-03-04T04:06:42.757Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: How to run multiple Python versions on Windows <p>I had two versions of Python installed on my machine (versions 2.6 and 2.5). I want to run 2.6 for one project and 2.5 for another. </p> <p>How can I specify which I want to use?</p> <p>I am working on Windows XP SP2.</p>
<p>Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing <code>python</code>. </p> <p>What this does under Windows, is to trawl the <code>%PATH%</code> environment variable, checking for an executable, either batch file (<code>.bat</code>), command file (<code>.cmd</code>) or some other executable to run (this is controlled by the <code>PATHEXT</code> environment variable), that matches the name given. When it finds the correct file to run the file is being run.</p> <p>Now, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like <code>PATH=c:\python\2.5;c:\python\2.6</code> but Windows will stop examining the path when it finds a match.</p> <p>What you really need to do is to explicitly call one or both of the applications, such as <code>c:\python\2.5\python.exe</code> or <code>c:\python\2.6\python.exe</code>.</p> <p>The other alternative is to create a shortcut to the respective <code>python.exe</code> calling one of them <code>python25</code> and the other <code>python26</code>; you can then simply run <code>python25</code> on your command line.</p>
{ "question_id": 4583367, "question_date": "2011-01-03T09:30:33.650Z", "question_score": 233, "tags": "python|windows|compatibility", "answer_id": 4584180, "answer_date": "2011-01-03T11:54:11.343Z", "answer_score": 171 }
Please answer the following Stack Overflow question: Title: jQuery Scroll to bottom of page/iframe <p>How do I use jquery to scroll right down to the bottom of an iframe or page?</p>
<p>If you want a nice slow animation scroll, for any anchor with <code>href="#bottom"</code> this will scroll you to the bottom:</p> <pre><code>$("a[href='#bottom']").click(function() { $("html, body").animate({ scrollTop: $(document).height() }, "slow"); return false; }); </code></pre> <p>Feel free to change the selector.</p>
{ "question_id": 1890995, "question_date": "2009-12-11T21:30:54.130Z", "question_score": 233, "tags": "jquery|scroll|scrollto", "answer_id": 1891142, "answer_date": "2009-12-11T22:00:58.650Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: How to specify HTTP error code using Express.js? <p>I have tried:</p> <pre><code>app.get('/', function(req, res, next) { var e = new Error('error message'); e.status = 400; next(e); }); </code></pre> <p>and:</p> <pre><code>app.get('/', function(req, res, next) { res.statusCode = 400; var e = new Error('error message'); next(e); }); </code></pre> <p>but always an error code of 500 is announced.</p>
<p>Per the Express (Version 4+) docs, you can use:</p> <pre><code>res.status(400); res.send('None shall pass'); </code></pre> <p><a href="http://expressjs.com/4x/api.html#res.status">http://expressjs.com/4x/api.html#res.status</a></p> <p>&lt;=3.8</p> <pre><code>res.statusCode = 401; res.send('None shall pass'); </code></pre>
{ "question_id": 10563644, "question_date": "2012-05-12T12:17:28.833Z", "question_score": 233, "tags": "node.js|express|http-status-codes", "answer_id": 23394294, "answer_date": "2014-04-30T17:19:51.927Z", "answer_score": 393 }
Please answer the following Stack Overflow question: Title: Calculating moving average <p>I'm trying to use R to calculate the moving average over a series of values in a matrix. There doesn't seem to be a <a href="http://www.statmethods.net/management/functions.html" rel="noreferrer">built-in function</a> in R that will allow me to calculate moving averages. Do any packages provide one? Or do I need to write my own?</p>
<ul> <li>Rolling Means/Maximums/Medians in the <a href="http://cran.r-project.org/package=zoo" rel="noreferrer">zoo</a> package (rollmean)</li> <li>MovingAverages in <a href="http://cran.r-project.org/package=TTR" rel="noreferrer">TTR</a></li> <li>ma in <a href="http://cran.r-project.org/package=forecast" rel="noreferrer">forecast</a></li> </ul>
{ "question_id": 743812, "question_date": "2009-04-13T12:52:51.980Z", "question_score": 233, "tags": "r|moving-average", "answer_id": 743846, "answer_date": "2009-04-13T13:06:55.380Z", "answer_score": 164 }
Please answer the following Stack Overflow question: Title: Difference between natural join and inner join <p>What is the difference between a natural join and an inner join?</p>
<p>One significant difference between INNER JOIN and NATURAL JOIN is the number of columns returned.</p> <p>Consider:</p> <pre><code>TableA TableB +------------+----------+ +--------------------+ |Column1 | Column2 | |Column1 | Column3 | +-----------------------+ +--------------------+ | 1 | 2 | | 1 | 3 | +------------+----------+ +---------+----------+ </code></pre> <p>The <code>INNER JOIN</code> of TableA and TableB on Column1 will return</p> <pre><code>SELECT * FROM TableA AS a INNER JOIN TableB AS b USING (Column1); SELECT * FROM TableA AS a INNER JOIN TableB AS b ON a.Column1 = b.Column1; </code></pre> <pre><code>+------------+-----------+---------------------+ | a.Column1 | a.Column2 | b.Column1| b.Column3| +------------------------+---------------------+ | 1 | 2 | 1 | 3 | +------------+-----------+----------+----------+ </code></pre> <p>The <code>NATURAL JOIN</code> of TableA and TableB on Column1 will return:</p> <pre><code>SELECT * FROM TableA NATURAL JOIN TableB +------------+----------+----------+ |Column1 | Column2 | Column3 | +-----------------------+----------+ | 1 | 2 | 3 | +------------+----------+----------+ </code></pre> <p>The repeated column is avoided.</p> <p>(AFAICT from the standard grammar, you can't specify the joining columns in a natural join; the join is strictly name-based. See also <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29#Natural_join" rel="noreferrer">Wikipedia</a>.)</p> <p>(<em>There's a cheat in the inner join output; the <code>a.</code> and <code>b.</code> parts would not be in the column names; you'd just have <code>column1</code>, <code>column2</code>, <code>column1</code>, <code>column3</code> as the headings.</em>)</p>
{ "question_id": 8696383, "question_date": "2012-01-01T23:45:58.847Z", "question_score": 233, "tags": "sql|join|natural-join", "answer_id": 8696402, "answer_date": "2012-01-01T23:51:06.877Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: Limit the length of a string with AngularJS <p>I have the following:</p> <pre><code>&lt;div&gt;{{modal.title}}&lt;/div&gt; </code></pre> <p>Is there a way that I could limit the length of the string to say 20 characters?</p> <p>And an even better question would be is there a way that I could change the string to be truncated and show <code>...</code> at the end if it's more than 20 characters?</p>
<p><strong>Edit</strong> The latest version of <code>AngularJS</code>offers <a href="https://docs.angularjs.org/api/ng/filter/limitTo" rel="noreferrer"><code>limitTo</code> filter</a>.</p> <p>You need a <em>custom filter</em> like this:</p> <pre><code>angular.module('ng').filter('cut', function () { return function (value, wordwise, max, tail) { if (!value) return ''; max = parseInt(max, 10); if (!max) return value; if (value.length &lt;= max) return value; value = value.substr(0, max); if (wordwise) { var lastspace = value.lastIndexOf(' '); if (lastspace !== -1) { //Also remove . and , so its gives a cleaner result. if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') { lastspace = lastspace - 1; } value = value.substr(0, lastspace); } } return value + (tail || ' …'); }; }); </code></pre> <h3>Usage:</h3> <pre><code>{{some_text | cut:true:100:' ...'}} </code></pre> <h3>Options:</h3> <ul> <li>wordwise (boolean) - if true, cut only by words bounds,</li> <li>max (integer) - max length of the text, cut to this number of chars,</li> <li>tail (string, default: '&nbsp;&hellip;') - add this string to the input string if the string was cut.</li> </ul> <p><strong>Another solution</strong>: <a href="http://ngmodules.org/modules/angularjs-truncate" rel="noreferrer">http://ngmodules.org/modules/angularjs-truncate</a> (by @Ehvince)</p>
{ "question_id": 18095727, "question_date": "2013-08-07T06:00:45.053Z", "question_score": 233, "tags": "angularjs|filter|angularjs-filter", "answer_id": 18096071, "answer_date": "2013-08-07T06:24:54.330Z", "answer_score": 349 }
Please answer the following Stack Overflow question: Title: How do I get current URL in Selenium Webdriver 2 Python? <p>I'm trying to get the current url after a series of navigations in Selenium. I know there's a command called getLocation for ruby, but I can't find the syntax for Python.</p>
<p>Use current_url element for Python 2:</p> <pre><code>print browser.current_url </code></pre> <p>For Python 3 and later versions of selenium:</p> <pre><code>print(driver.current_url) </code></pre>
{ "question_id": 15985339, "question_date": "2013-04-13T07:20:01.270Z", "question_score": 233, "tags": "python|selenium|selenium-webdriver", "answer_id": 15986028, "answer_date": "2013-04-13T08:53:39.323Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: How do you execute an arbitrary native command from a string? <p>I can express my need with the following scenario: <strong>Write a function that accepts a string to be run as a native command.</strong> </p> <p>It's not too far fetched of an idea: if you're interfacing with other command-line utilities from elsewhere in the company that supply you with a command to run verbatim. Because you don't control the command, you need to <em>accept any valid command as input</em>. These are the main hiccups I've been unable to easily overcome:</p> <ol> <li><p>The command might execute a program living in a path with a space in it:</p> <pre><code>$command = '"C:\Program Files\TheProg\Runit.exe" Hello'; </code></pre></li> <li><p>The command may have parameters with spaces in them:</p> <pre><code>$command = 'echo "hello world!"'; </code></pre></li> <li><p>The command might have both single and double ticks:</p> <pre><code>$command = "echo `"it`'s`""; </code></pre></li> </ol> <p>Is there <strong>any</strong> clean way of accomplishing this? I've only been able to devise lavish and ugly workarounds, but for a scripting language I feel like this should be dead simple.</p>
<p><code>Invoke-Expression</code>, also aliased as <code>iex</code>. The following will work on your examples #2 and #3:</p> <pre><code>iex $command </code></pre> <p>Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:</p> <pre><code>$command = 'C:\somepath\someexe.exe somearg' iex $command </code></pre> <p>However, if the exe is in quotes, you need the help of <code>&amp;</code> to get it running, as in this example, as run from the commandline:</p> <pre><code>&gt;&gt; &amp;"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext" </code></pre> <p>And then in the script:</p> <pre><code>$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"' iex "&amp; $command" </code></pre> <p>Likely, you could handle nearly all cases by detecting if the first character of the command string is <code>"</code>, like in this naive implementation:</p> <pre><code>function myeval($command) { if ($command[0] -eq '"') { iex "&amp; $command" } else { iex $command } } </code></pre> <p>But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use <code>try{}catch{}</code>, perhaps for specific exception types/messages, or examine the command string.</p> <p>If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.</p>
{ "question_id": 6338015, "question_date": "2011-06-14T00:54:59.367Z", "question_score": 233, "tags": "scripting|powershell", "answer_id": 6338047, "answer_date": "2011-06-14T01:00:08.770Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: Using the "animated circle" in an ImageView while loading stuff <p>I am currently using in my application a listview that need maybe one second to be displayed.</p> <p>What I currently do is using the @id/android:empty property of the listview to create a "loading" text.</p> <pre><code> &lt;TextView android:id="@id/android:empty" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF0000" android:text="Loading..."/&gt; </code></pre> <p>Now, I would like to replace that with the animated circle that is used in a loading dialog instead of this text, i guess you all know what I mean:</p> <p>Edit: I do not want a dialog. I want to show that inside my layout.</p> <p><img src="https://i.stack.imgur.com/h6viz.gif" alt="http://flexfwd.com/DesktopModules/ATI_Base/resources/images/loading_blue_circle.gif"></p> <p>Thank a lot for your help!</p>
<p>Simply put this block of xml in your activity layout file:</p> <pre><code>&lt;RelativeLayout android:id="@+id/loadingPanel" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" &gt; &lt;ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminate="true" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>And when you finish loading, call this one line:</p> <pre><code>findViewById(R.id.loadingPanel).setVisibility(View.GONE); </code></pre> <p>The result (and it spins too): </p> <p><img src="https://i.stack.imgur.com/1sp1o.png" alt="enter image description here"></p>
{ "question_id": 5442183, "question_date": "2011-03-26T12:03:24.407Z", "question_score": 233, "tags": "android|loading|android-asynctask|geometry", "answer_id": 23923473, "answer_date": "2014-05-28T23:27:39.297Z", "answer_score": 496 }
Please answer the following Stack Overflow question: Title: Wait until a process ends <p>I've an application which does</p> <pre><code>Process.Start() </code></pre> <p>to start another application 'ABC'. I want to wait till that application ends (process dies) and continue my execution. How can I do it?</p> <p>There may be multiple instances of the application 'ABC' running at the same time.</p>
<p>I think you just want this:</p> <pre><code>var process = Process.Start(...); process.WaitForExit(); </code></pre> <p>See the <a href="http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx" rel="noreferrer">MSDN page</a> for the method. It also has an overload where you can specify the timeout, so you're not potentially waiting forever.</p>
{ "question_id": 3147911, "question_date": "2010-06-30T09:18:43.830Z", "question_score": 233, "tags": "c#|.net|process", "answer_id": 3147920, "answer_date": "2010-06-30T09:19:48.973Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: OWIN Startup Class Missing <p>I'm getting this error as my project is not able to find the reference for <code>OWIN</code> startup class. I've even installed all the OWIN reference packages through Nuget still getting the same issue. I'm using <code>Visual Studio 2012</code> and <code>MVC4</code>. </p> <p>The following errors occurred while attempting to load the app.</p> <blockquote> <ul> <li>No assembly found containing an OwinStartupAttribute.</li> <li>No assembly found containing a Startup or [AssemblyName].Startup class. To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config. To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.</li> </ul> </blockquote>
<p>Create One Class With Name Startup this will help you.. </p> <pre><code>public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } </code></pre>
{ "question_id": 20068075, "question_date": "2013-11-19T09:44:36.110Z", "question_score": 233, "tags": "c#|asp.net-mvc-4|visual-studio-2012|owin", "answer_id": 20068419, "answer_date": "2013-11-19T10:01:24.560Z", "answer_score": 216 }
Please answer the following Stack Overflow question: Title: Processing $http response in service <p>I recently posted a detailed description of the issue I am facing <a href="https://stackoverflow.com/questions/12504747/angularjs-processing-asynchronous-data-in-service">here</a> at SO. As I couldn't send an actual <code>$http</code> request, I used timeout to simulate asynchronous behavior. Data binding from my model to view is working correct, with the help of @Gloopy</p> <p>Now, when I use <code>$http</code> instead of <code>$timeout</code> (tested locally), I could see the asynchronous request was successful and <code>data</code> is filled with json response in my service. But, my view is not updating.</p> <p>updated Plunkr <a href="http://plnkr.co/edit/RbzODj?p=preview" rel="noreferrer">here</a></p>
<p>Here is a Plunk that does what you want: <a href="http://plnkr.co/edit/TTlbSv?p=preview">http://plnkr.co/edit/TTlbSv?p=preview</a></p> <p>The idea is that you work with promises directly and their "then" functions to manipulate and access the asynchronously returned responses.</p> <pre><code>app.factory('myService', function($http) { var myService = { async: function() { // $http returns a promise, which has a then function, which also returns a promise var promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); }); </code></pre> <p>Here is a slightly more complicated version that caches the request so you only make it first time (<a href="http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview">http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview</a>):</p> <pre><code>app.factory('myService', function($http) { var promise; var myService = { async: function() { if ( !promise ) { // $http returns a promise, which has a then function, which also returns a promise promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); } // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { $scope.clearData = function() { $scope.data = {}; }; $scope.getData = function() { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); }; }); </code></pre>
{ "question_id": 12505760, "question_date": "2012-09-20T03:36:10.003Z", "question_score": 233, "tags": "javascript|angularjs|angular-http", "answer_id": 12513509, "answer_date": "2012-09-20T13:19:10.247Z", "answer_score": 418 }
Please answer the following Stack Overflow question: Title: How do you run a command eg chmod, for each line of a file? <p>For example, right now I'm using the following to change a couple of files whose Unix paths I wrote to a file:</p> <pre><code>cat file.txt | while read in; do chmod 755 "$in"; done </code></pre> <p>Is there a more elegant, safer way?</p>
<h1>Read a file line by line and execute commands: 4+ answers</h1> <p>This is because there is not only 1 answer...</p> <ol start="0"> <li>Shell command line expansion</li> <li><code>xargs</code> dedicated tool</li> <li><code>while read</code> with some remarks</li> <li><code>while read -u</code> using dedicated <em><code>fd</code></em>, for <em>interactive</em> processing (sample)</li> <li>running <a href="/questions/tagged/shell" class="post-tag" title="show questions tagged &#39;shell&#39;" rel="tag">shell</a> with inline generated script</li> </ol> <p>Regarding the OP request: <em><strong>running <code>chmod</code> on all targets listed in file</strong></em>, <code>xargs</code> is the indicated tool. But for some other applications, small amount of files, etc...</p> <h2>0. Read entire file as command line argument.</h2> <p>If your file is not too big and all files are <em>well named</em> (without spaces or other special chars like quotes), you could use shell <em>command line expansion</em>. Simply:</p> <pre><code>chmod 755 $(&lt;file.txt) </code></pre> <p>For small amounts of files (lines), this command is the lighter one.</p> <h2>1. <code>xargs</code> is the right tool</h2> <p>For bigger amount of files, or almost <strong>any</strong> number of lines in your input file...</p> <p>For many <em>binutils</em> tools, like <code>chown</code>, <code>chmod</code>, <code>rm</code>, <code>cp -t</code> ...</p> <pre><code>xargs chmod 755 &lt;file.txt </code></pre> <p>If you have special chars and/or a lot of lines in <code>file.txt</code>.</p> <pre><code>xargs -0 chmod 755 &lt; &lt;(tr \\n \\0 &lt;file.txt) </code></pre> <p>If your command need to be run exactly 1 time for each entry:</p> <pre><code>xargs -0 -n 1 chmod 755 &lt; &lt;(tr \\n \\0 &lt;file.txt) </code></pre> <p>This is not needed for this sample, as <code>chmod</code> accepts multiple files as arguments, but this matches the title of question.</p> <p>For some special cases, you could even define the location of the file argument in commands generated by <code>xargs</code>:</p> <pre><code>xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd &lt; &lt;(tr \\n \\0 &lt;file.txt) </code></pre> <h3>Test with <code>seq 1 5</code> as input</h3> <p>Try this:</p> <pre><code>xargs -n 1 -I{} echo Blah {} blabla {}.. &lt; &lt;(seq 1 5) Blah 1 blabla 1.. Blah 2 blabla 2.. Blah 3 blabla 3.. Blah 4 blabla 4.. Blah 5 blabla 5.. </code></pre> <p>where your command is executed once per line.</p> <h2>2. <code>while read</code> and variants.</h2> <p>As OP suggests,</p> <pre><code>cat file.txt | while read in; do chmod 755 &quot;$in&quot; done </code></pre> <p>will work, but there are 2 issues:</p> <ul> <li><p><code>cat |</code> is a <em>useless fork</em>, and</p> </li> <li><p><code>| while ... ;done</code> will become a <em>subshell</em> whose environment will disappear after <code>;done</code>.</p> </li> </ul> <p>So this could be better written:</p> <pre><code>while read in; do chmod 755 &quot;$in&quot; done &lt; file.txt </code></pre> <p>But</p> <ul> <li>You may be warned about <code>$IFS</code> and <code>read</code> flags:</li> </ul> <p><code>help read</code></p> <blockquote> <pre><code>read: read [-r] ... [-d delim] ... [name ...] ... Reads a single line from the standard input... The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on... Only the characters found in $IFS are recognized as word delimiters. ... Options: ... -d delim continue until the first character of DELIM is read, rather than newline ... -r do not allow backslashes to escape any characters ... Exit Status: The return code is zero, unless end-of-file is encountered... </code></pre> </blockquote> <p>In some cases, you may need to use</p> <pre><code>while IFS= read -r in;do chmod 755 &quot;$in&quot; done &lt;file.txt </code></pre> <p>for avoiding problems with strange filenames. And maybe if you encounter problems with UTF-8:</p> <pre><code>while LANG=C IFS= read -r in ; do chmod 755 &quot;$in&quot; done &lt;file.txt </code></pre> <p>While you use a redirection from standard input<code>for reading </code>file.txt`, your script cannot read other input interactively (you cannot use standard input for other input anymore).</p> <h2>3. <code>while read</code>, using dedicated <em><code>fd</code></em>.</h2> <p>Syntax: <code>while read ...;done &lt;file.txt</code> will redirect standard input to come from <code>file.txt</code>. That means you won't be able to deal with processes until they finish.</p> <p>This will let you use more than one input simultaneously, you could merge two files (like here: <a href="https://stackoverflow.com/a/71009297/1765658">scriptReplay.sh</a>), or maybe:</p> <p>You plan to create an <em>interactive</em> tool, you have to avoid use of standard input and use some alternative file descriptor.</p> <p>Constant file descriptors are:</p> <ul> <li>0 for standard input</li> <li>1 for standard output</li> <li>2 for standard error.</li> </ul> <h3>3.1 <a href="/questions/tagged/posix" class="post-tag" title="show questions tagged &#39;posix&#39;" rel="tag">posix</a> <a href="/questions/tagged/shell" class="post-tag" title="show questions tagged &#39;shell&#39;" rel="tag">shell</a> first</h3> <p>You could see them by:</p> <pre><code>ls -l /dev/fd/ </code></pre> <p>or</p> <pre><code>ls -l /proc/$$/fd/ </code></pre> <p>From there, you have to choose unused numbers between 0 and 63 (more, in fact, depending on <code>sysctl</code> superuser tool) as your file descriptor.</p> <p>For this demo, I will use file descriptor 7:</p> <pre><code>while read &lt;&amp;7 filename; do ans= while [ -z &quot;$ans&quot; ]; do read -p &quot;Process file '$filename' (y/n)? &quot; foo [ &quot;$foo&quot; ] &amp;&amp; [ -z &quot;${foo#[yn]}&quot; ] &amp;&amp; ans=$foo || echo '??' done if [ &quot;$ans&quot; = &quot;y&quot; ]; then echo Yes echo &quot;Processing '$filename'.&quot; else echo No fi done 7&lt;file.txt </code></pre> <p>If you want to read your input file in more differents steps, you have to use:</p> <pre><code>exec 7&lt;file.txt # Without spaces between `7` and `&lt;`! # ls -l /dev/fd/ read &lt;&amp;7 headLine while read &lt;&amp;7 filename; do case &quot;$filename&quot; in *'----' ) break ;; # break loop when line end with four dashes. esac .... done read &lt;&amp;7 lastLine exec 7&lt;&amp;- # This will close file descriptor 7. # ls -l /dev/fd/ </code></pre> <h3>3.2 Same under <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a></h3> <p>Under <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a>, you could let him choose any free <em><code>fd</code></em> for you and store into a variable:<br /> <code>exec {varname}&lt;/path/to/input</code>:</p> <pre><code>while read -ru ${fle} filename;do ans= while [ -z &quot;$ans&quot; ]; do read -rp &quot;Process file '$filename' (y/n)? &quot; -sn 1 foo [ &quot;$foo&quot; ] &amp;&amp; [ -z &quot;${foo/[yn]}&quot; ] &amp;&amp; ans=$foo || echo '??' done if [ &quot;$ans&quot; = &quot;y&quot; ]; then echo Yes echo &quot;Processing '$filename'.&quot; else echo No fi done {fle}&lt;file.txt </code></pre> <p>Or</p> <pre><code>exec {fle}&lt;file.txt # ls -l /dev/fd/ read -ru ${fle} headline while read -ru ${fle} filename;do [[ -n &quot;$filename&quot; ]] &amp;&amp; [[ -z ${filename//*----} ]] &amp;&amp; break .... done read -ru ${fle} lastLine exec {fle}&lt;&amp;- # ls -l /dev/fd/ </code></pre> <h3>5 filtering input file for creating <a href="/questions/tagged/shell" class="post-tag" title="show questions tagged &#39;shell&#39;" rel="tag">shell</a> commands</h3> <pre><code>sed &lt;file.txt 's/.*/chmod 755 &quot;&amp;&quot;/' | sh </code></pre> <p>This won't optimise <em>forks</em>, but this could be usefull for more complex (or conditional) operation:</p> <pre><code>sed &lt;file.txt 's/.*/if [ -e &quot;&amp;&quot; ];then chmod 755 &quot;&amp;&quot;;fi/' | sh sed 's/.*/[ -f &quot;&amp;&quot; ] \&amp;\&amp; echo &quot;Processing: \\&quot;&amp;\\&quot;&quot; \&amp;\&amp; chmod 755 &quot;&amp;&quot;/' \ file.txt | sh </code></pre>
{ "question_id": 13939038, "question_date": "2012-12-18T18:17:24.887Z", "question_score": 233, "tags": "bash|loops|line", "answer_id": 13941223, "answer_date": "2012-12-18T20:46:22.547Z", "answer_score": 225 }
Please answer the following Stack Overflow question: Title: Exception thrown inside catch block - will it be caught again? <p>This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?</p> <pre><code>try { // Do something } catch(IOException e) { throw new ApplicationException("Problem connecting to server"); } catch(Exception e) { // Will the ApplicationException be caught here? } </code></pre> <p>I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.</p>
<p>No, since the new <code>throw</code> is not in the <code>try</code> block directly.</p>
{ "question_id": 143622, "question_date": "2008-09-27T13:10:51.740Z", "question_score": 233, "tags": "java|exception", "answer_id": 143628, "answer_date": "2008-09-27T13:13:30.890Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: AssertContains on strings in jUnit <p>Is there a nicer way to write in jUnit</p> <pre><code>String x = "foo bar"; Assert.assertTrue(x.contains("foo")); </code></pre>
<p>If you add in Hamcrest and JUnit4, you could do:</p> <pre><code>String x = &quot;foo bar&quot;; Assert.assertThat(x, CoreMatchers.containsString(&quot;foo&quot;)); </code></pre> <p>With some static imports, it looks a lot better:</p> <pre><code>assertThat(x, containsString(&quot;foo&quot;)); </code></pre> <p>The static imports needed would be:</p> <pre><code>import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.containsString; </code></pre>
{ "question_id": 1092219, "question_date": "2009-07-07T13:02:14.780Z", "question_score": 233, "tags": "java|string|junit|assert", "answer_id": 1092241, "answer_date": "2009-07-07T13:05:52.453Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: Using :before and :after CSS selector to insert HTML <p>I'm wondering if the following is possible. I know it doesn't work, but maybe I'm not writing it in the correct syntax.</p> <pre><code>li.first div.se_bizImg:before{ content: &quot;&lt;h1&gt;6 Businesses Found &lt;span class=&quot;headingDetail&quot;&gt;(view all)&lt;/span&gt;&lt;/h1&gt;&quot;; } </code></pre> <p>Any way of doing this?</p>
<p><code>content</code> doesn't support HTML, only text. You should probably use javascript, jQuery or something like that. </p> <p>Another problem with your code is <code>"</code> inside a <code>"</code> block. You should mix <code>'</code> and <code>"</code> (<code>class='headingDetail'</code>).</p> <p>If <code>content</code> did support HTML you could end up in an infinite loop where <code>content</code> is added inside <code>content</code>.</p>
{ "question_id": 5865937, "question_date": "2011-05-03T06:37:06.700Z", "question_score": 233, "tags": "html|css|css-selectors", "answer_id": 5865996, "answer_date": "2011-05-03T06:42:39.600Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Add querystring parameters to link_to <p>I'm having difficultly adding querystring parameters to link_to UrlHelper. I have an Index view, for example, that has UI elements for sorting, filtering, and pagination (via will_paginate). The will_paginate plugin manages the intra-page persistence of querystring parameters correctly.</p> <p>Is there an automatic mechanism to add the querystring parameters to a give named route, or do I need to do so manually? A great deal of research on this seemingly simple construct has left me clueless.</p> <p><strong>Edit</strong></p> <p>Some of the challenges:</p> <ol> <li><p>If I have two querystring parameters, bucket &amp; sorting, how do set a specific value to one of these in a link_to, while preserving the current value of the other? For example:</p> <pre><code>&lt;%= link_to "0", profiles_path(:bucket =&gt; '0', :sorting=&gt;?? ) %&gt; </code></pre></li> <li><p>If I have multiple querystring parameters, bucket &amp; sorting &amp; page_size, and I want to set the value to one of these, is there a way to 'automatically' include the names and values of the remaining parameters? For example:</p> <pre><code>&lt;%= link_to "0", profiles_path(:bucket =&gt; '0', [include sorting and page_size name/values here] ) %&gt; </code></pre></li> <li><p>The will_paginate plugin manages its page variable and other querystring variables automatically. There doesn't seem to be an automatic UI element for managing page size. While I've seen code to create a select list of page sizes, I would rather have A elements for this (like SO). Part of this challenge is related to #2, part is related to hiding/showing this UI element based on the existence/non-existence of records. Said another way, I only want to include page-size links if there are records to page. Moreover, I prefer to automatically include the other QS variables (i.e. page, bucket, sorting), rather than having to include them by name in the link_to.</p></li> </ol>
<p>The <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to" rel="noreferrer">API docs on link_to</a> show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?</p> <p><code>link_to</code> can also produce links with anchors or query strings:</p> <pre><code>link_to "Comment wall", profile_path(@profile, :anchor =&gt; "wall") #=&gt; &lt;a href="/profiles/1#wall"&gt;Comment wall&lt;/a&gt; link_to "Ruby on Rails search", :controller =&gt; "searches", :query =&gt; "ruby on rails" #=&gt; &lt;a href="/searches?query=ruby+on+rails"&gt;Ruby on Rails search&lt;/a&gt; link_to "Nonsense search", searches_path(:foo =&gt; "bar", :baz =&gt; "quux") #=&gt; &lt;a href="/searches?foo=bar&amp;amp;baz=quux"&gt;Nonsense search&lt;/a&gt; </code></pre>
{ "question_id": 2695538, "question_date": "2010-04-23T01:01:53.327Z", "question_score": 233, "tags": "ruby-on-rails|query-string", "answer_id": 2696001, "answer_date": "2010-04-23T03:18:01.933Z", "answer_score": 366 }
Please answer the following Stack Overflow question: Title: Declare a constant array <p>I have tried:</p> <pre><code>const ascii = &quot;abcdefghijklmnopqrstuvwxyz&quot; const letter_goodness []float32 = { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 } const letter_goodness = { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 } const letter_goodness = []float32 { .0817,.0149,.0278,.0425,.1270,.0223,.0202, .0609,.0697,.0015,.0077,.0402,.0241,.0675, .0751,.0193,.0009,.0599,.0633,.0906,.0276, .0098,.0236,.0015,.0197,.0007 } </code></pre> <p>The first declaration and initialization works fine, but the second, third and fourth don't work.</p> <p>How can I declare and initialize a const array of floats?</p>
<p>An array isn't immutable by nature; you can't make it constant.</p> <p>The nearest you can get is:</p> <pre><code>var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 } </code></pre> <p>Note the <code>[...]</code> instead of <code>[]</code>: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.</p> <p>As pointed out by <a href="https://stackoverflow.com/users/357705/jimt">@jimt</a>, the <code>[...]T</code> syntax is sugar for <code>[123]T</code>. It creates a fixed size array, but lets the compiler figure out how many elements are in it.</p>
{ "question_id": 13137463, "question_date": "2012-10-30T10:53:27.807Z", "question_score": 233, "tags": "arrays|go|constants", "answer_id": 13137568, "answer_date": "2012-10-30T11:00:47.843Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: How to get all columns' names for all the tables in MySQL? <p>Is there a fast way of getting all column names from all tables in <code>MySQL</code>, without having to list all the tables?</p>
<pre><code>select column_name from information_schema.columns where table_schema = 'your_db' order by table_name,ordinal_position </code></pre>
{ "question_id": 5648420, "question_date": "2011-04-13T11:27:50.520Z", "question_score": 233, "tags": "mysql|database-schema|database-metadata", "answer_id": 5648713, "answer_date": "2011-04-13T11:50:32.523Z", "answer_score": 378 }
Please answer the following Stack Overflow question: Title: How to stop an unstoppable zombie job on Jenkins without restarting the server? <p>Our Jenkins server has a job that has been running for three days, but is not doing anything. Clicking the little X in the corner does nothing, and the console output log doesn't show anything either. I've checked on our build servers and the job doesn't actually seem to be running at all. </p> <p>Is there a way to tell jenkins that the job is "done", by editing some file or lock or something? Since we have a lot of jobs we don't really want to restart the server. </p>
<p>Go to "Manage Jenkins" > "Script Console" to run a script on your server to interrupt the hanging thread. </p> <p>You can get all the live threads with <code>Thread.getAllStackTraces()</code> and interrupt the one that's hanging.</p> <pre class="lang-groovy prettyprint-override"><code>Thread.getAllStackTraces().keySet().each() { t -&gt; if (t.getName()=="YOUR THREAD NAME" ) { t.interrupt(); } } </code></pre> <p>UPDATE:</p> <p>The above solution using threads may not work on more recent Jenkins versions. To interrupt frozen pipelines refer to <a href="https://stackoverflow.com/a/38481808/1434041">this</a> solution (by <a href="https://stackoverflow.com/users/4667789/alexandru-bantiuc">alexandru-bantiuc</a>) instead and run:</p> <pre><code>Jenkins.instance.getItemByFullName("JobName") .getBuildByNumber(JobNumber) .finish( hudson.model.Result.ABORTED, new java.io.IOException("Aborting build") ); </code></pre>
{ "question_id": 14456592, "question_date": "2013-01-22T10:37:50.463Z", "question_score": 233, "tags": "jenkins", "answer_id": 26306081, "answer_date": "2014-10-10T18:48:05.170Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Haskell: Converting Int to String <p>I know you can convert a <code>String</code> to an number with <code>read</code>:</p> <pre><code>Prelude&gt; read "3" :: Int 3 Prelude&gt; read "3" :: Double 3.0 </code></pre> <p>But how do you grab the <code>String</code> representation of an <code>Int</code> value?</p>
<p>The opposite of <code>read</code> is <code>show</code>.</p> <pre><code>Prelude&gt; show 3 "3" Prelude&gt; read $ show 3 :: Int 3 </code></pre>
{ "question_id": 2784271, "question_date": "2010-05-06T20:32:21.643Z", "question_score": 233, "tags": "string|haskell|int|casting", "answer_id": 2784280, "answer_date": "2010-05-06T20:33:55.010Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: create react app not picking up .env files? <p>I am using <a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">create react app</a> to bootstrap my app.</p> <p>I have added two <code>.env</code> files <code>.env.development</code> and <code>.env.production</code> in the root.</p> <p>My <code>.env.development</code> includes:</p> <pre><code>API_URL=http://localhost:3000/api CALLBACK_URL=http://localhost:3005/callback </code></pre> <p>When I run my app using <code>react-scripts start</code> and console out <code>process.env</code> it spits out</p> <pre><code>{ NODE_ENV: "development", PUBLIC_URL: "" } </code></pre> <p>I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!</p> <p>Directry structure is:</p> <pre><code>/.env.development /src/index.js </code></pre> <p>Package.json script is:</p> <pre><code>"start": "export PORT=3005; npm-run-all --parallel server:start client:start", "client:start": "export PORT=3005; react-scripts start", "server:start": "node server.js", "build": "react-scripts build", </code></pre> <p><strong>Edit:</strong></p> <p>@jamcreencia correctly pointed out my variables <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables" rel="noreferrer">should be prefixed</a> with <code>REACT_APP</code>.</p> <p><strong>Edit 2</strong></p> <p>It works okay if I name the file <code>.env</code> but not if I use <code>.env.development</code> or <code>.end.production</code></p>
<p>With create react app, you need to prefix <code>REACT_APP_</code> to the variable name. ex:</p> <pre><code>REACT_APP_API_URL=http://localhost:3000/api REACT_APP_CALLBACK_URL=http://localhost:3005/callback </code></pre> <p>CRA Docs on <a href="https://create-react-app.dev/docs/adding-custom-environment-variables/" rel="noreferrer">Adding Custom Environment Variables</a>:</p> <blockquote> <p><em>Note</em>: You must create custom environment variables beginning with <code>REACT_APP_</code>. Any other variables except <code>NODE_ENV</code> will be ignored to avoid accidentally exposing a private key on the machine that could have the same name</p> </blockquote>
{ "question_id": 48378337, "question_date": "2018-01-22T09:30:22.377Z", "question_score": 233, "tags": "reactjs|create-react-app", "answer_id": 48378498, "answer_date": "2018-01-22T09:41:40.300Z", "answer_score": 499 }
Please answer the following Stack Overflow question: Title: Getting individual colors from a color map in matplotlib <p>If you have a <a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html" rel="noreferrer">Colormap</a> <code>cmap</code>, for example:</p> <pre><code>cmap = matplotlib.cm.get_cmap('Spectral') </code></pre> <p>How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map?</p> <p>Ideally, I would be able to get the middle colour in the map by doing:</p> <pre><code>&gt;&gt;&gt; do_some_magic(cmap, 0.5) # Return an RGBA tuple (0.1, 0.2, 0.3, 1.0) </code></pre>
<p>You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the <code>cmap</code> object you have.</p> <pre><code>import matplotlib cmap = matplotlib.cm.get_cmap('Spectral') rgba = cmap(0.5) print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0) </code></pre> <p>For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with <code>cmap.set_under()</code> and <code>cmap.set_over()</code>. </p> <p>For "special" numbers such as <code>np.nan</code> and <code>np.inf</code> the default is to use the 0.0 value, this can be changed using <code>cmap.set_bad()</code> similarly to under and over as above.</p> <p>Finally it may be necessary for you to normalize your data such that it conforms to the range <code>[0.0, 1.0]</code>. This can be done using <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.Normalize" rel="noreferrer"><code>matplotlib.colors.Normalize</code></a> simply as shown in the small example below where the arguments <code>vmin</code> and <code>vmax</code> describe what numbers should be mapped to 0.0 and 1.0 respectively.</p> <pre><code>import matplotlib norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0) print(norm(15.0)) # 0.5 </code></pre> <p>A logarithmic normaliser (<a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.LogNorm" rel="noreferrer">matplotlib.colors.LogNorm</a>) is also available for data ranges with a large range of values.</p> <p><em>(Thanks to both <a href="https://stackoverflow.com/users/325565/joe-kington">Joe Kington</a> and <a href="https://stackoverflow.com/users/380231/tcaswell">tcaswell</a> for suggestions on how to improve the answer.)</em></p>
{ "question_id": 25408393, "question_date": "2014-08-20T15:12:26.633Z", "question_score": 233, "tags": "python|matplotlib|colors", "answer_id": 25408562, "answer_date": "2014-08-20T15:20:55.560Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: How can I find the location of origin/master in git, and how do I change it? <p>I'm a Git newbie. I recently moved a Rails project from Subversion to Git. I followed the tutorial here: <a href="http://www.simplisticcomplexity.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/" rel="noreferrer">http://www.simplisticcomplexity.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/</a></p> <p>I am also using unfuddle.com to store my code. I make changes on my Mac laptop on the train to/from work and then push them to unfuddle when I have a network connection using the following command:</p> <pre><code>git push unfuddle master </code></pre> <p>I use Capistrano for deployments and pull code from the unfuddle repository using the master branch.</p> <p>Lately I've noticed the following message when I run "git status" on my laptop:</p> <pre><code># On branch master # Your branch is ahead of 'origin/master' by 11 commits. # nothing to commit (working directory clean) </code></pre> <p>And I'm confused as to why. I thought my laptop was the origin... but don't know if either the fact that I originally pulled from Subversion or push to Unfuddle is what's causing the message to show up. How can I:</p> <ol> <li>Find out where Git thinks 'origin/master' is?</li> <li>If it's somewhere else, how do I turn my laptop into the 'origin/master'?</li> <li>Get this message to go away. It makes me think Git is unhappy about something.</li> </ol> <p>My mac is running Git version 1.6.0.1.</p> <hr> <p>When I run <code>git remote show origin</code> as suggested by dbr, I get the following:</p> <pre><code>~/Projects/GeekFor/geekfor 10:47 AM $ git remote show origin fatal: '/Users/brian/Projects/GeekFor/gf/.git': unable to chdir or not a git archive fatal: The remote end hung up unexpectedly </code></pre> <p>When I run <code>git remote -v</code> as suggested by Aristotle Pagaltzis, I get the following:</p> <pre><code>~/Projects/GeekFor/geekfor 10:33 AM $ git remote -v origin /Users/brian/Projects/GeekFor/gf/.git unfuddle [email protected]:spilth/geekfor.git </code></pre> <p>Now, interestingly, I'm working on my project in the <code>geekfor</code> directory but it says my origin is my local machine in the <code>gf</code> directory. I believe <code>gf</code> was the temporary directory I used when converting my project from Subversion to Git and probably where I pushed to unfuddle from. Then I believe I checked out a fresh copy from unfuddle to the <code>geekfor</code> directory.</p> <p>So it looks like I should follow dbr's advice and do:</p> <pre><code>git remote rm origin git remote add origin [email protected]:spilth/geekfor.git </code></pre>
<blockquote> <p><code>1.</code> Find out where Git thinks 'origin/master' is using <a href="http://schacon.github.com/git/git-remote.html#_commands" rel="noreferrer"><code>git-remote</code></a></p> </blockquote> <pre><code>git remote show origin </code></pre> <p>..which will return something like..</p> <pre><code>* remote origin URL: [email protected]:~/something.git Remote branch merged with 'git pull' while on branch master master Tracked remote branch master </code></pre> <p>A remote is basically a link to a remote repository. When you do..</p> <pre><code>git remote add unfuddle [email protected]/myrepo.git git push unfuddle </code></pre> <p>..git will push changes to that address you added. It's like a bookmark, for remote repositories.</p> <p>When you run <code>git status</code>, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to "origin", both will be in sync, so you wont get that message.</p> <blockquote> <p><code>2.</code> If it's somewhere else, how do I turn my laptop into the 'origin/master'?</p> </blockquote> <p>There is no point in doing this. Say "origin" is renamed to "laptop" - you never want to do <code>git push laptop</code> from your laptop.</p> <p>If you want to remove the origin remote, you do..</p> <pre><code>git remote rm origin </code></pre> <p>This wont delete anything (in terms of file-content/revisions-history). This will stop the "your branch is ahead by.." message, as it will no longer compare your repository with the remote (because it's gone!)</p> <p>One thing to remember is that there is nothing special about <code>origin</code>, it's just a default name git uses.</p> <p>Git does use <code>origin</code> by default when you do things like <code>git push</code> or <code>git pull</code>. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as "origin":</p> <pre><code>git remote rm origin git remote add origin [email protected]:subdomain/abbreviation.git </code></pre> <p>or do the above in one command using set-url:</p> <pre><code>git remote set-url origin [email protected]:subdomain/abbreviation.git </code></pre> <p>Then you can simply do <code>git push</code> or <code>git pull</code> to update, instead of <code>git push unfuddle master</code></p>
{ "question_id": 277077, "question_date": "2008-11-10T04:50:26.877Z", "question_score": 233, "tags": "git|git-push|git-remote", "answer_id": 277186, "answer_date": "2008-11-10T06:16:45.063Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: What is a .pid file and what does it contain? <p>I recently come across a file with the extension .pid and explored inside it but didn't find much. The documentation says:</p> <blockquote> <p>A Pid-File is a file containing the process identification number (pid) that is stored in a well-defined location of the filesystem thus allowing other programs to find out the pid of a running script.</p> </blockquote> <p>Can anyone shed more light on this, or guide me to details of what's contained in the pid file?</p>
<p>The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using <code>cat filename.pid | xargs kill</code></p>
{ "question_id": 8296170, "question_date": "2011-11-28T13:01:52.643Z", "question_score": 233, "tags": "linux|unix|pid", "answer_id": 8296204, "answer_date": "2011-11-28T13:05:54.793Z", "answer_score": 250 }
Please answer the following Stack Overflow question: Title: How to round an image with Glide library? <p>So, anybody know how to display an image with rounded corners with Glide? I am loading an image with Glide, but I don't know how to pass rounded params to this library.</p> <p>I need display image like following example:</p> <p><img src="https://i.stack.imgur.com/x8PhM.png" alt="enter image description here"></p>
<p><strong>Glide V4:</strong></p> <pre><code> Glide.with(context) .load(url) .circleCrop() .into(imageView); </code></pre> <p><strong>Glide V3:</strong></p> <p>You can use <code>RoundedBitmapDrawable</code> for circular images with Glide. No custom ImageView is required.</p> <pre><code> Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource); circularBitmapDrawable.setCircular(true); imageView.setImageDrawable(circularBitmapDrawable); } }); </code></pre>
{ "question_id": 25278821, "question_date": "2014-08-13T05:43:30.007Z", "question_score": 233, "tags": "android|android-glide", "answer_id": 32390715, "answer_date": "2015-09-04T05:30:35.033Z", "answer_score": 581 }
Please answer the following Stack Overflow question: Title: Multiple aggregations of the same column using pandas GroupBy.agg() <p>Is there a pandas built-in way to apply two different aggregating functions <code>f1, f2</code> to the same column <code>df[&quot;returns&quot;]</code>, without having to call <code>agg()</code> multiple times?</p> <p>Example dataframe:</p> <pre><code>import pandas as pd import datetime as dt import numpy as np pd.np.random.seed(0) df = pd.DataFrame({ &quot;date&quot; : [dt.date(2012, x, 1) for x in range(1, 11)], &quot;returns&quot; : 0.05 * np.random.randn(10), &quot;dummy&quot; : np.repeat(1, 10) }) </code></pre> <p>The syntactically wrong, but intuitively right, way to do it would be:</p> <pre><code># Assume `f1` and `f2` are defined for aggregating. df.groupby(&quot;dummy&quot;).agg({&quot;returns&quot;: f1, &quot;returns&quot;: f2}) </code></pre> <p>Obviously, Python doesn't allow duplicate keys. Is there any other manner for expressing the input to <code>agg()</code>? Perhaps a list of tuples <code>[(column, function)]</code> would work better, to allow multiple functions applied to the same column? But <code>agg()</code> seems like it only accepts a dictionary.</p> <p>Is there a workaround for this besides defining an auxiliary function that just applies both of the functions inside of it? (How would this work with aggregation anyway?)</p>
<p>As of 2022-06-20, the below is the accepted practice for aggregations:</p> <pre><code>df.groupby('dummy').agg( Mean=('returns', np.mean), Sum=('returns', np.sum)) </code></pre> <hr /> <p>Below the fold included for historical versions of <code>pandas</code>.</p> <p>You can simply pass the functions as a list:</p> <pre><code>In [20]: df.groupby(&quot;dummy&quot;).agg({&quot;returns&quot;: [np.mean, np.sum]}) Out[20]: mean sum dummy 1 0.036901 0.369012 </code></pre> <p>or as a dictionary:</p> <pre><code>In [21]: df.groupby('dummy').agg({'returns': {'Mean': np.mean, 'Sum': np.sum}}) Out[21]: returns Mean Sum dummy 1 0.036901 0.369012 </code></pre>
{ "question_id": 12589481, "question_date": "2012-09-25T19:05:26.550Z", "question_score": 233, "tags": "python|pandas|dataframe|aggregate|pandas-groupby", "answer_id": 13592901, "answer_date": "2012-11-27T20:57:33.097Z", "answer_score": 266 }
Please answer the following Stack Overflow question: Title: Why does Python code use len() function instead of a length method? <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why it's not a method of the string object?</p>
<p>Strings do have a length method: <code>__len__()</code></p> <p>The protocol in Python is to implement this method on objects which have a length and use the built-in <a href="http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-45" rel="noreferrer"><code>len()</code></a> function, which calls it for you, similar to the way you would implement <code>__iter__()</code> and use the built-in <code>iter()</code> function (or have the method called behind the scenes for you) on objects which are iterable.</p> <p>See <a href="http://www.python.org/doc/2.5.2/ref/sequence-types.html" rel="noreferrer">Emulating container types</a> for more information.</p> <p>Here's a good read on the subject of protocols in Python: <a href="http://lucumr.pocoo.org/2011/7/9/python-and-pola/" rel="noreferrer">Python and the Principle of Least Astonishment</a></p>
{ "question_id": 237128, "question_date": "2008-10-25T22:37:03.223Z", "question_score": 233, "tags": "python", "answer_id": 237150, "answer_date": "2008-10-25T22:51:19.217Z", "answer_score": 197 }
Please answer the following Stack Overflow question: Title: Android: ScrollView force to bottom <p>I would like a ScrollView to start all the way at the bottom. Any methods?</p>
<p><code>scroll.fullScroll(View.FOCUS_DOWN)</code> also should work.</p> <p>Put this in a <code>scroll.Post(Runnable run)</code></p> <p>Kotlin Code </p> <pre><code>scrollView.post { scrollView.fullScroll(View.FOCUS_DOWN) } </code></pre>
{ "question_id": 3080402, "question_date": "2010-06-20T18:20:53.833Z", "question_score": 233, "tags": "android|android-scrollview", "answer_id": 3080483, "answer_date": "2010-06-20T18:41:55.287Z", "answer_score": 331 }
Please answer the following Stack Overflow question: Title: C++ STL Vectors: Get iterator from index? <p>So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like <code>vector.insert(pos, first, last)</code> is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values?</p>
<p>Try this:</p> <pre><code>vector&lt;Type&gt;::iterator nth = v.begin() + index; </code></pre>
{ "question_id": 671423, "question_date": "2009-03-22T18:41:33.697Z", "question_score": 233, "tags": "c++|stl|vector|iterator", "answer_id": 671427, "answer_date": "2009-03-22T18:42:49.903Z", "answer_score": 340 }
Please answer the following Stack Overflow question: Title: In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded <p>In my node application I'm using mocha to test my code. While calling many asynchronous functions using mocha, I'm getting timeout error (<code>Error: timeout of 2000ms exceeded.</code>). How can I resolve this?</p> <pre><code>var module = require('../lib/myModule'); var should = require('chai').should(); describe('Testing Module', function() { it('Save Data', function(done) { this.timeout(15000); var data = { a: 'aa', b: 'bb' }; module.save(data, function(err, res) { should.not.exist(err); done(); }); }); it('Get Data By Id', function(done) { var id = "28ca9"; module.get(id, function(err, res) { console.log(res); should.not.exist(err); done(); }); }); }); </code></pre>
<p>You can either set the timeout when running your test:</p> <pre><code>mocha --timeout 15000 </code></pre> <p>Or you can set the timeout for each suite or each test programmatically:</p> <pre><code>describe('...', function(){ this.timeout(15000); it('...', function(done){ this.timeout(15000); setTimeout(done, 15000); }); }); </code></pre> <p>For more info see the <a href="https://mochajs.org/#timeouts">docs</a>.</p>
{ "question_id": 16607039, "question_date": "2013-05-17T10:40:58.663Z", "question_score": 233, "tags": "node.js|mocha.js|chai", "answer_id": 16607408, "answer_date": "2013-05-17T11:02:02.190Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: How to Update Multiple Array Elements in mongodb <p>I have a Mongo document which holds an array of elements.</p> <p>I'd like to reset the <code>.handled</code> attribute of all objects in the array where <code>.profile</code> = XX.</p> <p>The document is in the following form: </p> <pre><code>{ "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), "user_id": "714638ba-2e08-2168-2b99-00002f3d43c0", "events": [{ "handled": 1, "profile": 10, "data": "....." } { "handled": 1, "profile": 10, "data": "....." } { "handled": 1, "profile": 20, "data": "....." } ... ] } </code></pre> <p>so, I tried the following:</p> <pre><code>.update({"events.profile":10},{$set:{"events.$.handled":0}},false,true) </code></pre> <p>However it updates only the <strong>first</strong> matched array element in each document. (That's the defined behaviour for <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator" rel="noreferrer">$ - the positional operator</a>.)</p> <p>How can I update <strong>all</strong> matched array elements?</p>
<p><strong>UPDATE:</strong> <em>As of Mongo version 3.6, this answer is no longer valid as the mentioned issue was fixed and there are ways to achieve this. Please check other answers.</em></p> <hr /> <p>At this moment it is not possible to use the positional operator to update all items in an array. See JIRA <a href="http://jira.mongodb.org/browse/SERVER-1243" rel="noreferrer">http://jira.mongodb.org/browse/SERVER-1243</a></p> <p>As a work around you can:</p> <ul> <li>Update each item individually (events.0.handled events.1.handled ...) or...</li> <li>Read the document, do the edits manually and save it replacing the older one (check <a href="http://www.mongodb.org/display/DOCS/Atomic+Operations" rel="noreferrer">&quot;Update if Current&quot;</a> if you want to ensure atomic updates)</li> </ul>
{ "question_id": 4669178, "question_date": "2011-01-12T13:13:39.047Z", "question_score": 233, "tags": "arrays|mongodb|mongodb-query", "answer_id": 4669702, "answer_date": "2011-01-12T14:09:43.670Z", "answer_score": 119 }
Please answer the following Stack Overflow question: Title: What is middleware exactly? <p>I have heard a lot of people talking recently about <em>middleware</em>, but what is the exact definition of middleware? When I look into middleware, I find a lot of information and some definitions, but while reading these information and definitions, it seems that mostly all 'wares' are in the middle of something. So, are all things middleware?</p> <p>Or do you have an example of a ware that isn't middleware?</p>
<p>Lets say your company makes 4 different products, your client has another 3 different products from another 3 different companies.</p> <p>Someday the client thought, why don't we integrate all our systems into one huge system. Ten minutes later their IT department said that will take 2 years.</p> <p>You (the wise developer) said, why don't we just integrate all the different systems and make them work together? The client manager staring at you... You continued, we will use a Middleware, we will study the Inputs/Outputs of all different systems, the resources they use and then choose an appropriate Middleware framework.</p> <p><em>Still explaining to the non tech manager</em><br /> With Middleware framework in the middle, the first system will produce X stuff, the system Y and Z would consume those outputs and so on.</p>
{ "question_id": 2904854, "question_date": "2010-05-25T13:05:56.907Z", "question_score": 233, "tags": "frameworks|middleware", "answer_id": 2904937, "answer_date": "2010-05-25T13:15:25.360Z", "answer_score": 251 }
Please answer the following Stack Overflow question: Title: What's the difference between Unicode and UTF-8? <p>Consider:</p> <p><img src="https://i.stack.imgur.com/3ayWh.jpg" alt="Alt text"></p> <p>Is it true that <code>unicode=utf16</code>?</p> <p>Many are saying Unicode is a standard, not an encoding, but most editors support save as Unicode <strong>encoding</strong> actually.</p>
<blockquote> <p>most editors support save as ‘Unicode’ encoding actually.</p> </blockquote> <p>This is an unfortunate misnaming perpetrated by Windows.</p> <p>Because Windows uses UTF-16LE encoding internally as the memory storage format for Unicode strings, it considers this to be the natural encoding of Unicode text. In the Windows world, there are ANSI strings (the system codepage on the current machine, subject to total unportability) and there are Unicode strings (stored internally as UTF-16LE).</p> <p>This was all devised in the early days of Unicode, before we realised that UCS-2 wasn't enough, and before UTF-8 was invented. This is why Windows's support for UTF-8 is all-round poor.</p> <p>This misguided naming scheme became part of the user interface. A text editor that uses Windows's encoding support to provide a range of encodings will automatically and inappropriately describe UTF-16LE as “Unicode”, and UTF-16BE, if provided, as “Unicode big-endian”.</p> <p>(Other editors that do encodings themselves, like Notepad++, don't have this problem.)</p> <p>If it makes you feel any better about it, ‘ANSI’ strings aren't based on any ANSI standard, either.</p>
{ "question_id": 3951722, "question_date": "2010-10-17T02:17:02.930Z", "question_score": 233, "tags": "unicode|utf-8", "answer_id": 3951826, "answer_date": "2010-10-17T02:57:30.210Z", "answer_score": 179 }
Please answer the following Stack Overflow question: Title: What are the differences between application/json and application/x-www-form-urlencoded? <p>What is the difference between</p> <blockquote> <p>request.ContentType = &quot;application/json; charset=utf-8&quot;;</p> </blockquote> <p>and</p> <blockquote> <p>webRequest.ContentType = &quot;application/x-www-form-urlencoded&quot;;</p> </blockquote>
<p>The first case is telling the web server that you are posting JSON data as in:</p> <pre><code>{&quot;Name&quot;: &quot;John Smith&quot;, &quot;Age&quot;: 23} </code></pre> <p>The second case is telling the web server that you will be encoding the parameters in the URL:</p> <pre><code>Name=John+Smith&amp;Age=23 </code></pre>
{ "question_id": 9870523, "question_date": "2012-03-26T10:31:48.480Z", "question_score": 233, "tags": "json|post|content-type|x-www-form-urlencoded", "answer_id": 9880122, "answer_date": "2012-03-26T21:26:36.800Z", "answer_score": 260 }
Please answer the following Stack Overflow question: Title: How to automatically generate N "distinct" colors? <p>I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that's what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB cube into a lattice and then drawing points. Does anyone know any other methods? I'm ruling out defining a list and then just cycling through it. I should also say I don't generally care if they clash or don't look nice, they just have to be visually distinct.</p> <pre><code>public static List&lt;Color&gt; pick(int num) { List&lt;Color&gt; colors = new ArrayList&lt;Color&gt;(); if (num &lt; 2) return colors; float dx = 1.0f / (float) (num - 1); for (int i = 0; i &lt; num; i++) { colors.add(get(i * dx)); } return colors; } public static Color get(float x) { float r = 0.0f; float g = 0.0f; float b = 1.0f; if (x &gt;= 0.0f &amp;&amp; x &lt; 0.2f) { x = x / 0.2f; r = 0.0f; g = x; b = 1.0f; } else if (x &gt;= 0.2f &amp;&amp; x &lt; 0.4f) { x = (x - 0.2f) / 0.2f; r = 0.0f; g = 1.0f; b = 1.0f - x; } else if (x &gt;= 0.4f &amp;&amp; x &lt; 0.6f) { x = (x - 0.4f) / 0.2f; r = x; g = 1.0f; b = 0.0f; } else if (x &gt;= 0.6f &amp;&amp; x &lt; 0.8f) { x = (x - 0.6f) / 0.2f; r = 1.0f; g = 1.0f - x; b = 0.0f; } else if (x &gt;= 0.8f &amp;&amp; x &lt;= 1.0f) { x = (x - 0.8f) / 0.2f; r = 1.0f; g = 0.0f; b = x; } return new Color(r, g, b); } </code></pre>
<p>You can use the <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" rel="noreferrer">HSL color model</a> to create your colors.</p> <p>If all you want is differing hues (likely), and slight variations on lightness or saturation, you can distribute the hues like so:</p> <pre><code>// assumes hue [0, 360), saturation [0, 100), lightness [0, 100) for(i = 0; i &lt; 360; i += 360 / num_colors) { HSLColor c; c.hue = i; c.saturation = 90 + randf() * 10; c.lightness = 50 + randf() * 10; addColor(c); } </code></pre>
{ "question_id": 470690, "question_date": "2009-01-22T20:34:00.127Z", "question_score": 233, "tags": "java|colors|color-scheme|color-picker", "answer_id": 470747, "answer_date": "2009-01-22T20:50:10.030Z", "answer_score": 87 }
Please answer the following Stack Overflow question: Title: Apply vs transform on a group object <p>Consider the following dataframe:</p> <pre><code>columns = ['A', 'B', 'C', 'D'] records = [ ['foo', 'one', 0.162003, 0.087469], ['bar', 'one', -1.156319, -1.5262719999999999], ['foo', 'two', 0.833892, -1.666304], ['bar', 'three', -2.026673, -0.32205700000000004], ['foo', 'two', 0.41145200000000004, -0.9543709999999999], ['bar', 'two', 0.765878, -0.095968], ['foo', 'one', -0.65489, 0.678091], ['foo', 'three', -1.789842, -1.130922] ] df = pd.DataFrame.from_records(records, columns=columns) &quot;&quot;&quot; A B C D 0 foo one 0.162003 0.087469 1 bar one -1.156319 -1.526272 2 foo two 0.833892 -1.666304 3 bar three -2.026673 -0.322057 4 foo two 0.411452 -0.954371 5 bar two 0.765878 -0.095968 6 foo one -0.654890 0.678091 7 foo three -1.789842 -1.130922 &quot;&quot;&quot; </code></pre> <p>The following commands work:</p> <pre><code>df.groupby('A').apply(lambda x: (x['C'] - x['D'])) df.groupby('A').apply(lambda x: (x['C'] - x['D']).mean()) </code></pre> <p>but none of the following work:</p> <pre><code>df.groupby('A').transform(lambda x: (x['C'] - x['D'])) # KeyError or ValueError: could not broadcast input array from shape (5) into shape (5,3) df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean()) # KeyError or TypeError: cannot concatenate a non-NDFrame object </code></pre> <p><strong>Why?</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="noreferrer">The example on the documentation</a> seems to suggest that calling <code>transform</code> on a group allows one to do row-wise operation processing:</p> <pre><code># Note that the following suggests row-wise operation (x.mean is the column mean) zscore = lambda x: (x - x.mean()) / x.std() transformed = ts.groupby(key).transform(zscore) </code></pre> <p>In other words, I thought that transform is essentially a specific type of apply (the one that does not aggregate). Where am I wrong?</p> <p>For reference, below is the construction of the original dataframe above:</p> <pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : randn(8), 'D' : randn(8)}) </code></pre>
<h3>Two major differences between <code>apply</code> and <code>transform</code></h3> <p>There are two major differences between the <code>transform</code> and <code>apply</code> groupby methods.</p> <ul> <li><strong>Input</strong>: <ul> <li><code>apply</code> implicitly passes all the columns for each group as a <strong>DataFrame</strong> to the custom function.</li> <li>while <code>transform</code> passes each column for each group individually as a <strong>Series</strong> to the custom function.</li> </ul> </li> <li><strong>Output</strong>: <ul> <li>The custom function passed to <strong><code>apply</code> can return a scalar, or a Series or DataFrame (or numpy array or even list)</strong>.</li> <li>The custom function passed to <strong><code>transform</code> must return a sequence</strong> (a one dimensional Series, array or list) <strong>the same length as the group</strong>.</li> </ul> </li> </ul> <p>So, <code>transform</code> works on just one Series at a time and <code>apply</code> works on the entire DataFrame at once.</p> <h3>Inspecting the custom function</h3> <p>It can help quite a bit to inspect the input to your custom function passed to <code>apply</code> or <code>transform</code>.</p> <h3>Examples</h3> <p>Let's create some sample data and inspect the groups so that you can see what I am talking about:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 'a':[4,5,1,3], 'b':[6,10,3,11]}) State a b 0 Texas 4 6 1 Texas 5 10 2 Florida 1 3 3 Florida 3 11 </code></pre> <p>Let's create a simple custom function that prints out the type of the implicitly passed object and then raises an exception so that execution can be stopped.</p> <pre><code>def inspect(x): print(type(x)) raise </code></pre> <p>Now let's pass this function to both the groupby <code>apply</code> and <code>transform</code> methods to see what object is passed to it:</p> <pre><code>df.groupby('State').apply(inspect) &lt;class 'pandas.core.frame.DataFrame'&gt; &lt;class 'pandas.core.frame.DataFrame'&gt; RuntimeError </code></pre> <p>As you can see, a DataFrame is passed into the <code>inspect</code> function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.</p> <p>Now, let's do the same thing with <code>transform</code></p> <pre><code>df.groupby('State').transform(inspect) &lt;class 'pandas.core.series.Series'&gt; &lt;class 'pandas.core.series.Series'&gt; RuntimeError </code></pre> <p>It is passed a Series - a totally different Pandas object.</p> <p>So, <code>transform</code> is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column <code>a</code> from <code>b</code> inside of our custom function we would get an error with <code>transform</code>. See below:</p> <pre><code>def subtract_two(x): return x['a'] - x['b'] df.groupby('State').transform(subtract_two) KeyError: ('a', 'occurred at index a') </code></pre> <p>We get a KeyError as pandas is attempting to find the Series index <code>a</code> which does not exist. You can complete this operation with <code>apply</code> as it has the entire DataFrame:</p> <pre><code>df.groupby('State').apply(subtract_two) State Florida 2 -2 3 -8 Texas 0 -2 1 -5 dtype: int64 </code></pre> <p>The output is a Series and a little confusing as the original index is kept, but we have access to all columns.</p> <hr /> <h3>Displaying the passed pandas object</h3> <p>It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use <code>print</code> statements by I like to use the <code>display</code> function from the <code>IPython.display</code> module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:</p> <pre><code>from IPython.display import display def subtract_two(x): display(x) return x['a'] - x['b'] </code></pre> <p>Screenshot: <a href="https://i.stack.imgur.com/8LMn5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8LMn5.png" alt="enter image description here" /></a></p> <hr /> <h3>Transform must return a single dimensional sequence the same size as the group</h3> <p>The other difference is that <code>transform</code> must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so <code>transform</code> must return a sequence of two rows. If it does not then an error is raised:</p> <pre><code>def return_three(x): return np.array([1, 2, 3]) df.groupby('State').transform(return_three) ValueError: transform must return a scalar value for each group </code></pre> <p>The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:</p> <pre><code>def rand_group_len(x): return np.random.rand(len(x)) df.groupby('State').transform(rand_group_len) a b 0 0.962070 0.151440 1 0.440956 0.782176 2 0.642218 0.483257 3 0.056047 0.238208 </code></pre> <hr /> <h3>Returning a single scalar object also works for <code>transform</code></h3> <p>If you return just a single scalar from your custom function, then <code>transform</code> will use it for each of the rows in the group:</p> <pre><code>def group_sum(x): return x.sum() df.groupby('State').transform(group_sum) a b 0 9 16 1 9 16 2 4 14 3 4 14 </code></pre>
{ "question_id": 27517425, "question_date": "2014-12-17T02:27:43.740Z", "question_score": 233, "tags": "python|pandas", "answer_id": 47143056, "answer_date": "2017-11-06T18:03:46.547Z", "answer_score": 302 }
Please answer the following Stack Overflow question: Title: Can constructors throw exceptions in Java? <p>Are constructors allowed to throw exceptions?</p>
<p>Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).</p> <p>One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a <code>FileInputStream</code> and a <code>FileOutputStream</code>, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.</p>
{ "question_id": 1371369, "question_date": "2009-09-03T03:58:43.853Z", "question_score": 233, "tags": "java|exception|constructor", "answer_id": 1371559, "answer_date": "2009-09-03T05:30:18.770Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: How do I create my own URL protocol? (e.g. so://...) <p>I have seen:</p> <ul> <li><code>http://www...</code></li> <li><code>ftp://blah.blah...</code></li> <li><code>file://blah.blah...</code></li> <li><code>unreal://blah.blah...</code></li> <li><code>mailto://blah.blah...</code></li> </ul> <p>What is that first section where you see <code>http</code> and the like called?</p> <p>Can I register my own?</p>
<p>The portion with the <code>HTTP://</code>,<code>FTP://</code>, etc are called <a href="https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml" rel="noreferrer">URI Schemes</a> </p> <p>You can register your own through the registry.</p> <pre><code>HKEY_CLASSES_ROOT/ your-protocol-name/ (Default) "URL:your-protocol-name Protocol" URL Protocol "" shell/ open/ command/ (Default) PathToExecutable </code></pre> <p>Sources: <a href="https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml" rel="noreferrer">https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml</a>, <a href="http://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx</a></p>
{ "question_id": 389204, "question_date": "2008-12-23T15:45:41.580Z", "question_score": 233, "tags": "windows|protocols|protocol-handler", "answer_id": 389223, "answer_date": "2008-12-23T15:51:12.193Z", "answer_score": 229 }
Please answer the following Stack Overflow question: Title: What is the difference between HTTP 1.1 and HTTP 2.0? <blockquote> <p>HTTP/1.1 has served the Web well for more than fifteen years, but its age is starting to show.</p> </blockquote> <p>Can anybody explain what is the <strong>main difference</strong> between HTTP 1.1 and 2.0?</p> <p>Is there any change in the transport protocol?</p>
<p>HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.</p> <p><a href="https://daniel.haxx.se/http2/">More details here.</a></p>
{ "question_id": 28592077, "question_date": "2015-02-18T19:21:19.503Z", "question_score": 233, "tags": "http|tcp|webserver|http2", "answer_id": 28592283, "answer_date": "2015-02-18T19:32:02.677Z", "answer_score": 200 }
Please answer the following Stack Overflow question: Title: iPhone - Get Position of UIView within entire UIWindow <p>The position of a <code>UIView</code> can obviously be determined by <code>view.center</code> or <code>view.frame</code> etc. but this only returns the position of the <code>UIView</code> in relation to it's immediate superview.</p> <p>I need to determine the position of the <code>UIView</code> in the entire 320x480 co-ordinate system. For example, if the <code>UIView</code> is in a <code>UITableViewCell</code> it's position within the window could change dramatically irregardless of the superview.</p> <p>Any ideas if and how this is possible?</p> <p>Cheers :)</p>
<p>That's an easy one:</p> <pre><code>[aView convertPoint:localPosition toView:nil]; </code></pre> <p>... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:</p> <pre><code>[aView.superview convertPoint:aView.frame.origin toView:nil]; </code></pre> <p><strong>2014 Edit:</strong> Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...</p> <ol> <li>don't change when rotating the device.</li> <li>always have their origin in the top left corner of the unrotated screen.</li> <li>are <strong>window coordinates</strong>: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.</li> </ol>
{ "question_id": 1465394, "question_date": "2009-09-23T11:23:43.690Z", "question_score": 233, "tags": "iphone|cocoa-touch|ios|uiview|uiwindow", "answer_id": 1465431, "answer_date": "2009-09-23T11:32:34.590Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: Making the iPhone vibrate <p>How can the iPhone be set to vibrate once?</p> <p>For example, when a player loses a life or the game is over, the iPhone should vibrate.</p>
<p>From "<a href="http://blog.mugunthkumar.com/coding/iphone-tutorial-better-way-to-check-capabilities-of-ios-devices/" rel="noreferrer">iPhone Tutorial: Better way to check capabilities of iOS devices</a>":</p> <p>There are two seemingly similar functions that take a parameter <code>kSystemSoundID_Vibrate</code>:</p> <pre><code>1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); 2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); </code></pre> <blockquote> <p>Both of the functions vibrate the iPhone. But, when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function, on the other hand, does nothing on unsupported devices. So if you are going to vibrate the device continuously, as an alert, common sense says, use function 2.</p> </blockquote> <p>First, add the AudioToolbox framework <code>AudioToolbox.framework</code> to your target in Build Phases.</p> <p>Then, import this header file:</p> <pre><code>#import &lt;AudioToolbox/AudioServices.h&gt; </code></pre>
{ "question_id": 4724980, "question_date": "2011-01-18T14:04:50.777Z", "question_score": 233, "tags": "ios|cocoa-touch|avfoundation|vibration", "answer_id": 4725039, "answer_date": "2011-01-18T14:11:41.103Z", "answer_score": 407 }
Please answer the following Stack Overflow question: Title: Git file permissions on Windows <p>I've read through a few questions regarding file permissions in Git and I'm still a bit confused. I've got a repo on GitHub forked from another. Post merge, they should be identical. However:</p> <pre><code>$ git diff --summary origin/epsilon master/epsilon mode change 100644 =&gt; 100755 ants/dist/sample_bots/csharp/compile.sh mode change 100644 =&gt; 100755 ants/dist/starter_bots/coffeescript/MyBot.coffee mode change 100644 =&gt; 100755 ants/dist/starter_bots/coffeescript/ants.coffee mode change 100644 =&gt; 100755 ants/util/block_test.sh mode change 100644 =&gt; 100755 manager/mass_skill_update.py mode change 100644 =&gt; 100755 worker/jailguard.py mode change 100644 =&gt; 100755 worker/release_stale_jails.py mode change 100644 =&gt; 100755 worker/start_worker.sh </code></pre> <p>I've tried changing file permissions, but it does not alter the diff results.</p>
<p>I found the solution of how to change permissions (also) on Windows here: <a href="http://blog.lesc.se/2011/11/how-to-change-file-premissions-in-git.html" rel="noreferrer">http://blog.lesc.se/2011/11/how-to-change-file-premissions-in-git.html</a></p> <p>For example following command adds user execute permission to an arbitrary file:</p> <pre><code>git update-index --chmod=+x &lt;file&gt; </code></pre>
{ "question_id": 6476513, "question_date": "2011-06-25T07:28:58.713Z", "question_score": 233, "tags": "windows|git|diff|file-permissions", "answer_id": 13593391, "answer_date": "2012-11-27T21:28:13.247Z", "answer_score": 455 }
Please answer the following Stack Overflow question: Title: How to assign text size in sp value using java code <p>If I assign an integer value to change a certain text size of a <code>TextView</code> using java code, the value is interpreted as pixel (<code>px</code>).</p> <p>Now does anyone know how to assign it in <code>sp</code>?</p>
<p><a href="http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29" rel="noreferrer">http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29</a> </p> <p>Example:</p> <pre><code>textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65); </code></pre>
{ "question_id": 2069810, "question_date": "2010-01-15T06:15:19.237Z", "question_score": 233, "tags": "android|textview|text-size", "answer_id": 7118377, "answer_date": "2011-08-19T07:37:45.120Z", "answer_score": 586 }
Please answer the following Stack Overflow question: Title: How can I change the table names when using ASP.NET Identity? <p>I am using the release version (RTM, not RC) of Visual Studio 2013 (downloaded from MSDN 2013-10-18) and therefore the latest (RTM) version of AspNet.Identity. When I create a new web project, I select "Individual User Accounts" for authentication. This creates the following tables:</p> <ol> <li>AspNetRoles</li> <li>AspNetUserClaims</li> <li>AspNetUserLogins</li> <li>AspNetUserRoles</li> <li>AspNetUsers</li> </ol> <p>When I register a new user (using the default template), these tables (listed above) are created and the AspNetUsers table has a record inserted which contains:</p> <ol> <li>Id</li> <li>UserName</li> <li>PasswordHash</li> <li>SecurityStamp</li> <li>Discriminator</li> </ol> <p>Additionally, by adding public properties to the class "ApplicationUser" I have successfully added additional fields to the AspNetUsers table, such as "FirstName", "LastName", "PhoneNumber", etc.</p> <p>Here's my question. Is there a way to change the names of the above tables (when they are first created) or will they always be named with the <code>AspNet</code> prefix as I listed above? If the table names can be named differently, please explain how.</p> <p><strong>-- UPDATE --</strong></p> <p>I implemented @Hao Kung's solution. It does create a new table (for example I called it MyUsers), but it also still creates the AspNetUsers table. The goal is to replace the "AspNetUsers" table with the "MyUsers" table. See code below and database image of tables created.</p> <p>I would actually like to replace each <code>AspNet</code> table with my own name... For fxample, MyRoles, MyUserClaims, MyUserLogins, MyUserRoles, and MyUsers.</p> <p>How do I accomplish this and end up with only one set of tables?</p> <pre><code>public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string State { get; set; } public string PostalCode { get; set; } public string PhonePrimary { get; set; } public string PhoneSecondary { get; set; } } public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt; { public ApplicationDbContext(): base("DefaultConnection") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity&lt;IdentityUser&gt;().ToTable("MyUsers"); } } </code></pre> <p><img src="https://i.stack.imgur.com/P1p5S.png" alt="Database Tables"></p> <p><strong>-- UPDATE ANSWER --</strong></p> <p>Thanks to both Hao Kung and Peter Stulinski. This solved my problem...</p> <pre><code> protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity&lt;IdentityUser&gt;().ToTable("MyUsers").Property(p =&gt; p.Id).HasColumnName("UserId"); modelBuilder.Entity&lt;ApplicationUser&gt;().ToTable("MyUsers").Property(p =&gt; p.Id).HasColumnName("UserId"); modelBuilder.Entity&lt;IdentityUserRole&gt;().ToTable("MyUserRoles"); modelBuilder.Entity&lt;IdentityUserLogin&gt;().ToTable("MyUserLogins"); modelBuilder.Entity&lt;IdentityUserClaim&gt;().ToTable("MyUserClaims"); modelBuilder.Entity&lt;IdentityRole&gt;().ToTable("MyRoles"); } </code></pre>
<p>You can do this easily by modifying the IdentityModel.cs as per the below:</p> <p>Override OnModelCreating in your DbContext then add the following, this will change AspNetUser table to "Users" you can also change the field names the default Id column will become User_Id.</p> <pre><code>modelBuilder.Entity&lt;IdentityUser&gt;() .ToTable("Users", "dbo").Property(p =&gt; p.Id).HasColumnName("User_Id"); </code></pre> <p>or simply the below if you want to keep all the standard column names:</p> <pre><code>modelBuilder.Entity&lt;IdentityUser&gt;() .ToTable("Users", "dbo") </code></pre> <p>Full example below (this should be in your IdentityModel.cs file) i changed my ApplicationUser class to be called User.</p> <pre><code>public class User : IdentityUser { public string PasswordOld { get; set; } public DateTime DateCreated { get; set; } public bool Activated { get; set; } public bool UserRole { get; set; } } public class ApplicationDbContext : IdentityDbContext&lt;User&gt; { public ApplicationDbContext() : base("DefaultConnection") { } protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity&lt;IdentityUser&gt;() .ToTable("Users", "dbo").Property(p =&gt; p.Id).HasColumnName("User_Id"); modelBuilder.Entity&lt;User&gt;() .ToTable("Users", "dbo").Property(p =&gt; p.Id).HasColumnName("User_Id"); } } </code></pre> <p>Please note i have not managed to get this working if the current table exists. Also note whatever columns you do not map the default ones will be created.</p> <p>Hope that helps.</p>
{ "question_id": 19460386, "question_date": "2013-10-18T23:09:32.997Z", "question_score": 233, "tags": "c#|asp.net-identity", "answer_id": 19577814, "answer_date": "2013-10-24T22:21:57.093Z", "answer_score": 135 }
Please answer the following Stack Overflow question: Title: Why is ArrayDeque better than LinkedList <p>I am trying to to understand <strong>why Java's ArrayDeque is better than Java's LinkedList</strong> as they both implement Deque interface. </p> <p>I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. </p> <p>If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.</p>
<p>Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory.</p> <p>If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. </p> <p>The only better operation of a linked list is removing the current element during iteration.</p>
{ "question_id": 6163166, "question_date": "2011-05-28T17:16:39.393Z", "question_score": 233, "tags": "java|deque|linked-list|arraydeque", "answer_id": 6163204, "answer_date": "2011-05-28T17:23:34.073Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: How do you write tests for the argparse portion of a python module? <p>I have a Python module that uses the argparse library. How do I write tests for that section of the code base?</p>
<p>You should refactor your code and move the parsing to a function:</p> <pre><code>def parse_args(args): parser = argparse.ArgumentParser(...) parser.add_argument... # ...Create your parser as you like... return parser.parse_args(args) </code></pre> <p>Then in your <code>main</code> function you should just call it with:</p> <pre><code>parser = parse_args(sys.argv[1:]) </code></pre> <p>(where the first element of <code>sys.argv</code> that represents the script name is removed to not send it as an additional switch during CLI operation.)</p> <p>In your tests, you can then call the parser function with whatever list of arguments you want to test it with:</p> <pre><code>def test_parser(self): parser = parse_args(['-l', '-m']) self.assertTrue(parser.long) # ...and so on. </code></pre> <p>This way you'll never have to execute the code of your application just to test the parser.</p> <p>If you need to change and/or add options to your parser later in your application, then create a factory method:</p> <pre><code>def create_parser(): parser = argparse.ArgumentParser(...) parser.add_argument... # ...Create your parser as you like... return parser </code></pre> <p>You can later manipulate it if you want, and a test could look like:</p> <pre><code>class ParserTest(unittest.TestCase): def setUp(self): self.parser = create_parser() def test_something(self): parsed = self.parser.parse_args(['--something', 'test']) self.assertEqual(parsed.something, 'test') </code></pre>
{ "question_id": 18160078, "question_date": "2013-08-10T08:25:05.667Z", "question_score": 233, "tags": "python|unit-testing|argparse", "answer_id": 18161115, "answer_date": "2013-08-10T10:45:45.120Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: Eclipse menus don't show up after upgrading to Ubuntu 13.10 <p>After upgrading to Ubuntu 13.10, when I click on any menus in Eclipse (Help, Window, Run) they don’t show up. Only menu stubs and selection are visible.</p> <p><img src="https://i.stack.imgur.com/0sOOd.png" alt="Screenshot"></p> <p>I tried installing fresh 4.3 and the same thing is happening. Is anyone else experiencing this behavior?</p>
<p>The same question has been answered on askubuntu:</p> <p><a href="https://askubuntu.com/questions/361040/eclipse-menus-are-cut-off-or-dont-show">Eclipse menus are cut off or don't show</a></p> <p>I might have found a possible solution for your problem. I have experienced the same issue as you have described, Ubuntu 13.10 64-bit Unity, Eclipse 4.3.0, menus were not visible.</p> <p>So I realise that it might be helpful if I clarify myself, the desktop shortcut file for Eclipse would contain something like this:</p> <pre><code>[Desktop Entry] Version=4.3.0 Name=Eclipse Comment=IDE for all seasons #Exec=/home/USERNAME/Dokument/eclipse/eclipse Exec=env UBUNTU_MENUPROXY=0 /home/USERNAME/Dokument/eclipse/eclipse Icon=/home/USERNAME/Dokument/eclipse/icon.xpm Terminal=false Type=Application Categories=Utility;Application </code></pre> <p>The row <code>Exec=env UBUNTU_MENUPROXY=0 /home/USERNAME/Dokument/eclipse/eclipse</code>, part referenced in the post I pointed to, is the one that makes menus visible, et voila! :)</p> <p>In my case this file (<code>eclipse.desktop</code>) resides in <code>/usr/share/applications/</code></p> <p>Hope this helps.</p>
{ "question_id": 19452390, "question_date": "2013-10-18T14:39:06.217Z", "question_score": 233, "tags": "eclipse|ubuntu", "answer_id": 19526584, "answer_date": "2013-10-22T19:26:22.403Z", "answer_score": 258 }
Please answer the following Stack Overflow question: Title: What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6? <p>When generating services in the Angular CLI, it is adding extra metadata with a 'provided in' property with a default of 'root' for the Injectable decorator.</p> <pre><code>@Injectable({ providedIn: 'root', }) </code></pre> <p>What exactly does providedIn do? I am assuming this is making the service available like a 'global' type singleton service for the whole application, however, wouldn't be cleaner to declare such services in the provider array of the AppModule?</p>
<p>if you use providedIn, the injectable is registered as a provider of the Module without adding it to the providers of the module.</p> <p>From <a href="https://angular.io/guide/providers#providedin-and-ngmodules" rel="noreferrer"><code>Docs</code></a></p> <blockquote> <p>The service itself is a class that the CLI generated and that's decorated with @Injectable. By default, this decorator is configured with a providedIn property, which creates a provider for the service. In this case, providedIn: 'root' specifies that the service should be provided in the root injector.</p> </blockquote>
{ "question_id": 50848357, "question_date": "2018-06-14T01:22:51.557Z", "question_score": 233, "tags": "angular|typescript|angular6", "answer_id": 50848377, "answer_date": "2018-06-14T01:25:22.977Z", "answer_score": 71 }
Please answer the following Stack Overflow question: Title: Why Android Studio says "Waiting For Debugger" if am NOT debugging? <p>I am working with Android Studio. Since last night, when I Run my project on my device, appear the message "Waiting For Debugger". It is a very strange behavior because I am not debugging application.</p> <p>I've tried to uninstall application from my device and press Run on Android Studio. The message appears again.</p> <p>I've tried to restart Android Studio. The message appears again.</p> <p>The only way to properly install application on my phone is to press "Debug". The message appears but its automatically closed. Then application works fine.</p> <p>I've tried with</p> <pre><code>&lt;application android:debuggable="false" /&gt; </code></pre> <p>... and still the message appears.</p> <p>LogCat says:</p> <pre><code>E/InputDispatcher﹕ channel ~ Channel is unrecoverably broken and will be disposed! E/Launcher﹕ Error finding setting, default accessibility to not found: accessibility_enabled </code></pre> <p>Regards on first error line, <a href="https://stackoverflow.com/questions/12459719/why-i-am-getting-error-channel-is-unrecoverably-broken-and-will-be-disposed">someone says that the problems can starts after renaming of some resource</a>. But its not my case.</p> <p>Regards on second error line, ... I don't know. I really don't know what happens to my IDE.</p>
<p>I've ran into this issue in the past and again today. In my case the problem is resolved by a device reboot. After a clean boot I can again run the application and the "Waiting for Debugger" prompt does not appear.</p>
{ "question_id": 20537845, "question_date": "2013-12-12T07:49:47.013Z", "question_score": 233, "tags": "java|android|android-studio|debugging", "answer_id": 24560041, "answer_date": "2014-07-03T17:36:34.430Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: Difference Between Firestore Set with {merge: true} and Update <p>In <strong>Cloud Firestore</strong> there are three write operations:</p> <ol> <li><code>add()</code></li> <li><code>set()</code></li> <li><code>update()</code></li> </ol> <p>In the docs it says that using <code>set(object, { merge: true })</code> will merge the given object with the existing document.</p> <p>The same happens when you use <code>update(object)</code>... so what is the difference? It seems strange that google would duplicate functionality like this.</p>
<p>The way I understood the difference:</p> <ul> <li><p><code>set</code> without <code>merge</code> will overwrite a document or create it if it doesn't exist yet</p></li> <li><p><code>set</code> with <code>merge</code> will update fields in the document or create it if it doesn't exists</p></li> <li><p><code>update</code> will update fields but will fail if the document doesn't exist</p></li> <li><p><code>create</code> will create the document but fail if the document already exists</p></li> </ul> <p>There's also a difference in the kind of data you provide to <code>set</code> and <code>update</code>.</p> <p>For <code>set</code> you always have to provide document-shaped data:</p> <pre><code>set( {a: {b: {c: true}}}, {merge: true} ) </code></pre> <p>With <code>update</code> you can also use field paths for updating nested values:</p> <pre><code>update({ 'a.b.c': true }) </code></pre>
{ "question_id": 46597327, "question_date": "2017-10-06T02:17:40.337Z", "question_score": 233, "tags": "database|firebase|google-cloud-firestore", "answer_id": 46600599, "answer_date": "2017-10-06T07:35:11Z", "answer_score": 520 }
Please answer the following Stack Overflow question: Title: What really is a deque in STL? <p>I was looking at STL containers and trying to figure what they really are (i.e. the data structure used), and the <em>deque</em> stopped me: I thought at first that it was a double linked list, which would allow insertion and deletion from both ends in constant time, but I am troubled by <a href="http://en.cppreference.com/w/cpp/container/deque/operator_at" rel="noreferrer">the promise made</a> by the operator [] to be done in constant time. In a linked list, arbitrary access should be O(n), right?</p> <p>And if it's a dynamic array, how can it <a href="http://en.cppreference.com/w/cpp/container/deque/push_back" rel="noreferrer">add elements</a> in constant time? It should be mentioned that reallocation may happen, and that O(1) is an amortized cost, <a href="http://en.cppreference.com/w/cpp/container/vector/push_back" rel="noreferrer">like for a vector</a>.</p> <p>So I wonder what is this structure that allows arbitrary access in constant time, and at the same time never needs to be moved to a new bigger place.</p>
<p>A deque is somewhat recursively defined: internally it maintains a double-ended queue of <em>chunks</em> of fixed size. Each chunk is a vector, and the queue (“map” in the graphic below) of chunks itself is also a vector.</p> <p><a href="https://i.stack.imgur.com/SthOW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SthOW.png" alt="schematic of the memory layout of a deque" /></a></p> <p>There’s a great analysis of the performance characteristics and how it compares to the <code>vector</code> over at <a href="https://www.codeproject.com/Articles/5425/An-In-Depth-Study-of-the-STL-Deque-Container" rel="noreferrer">CodeProject</a>.</p> <p>The GCC standard library implementation internally uses a <code>T**</code> to represent the map. Each data block is a <code>T*</code> which is allocated with some fixed size <code>__deque_buf_size</code> (which depends on <code>sizeof(T)</code>).</p>
{ "question_id": 6292332, "question_date": "2011-06-09T11:52:47.903Z", "question_score": 233, "tags": "c++|stl|deque", "answer_id": 6292437, "answer_date": "2011-06-09T12:00:22.020Z", "answer_score": 228 }
Please answer the following Stack Overflow question: Title: ng-app vs. data-ng-app, what is the difference? <p>I'm currently looking at <a href="http://www.youtube.com/watch?feature=player_detailpage&amp;v=i9MHigUZKEM">this start tutorial video</a> for <code>angular.js</code></p> <p>At some moment (after 12'40"), the speaker states that the attributes <code>ng-app</code> and <code>data-ng-app=""</code> are more or less equivalent inside the <code>&lt;html&gt;</code> tag, and so are <code>ng-model="my_data_binding</code> and <code>data-ng-model="my_data_binding"</code>. However The speaker says the html would be validated through different validators, depending on which attribute is used.</p> <p>Could you explain the difference between the two ways, <code>ng-</code> prefix against <code>data-ng-</code> prefix ? </p>
<p>Good question. The difference is simple - there is absolutely no difference between the two <strong>except</strong> that certain HTML5 validators will throw an error on a property like <code>ng-app</code>, but they don't throw an error for anything prefixed with <code>data-</code>, like <code>data-ng-app</code>.</p> <p>So to answer your question, use <code>data-ng-app</code> if you would like validating your HTML to be a bit easier.</p> <p>Fun fact: You can also use <code>x-ng-app</code> to the same effect.</p>
{ "question_id": 16589853, "question_date": "2013-05-16T14:15:44.717Z", "question_score": 233, "tags": "html|angularjs", "answer_id": 16589915, "answer_date": "2013-05-16T14:18:19.250Z", "answer_score": 407 }
Please answer the following Stack Overflow question: Title: google protocol buffers vs json vs XML <p>I would like to know the merits &amp; de-merits of</p> <ul> <li>Google Protocol Buffers</li> <li>JSON</li> <li>XML</li> </ul> <p>I want to implement one common framework for two application, one in Perl and second in Java. So, would like to create common service which can be used by both technology i.e. Perl &amp; Java.</p> <p>Both are web-applications.</p> <p>Please share me your valuable thoughts &amp; suggestion on this. I have seen many links on google but all have mixed opinions.</p>
<p>Json</p> <ul> <li>human readable/editable</li> <li>can be parsed without knowing schema in advance</li> <li>excellent browser support</li> <li>less verbose than XML</li> </ul> <p>XML</p> <ul> <li>human readable/editable</li> <li>can be parsed without knowing schema in advance</li> <li>standard for SOAP etc</li> <li>good tooling support (xsd, xslt, sax, dom, etc)</li> <li>pretty verbose</li> </ul> <p>Protobuf</p> <ul> <li>very dense data (small output)</li> <li>hard to robustly decode without knowing the schema (data format is internally ambiguous, and needs schema to clarify)</li> <li>very fast processing</li> <li>not intended for human eyes (dense binary)</li> </ul> <p>All have good support on most platforms.</p> <p>Personally, I rarely use XML these days. If the consumer is a browser or a public API I tend to use json. For internal APIs I tend to use protobuf for performance. Offering both on public API (either via headers, or separate endpoints) works well too.</p>
{ "question_id": 14028293, "question_date": "2012-12-25T06:32:28.697Z", "question_score": 233, "tags": "xml|json|protocol-buffers|data-serialization", "answer_id": 14029040, "answer_date": "2012-12-25T08:37:27.417Z", "answer_score": 292 }
Please answer the following Stack Overflow question: Title: Why is a 3-way merge advantageous over a 2-way merge? <p><a href="http://en.wikipedia.org/wiki/Merge_%28revision_control%29#Three-way_merge" rel="noreferrer">Wikipedia</a> says a 3-way merge is less error-prone than a 2-way merge, and often times doesn't need user intervention. Why is this the case?</p> <p>An example where a 3-way merge succeeds and a 2-way merge fails would be helpful.</p>
<p>Say you and your friend both checked out a file, and made some changes to it. You removed a line at the beginning, and your friend added a line at the end. Then he committed his file, and you need to merge his changes into your copy.</p> <p>If you were doing a two-way merge (in other words, a diff), the tool could compare the two files, and see that the first and last lines are different. But how would it know what to do with the differences? Should the merged version include the first line? Should it include the last line?</p> <p>With a three-way merge, it can compare the two files, but it can also compare each of them against the original copy (before either of you changed it). So it can see that you removed the first line, and that your friend added the last line. And it can use that information to produce the merged version.</p>
{ "question_id": 4129049, "question_date": "2010-11-08T23:14:54.250Z", "question_score": 233, "tags": "version-control|merge|conflict|three-way-merge", "answer_id": 4129145, "answer_date": "2010-11-08T23:36:23.700Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: Are getters and setters poor design? Contradictory advice seen <p>I'm currently working on a simple game in Java with several different modes. I've extended a main Game class to put the main logic within the other classes. Despite this, the main game class is still pretty hefty.</p> <p>After taking a quick look at my code the majority of it was Getters and Setters (60%) compared to the rest that is truly needed for the logic of the game.</p> <p>A couple of Google searches have claimed that Getters and Setters are evil, whilst others have claimed that they are necessary for good OO practice and great programs.</p> <p>So what should I do? Which should it be? Should I be changing my Getters and Setters for my private variables, or should I stick with them?</p>
<p>There is also the point of view that most of the time, using setters still breaks encapsulation by allowing you to set values that are meaningless. As a very obvious example, if you have a score counter on the game that only ever goes up, instead of</p> <pre><code>// Game private int score; public void setScore(int score) { this.score = score; } public int getScore() { return score; } // Usage game.setScore(game.getScore() + ENEMY_DESTROYED_SCORE); </code></pre> <p>it should be</p> <pre><code>// Game private int score; public int getScore() { return score; } public void addScore(int delta) { score += delta; } // Usage game.addScore(ENEMY_DESTROYED_SCORE); </code></pre> <p>This is perhaps a bit of a facile example. What I'm trying to say is that discussing getter/setters vs public fields often obscures bigger problems with objects manipulating each others' internal state in an intimate manner and hence being too closely coupled.</p> <p>The idea is to make methods that directly do things you want to do. An example would be how to set enemies' "alive" status. You might be tempted to have a setAlive(boolean alive) method. Instead you should have:</p> <pre><code>private boolean alive = true; public boolean isAlive() { return alive; } public void kill() { alive = false; } </code></pre> <p>The reason for this is that if you change the implementation that things no longer have an "alive" boolean but rather a "hit points" value, you can change that around without breaking the contract of the two methods you wrote earlier:</p> <pre><code>private int hp; // Set in constructor. public boolean isAlive() { return hp &gt; 0; } // Same method signature. public void kill() { hp = 0; } // Same method signature. public void damage(int damage) { hp -= damage; } </code></pre>
{ "question_id": 565095, "question_date": "2009-02-19T12:33:20Z", "question_score": 233, "tags": "java|oop|setter|getter|accessor", "answer_id": 565227, "answer_date": "2009-02-19T13:03:56.917Z", "answer_score": 353 }
Please answer the following Stack Overflow question: Title: How to complete a git clone for a big project on an unstable connection? <p>I am trying to git clone the LibreOffice codebase, but at the moment I have an internet connection of about 300kbps and it's just anything but stable. I can get the connection back any moment, but then the git clone process already stopped working, and no way to get it running again. Is there some way to have a more failure-resistant git clone download?</p> <p>One option I considered myself is to download someone else's .git directory, but that is overly dependent of others and doesn't seem like the best possible solution to me.</p>
<p>I don't think this is ready yet. There's <a href="https://git.wiki.kernel.org/index.php/SoC2008Ideas#head-bcfe9e77ab9670575d242059ce3bedacd7f73126" rel="noreferrer">an old GSoC page</a> that which planned to implement your desired feature. My best bet is, like you suggested download it as a directory. I'm assuming you are able to resume downloads over other protocols.</p> <blockquote> <p>Restartable Clone</p> <p>When cloning a large repository (such as KDE, Open Office, Linux kernel) there is currently no way to restart an interrupted clone. It may take considerable time for a user on the end of a small pipe to download the data, and if the clone is interrupted in the middle the user currently needs to start over from the beginning and try again. For some users this may make it impossible to clone a large repository.</p> <p>Goal: Allow git-clone to automatically resume a previously failed download over the native git:// protocol. Language: C Mentor: Shawn Pearce Suggested by: Shawn Pearce on gmane</p> </blockquote> <hr> <h3>Update</h3> <p>Along with the shallow cloning (<code>git clone --depth=1</code>) suggestion in one of the other answers it may be helpful if someone can make a bare repository for you if you can communicate with the provider. You can easily <a href="https://stackoverflow.com/q/2199897/399268">convert</a> the bare repository to a full repository. Also read the comments in that answer as a shallow clone may not always help.</p>
{ "question_id": 3954852, "question_date": "2010-10-17T19:22:34.733Z", "question_score": 233, "tags": "git|git-clone", "answer_id": 3954878, "answer_date": "2010-10-17T19:28:09.323Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: Node.js and CPU intensive requests <p>I've started tinkering with Node.js HTTP server and really like to write server side Javascript but something is keeping me from starting to use Node.js for my web application.</p> <p>I understand the whole async I/O concept but I'm somewhat concerned about the edge cases where procedural code is very CPU intensive such as image manipulation or sorting large data sets.</p> <p>As I understand it, the server will be very fast for simple web page requests such as viewing a listing of users or viewing a blog post. However, if I want to write very CPU intensive code (in the admin back end for example) that generates graphics or resizes thousands of images, the request will be very slow (a few seconds). Since this code is not async, every requests coming to the server during those few seconds will be blocked until my slow request is done. </p> <p>One suggestion was to use Web Workers for CPU intensive tasks. However, I'm afraid web workers will make it hard to write clean code since it works by including a separate JS file. What if the CPU intensive code is located in an object's method? It kind of sucks to write a JS file for every method that is CPU intensive.</p> <p>Another suggestion was to spawn a child process, but that makes the code even less maintainable.</p> <p>Any suggestions to overcome this (perceived) obstacle? How do you write clean object oriented code with Node.js while making sure CPU heavy tasks are executed async? </p>
<p>What you need is a task queue! Moving your long running tasks out of the web-server is a GOOD thing. Keeping each task in "separate" js file promotes modularity and code reuse. It forces you to think about how to structure your program in a way that will make it easier to debug and maintain in the long run. Another benefit of a task queue is the workers can be written in a different language. Just pop a task, do the work, and write the response back.</p> <p>something like this <a href="https://github.com/resque/resque" rel="noreferrer">https://github.com/resque/resque</a></p> <p>Here is an article from github about why they built it <a href="http://github.com/blog/542-introducing-resque" rel="noreferrer">http://github.com/blog/542-introducing-resque</a></p>
{ "question_id": 3491811, "question_date": "2010-08-16T09:04:31.567Z", "question_score": 233, "tags": "javascript|node.js|serverside-javascript|web-worker", "answer_id": 3536183, "answer_date": "2010-08-21T03:39:55.937Z", "answer_score": 60 }
Please answer the following Stack Overflow question: Title: What is `git diff --patience` for? <p>How does the patience algorithm differ from the default <code>git diff</code> algorithm, and when would I want to use it?</p>
<p>You can read <a href="https://web.archive.org/web/20200128181055/http://git.661346.n2.nabble.com/Bram-Cohen-speaks-up-about-patience-diff-td2277041.html" rel="nofollow noreferrer">a post from Bram Cohen</a>, the author of the patience diff algorithm, but I found <a href="http://bryanpendleton.blogspot.com/2010/05/patience-diff.html" rel="nofollow noreferrer">this blog post</a> to summarize the patience diff algorithm very well:</p> <blockquote> <p>Patience Diff, instead, focuses its energy on the low-frequency high-content lines which serve as markers or signatures of important content in the text. It is still an LCS-based diff at its core, but with an important difference, as it only considers the longest common subsequence of the signature lines:</p> <blockquote> <p>Find all lines which occur exactly once on both sides, then do longest common subsequence on those lines, matching them up.</p> </blockquote> </blockquote> <p>When should you <em>use</em> patience diff? According to Bram, patience diff is good for this situation:</p> <blockquote> <p>The really bad cases are ones where two versions have diverged dramatically and the developer isn't being careful to keep patch sizes under control. Under those circumstances a diff algorithm can occasionally become 'misaligned' in that it matches long sections of curly brackets together, but it winds up correlating the curly brackets of functions in one version with the curly brackets of the next later function in the other version. This situation is <em>very ugly</em>, and can result in a totally unusable conflict file in the situation where you need such things to be presented coherently the most.</p> </blockquote>
{ "question_id": 4045017, "question_date": "2010-10-28T16:26:50.750Z", "question_score": 233, "tags": "git|diff", "answer_id": 4045087, "answer_date": "2010-10-28T16:34:58.823Z", "answer_score": 191 }
Please answer the following Stack Overflow question: Title: What are the differences between segment trees, interval trees, binary indexed trees and range trees? <p>What are differences between segment trees, interval trees, binary indexed trees and range trees in terms of:</p> <ul> <li>Key idea/definition </li> <li>Applications </li> <li>Performance/order in higher dimensions/space consumption</li> </ul> <p>Please do not just give definitions.</p>
<p>All these data structures are used for solving different problems:</p> <ul> <li><strong>Segment tree</strong> stores intervals, and optimized for "<em>which of these intervals contains a given point</em>" queries.</li> <li><strong>Interval tree</strong> stores intervals as well, but optimized for "<em>which of these intervals overlap with a given interval</em>" queries. It can also be used for point queries - similar to segment tree. </li> <li><strong>Range tree</strong> stores points, and optimized for "<em>which points fall within a given interval</em>" queries.</li> <li><strong>Binary indexed tree</strong> stores items-count per index, and optimized for "<em>how many items are there between index m and n</em>" queries.</li> </ul> <p>Performance / Space consumption for one dimension:</p> <ul> <li><strong>Segment tree</strong> - O(n logn) preprocessing time, O(k+logn) query time, O(n logn) space</li> <li><strong>Interval tree</strong> - O(n logn) preprocessing time, O(k+logn) query time, O(n) space</li> <li><strong>Range tree</strong> - O(n logn) preprocessing time, O(k+logn) query time, O(n) space</li> <li><strong>Binary Indexed tree</strong> - O(n logn) preprocessing time, O(logn) query time, O(n) space</li> </ul> <p>(k is the number of reported results).</p> <p>All data structures can be dynamic, in the sense that the usage scenario includes both data changes and queries:</p> <ul> <li><strong>Segment tree</strong> - interval can be added/deleted in O(logn) time (see <a href="http://3glab.cs.nthu.edu.tw/~spoon/courses/CS631100/Lecture05_handout.pdf">here</a>)</li> <li><strong>Interval tree</strong> - interval can be added/deleted in O(logn) time</li> <li><strong>Range tree</strong> - new points can be added/deleted in O(logn) time (see <a href="http://www.cs.unb.ca/tech-reports/documents/TR95_100.pdf">here</a>)</li> <li><strong>Binary Indexed tree</strong> - the items-count per index can be increased in O(logn) time</li> </ul> <p>Higher dimensions (d>1):</p> <ul> <li><strong>Segment tree</strong> - O(n(logn)^d) preprocessing time, O(k+(logn)^d) query time, O(n(logn)^(d-1)) space</li> <li><strong>Interval tree</strong> - O(n logn) preprocessing time, O(k+(logn)^d) query time, O(n logn) space</li> <li><strong>Range tree</strong> - O(n(logn)^d) preprocessing time, O(k+(logn)^d) query time, O(n(logn)^(d-1))) space</li> <li><strong>Binary Indexed tree</strong> - O(n(logn)^d) preprocessing time, O((logn)^d) query time, O(n(logn)^d) space</li> </ul>
{ "question_id": 17466218, "question_date": "2013-07-04T09:04:39.833Z", "question_score": 233, "tags": "algorithm|tree|graph-algorithm|interval-tree|segment-tree", "answer_id": 17504505, "answer_date": "2013-07-06T15:49:08.683Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired <p>Why am I getting this database error when I update a table?</p> <blockquote> <p>ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired</p> </blockquote>
<p>Your table is already locked by some query. For example, you may have executed "select for update" and have not yet committed/rollbacked and fired another select query. Do a commit/rollback before executing your query.</p>
{ "question_id": 4842765, "question_date": "2011-01-30T11:59:43.563Z", "question_score": 232, "tags": "oracle|ora-00054", "answer_id": 4842778, "answer_date": "2011-01-30T12:02:20.877Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: Import CSV file into SQL Server <p>I am looking for help to import a <code>.csv</code> file into SQL Server using <code>BULK INSERT</code> and I have few basic questions.</p> <p><strong>Issues:</strong> </p> <ol> <li><p>The CSV file data may have <code>,</code> (comma) in between (Ex: description), so how can I make import handling these data? </p></li> <li><p>If the client creates the CSV from Excel then the data that have comma are enclosed within <code>""</code> (double quotes) [as the below example] so how do the import can handle this? </p></li> <li><p>How do we track if some rows have bad data, which import skips? (does import skips rows that are not importable)</p></li> </ol> <p>Here is the sample CSV with header:</p> <pre><code>Name,Class,Subject,ExamDate,Mark,Description Prabhat,4,Math,2/10/2013,25,Test data for prabhat. Murari,5,Science,2/11/2013,24,"Test data for his's test, where we can test 2nd ROW, Test." sanjay,4,Science,,25,Test Only. </code></pre> <p>And SQL statement to import:</p> <pre><code>BULK INSERT SchoolsTemp FROM 'C:\CSVData\Schools.csv' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ',', --CSV field delimiter ROWTERMINATOR = '\n', --Use to shift the control to next row TABLOCK ) </code></pre>
<p>Based SQL Server CSV Import</p> <blockquote> <p>1) The CSV file data may have <code>,</code> (comma) in between (Ex: description), so how can I make import handling these data?</p> </blockquote> <p><strong>Solution</strong></p> <p>If you're using <code>,</code> (comma) as a delimiter, then there is no way to differentiate between a comma as a field terminator and a comma in your data. I would use a different <code>FIELDTERMINATOR</code> like <code>||</code>. Code would look like and this will handle comma and single slash perfectly.</p> <blockquote> <p>2) If the client create the csv from excel then the data that have comma are enclosed within <code>" ... "</code> (double quotes) [as the below example] so how do the import can handle this?</p> </blockquote> <p><strong>Solution</strong></p> <p>If you're using BULK insert then there is no way to handle double quotes, data will be inserted with double quotes into rows. after inserting the data into table you could replace those double quotes with '<code></code>'.</p> <pre><code>update table set columnhavingdoublequotes = replace(columnhavingdoublequotes,'"','') </code></pre> <blockquote> <p>3) How do we track if some rows have bad data, which import skips? (does import skips rows that are not importable)?</p> </blockquote> <p><strong>Solution</strong></p> <p>To handle rows which aren't loaded into table because of invalid data or format, could be handle using <a href="http://msdn.microsoft.com/en-us/library/ms188365.aspx" rel="noreferrer">ERRORFILE property</a>, specify the error file name, it will write the rows having error to error file. code should look like.</p> <pre><code>BULK INSERT SchoolsTemp FROM 'C:\CSVData\Schools.csv' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ',', --CSV field delimiter ROWTERMINATOR = '\n', --Use to shift the control to next row ERRORFILE = 'C:\CSVDATA\SchoolsErrorRows.csv', TABLOCK ) </code></pre>
{ "question_id": 15242757, "question_date": "2013-03-06T08:53:41.680Z", "question_score": 232, "tags": "sql|sql-server|csv|bulkinsert|bulk", "answer_id": 15243801, "answer_date": "2013-03-06T09:45:04.913Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Converting Java objects to JSON with Jackson <p>I want my JSON to look like this:</p> <pre><code>{ "information": [{ "timestamp": "xxxx", "feature": "xxxx", "ean": 1234, "data": "xxxx" }, { "timestamp": "yyy", "feature": "yyy", "ean": 12345, "data": "yyy" }] } </code></pre> <p>Code so far:</p> <pre><code>import java.util.List; public class ValueData { private List&lt;ValueItems&gt; information; public ValueData(){ } public List&lt;ValueItems&gt; getInformation() { return information; } public void setInformation(List&lt;ValueItems&gt; information) { this.information = information; } @Override public String toString() { return String.format("{information:%s}", information); } } </code></pre> <p>and</p> <pre><code>public class ValueItems { private String timestamp; private String feature; private int ean; private String data; public ValueItems(){ } public ValueItems(String timestamp, String feature, int ean, String data){ this.timestamp = timestamp; this.feature = feature; this.ean = ean; this.data = data; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getFeature() { return feature; } public void setFeature(String feature) { this.feature = feature; } public int getEan() { return ean; } public void setEan(int ean) { this.ean = ean; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public String toString() { return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data); } } </code></pre> <p>I just missing the part how I can convert the Java object to JSON with Jackson:</p> <pre><code>public static void main(String[] args) { // CONVERT THE JAVA OBJECT TO JSON HERE System.out.println(json); } </code></pre> <p>My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?</p>
<p>To convert your <code>object</code> in JSON with Jackson:</p> <pre><code>import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(object); </code></pre>
{ "question_id": 15786129, "question_date": "2013-04-03T11:29:39.957Z", "question_score": 232, "tags": "java|json|object|jackson", "answer_id": 15786175, "answer_date": "2013-04-03T11:31:37.997Z", "answer_score": 564 }
Please answer the following Stack Overflow question: Title: How to remove all MySQL tables from the command-line without DROP database permissions? <p>How do I drop all tables in Windows MySQL, using command prompt? The reason I want to do this is that our user has access to the database drops, but no access to re-creating the database itself, for this reason we must drop the tables manually. Is there a way to drop all the tables at once? Bear in mind that most of the tables are linked with foreign keys so they would have to be dropped in a specific order.</p>
<p>You can generate statement like this: <code>DROP TABLE t1, t2, t3, ...</code> and then use prepared statements to execute it:</p> <pre><code>SET FOREIGN_KEY_CHECKS = 0; SET @tables = NULL; SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables FROM information_schema.tables WHERE table_schema = 'database_name'; -- specify DB name here. SET @tables = CONCAT('DROP TABLE ', @tables); PREPARE stmt FROM @tables; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET FOREIGN_KEY_CHECKS = 1; </code></pre>
{ "question_id": 12403662, "question_date": "2012-09-13T09:52:46.353Z", "question_score": 232, "tags": "mysql|command-line|sql-drop", "answer_id": 12403746, "answer_date": "2012-09-13T09:58:49.613Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Center content in responsive bootstrap navbar <p>I'm having trouble centering my content in the bootstrap navbar. I'm using bootstrap 3. I've read many posts, but the CSS or methods used will not work with my code! I'm really frustrated, so this is like my last option. Any help would be appreciated!</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Navigation&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- Bootstrap --&gt; &lt;link href="css/bootstrap.min.css" rel="stylesheet" media="screen"&gt; &lt;link href="css/style.css" rel="stylesheet" media="screen"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;nav class="navbar navbar-default" role="navigation"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;!-- Collect the nav links, forms, and other content for toggling --&gt; &lt;div class="collapse navbar-collapse navbar-ex1-collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;Dropdown &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- /.navbar-collapse --&gt; &lt;/nav&gt; &lt;h1&gt;Home&lt;/h1&gt; &lt;/div&gt; &lt;!--JAVASCRIPT--&gt; &lt;script src="js/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="https://jsfiddle.net/amk07fb3/" rel="noreferrer">https://jsfiddle.net/amk07fb3/</a></p>
<p>I think this is what you are looking for. You need to remove the <code>float: left</code> from the inner nav to center it and make it a inline-block.</p> <pre><code>.navbar .navbar-nav { display: inline-block; float: none; vertical-align: top; } .navbar .navbar-collapse { text-align: center; } </code></pre> <p><a href="http://jsfiddle.net/bdd9U/2/" rel="noreferrer">http://jsfiddle.net/bdd9U/2/</a></p> <p><strong>Edit:</strong> if you only want this effect to happen when the nav isn't collapsed surround it in the appropriate media query.</p> <pre><code>@media (min-width: 768px) { .navbar .navbar-nav { display: inline-block; float: none; vertical-align: top; } .navbar .navbar-collapse { text-align: center; } } </code></pre> <p><a href="http://jsfiddle.net/bdd9U/3/" rel="noreferrer">http://jsfiddle.net/bdd9U/3/</a></p>
{ "question_id": 18777235, "question_date": "2013-09-13T02:17:33.407Z", "question_score": 232, "tags": "css|twitter-bootstrap|navbar", "answer_id": 18778769, "answer_date": "2013-09-13T05:14:21.770Z", "answer_score": 463 }
Please answer the following Stack Overflow question: Title: Convert JSON to Map <p>What is the best way to convert a JSON code as this:</p> <pre><code>{ "data" : { "field1" : "value1", "field2" : "value2" } } </code></pre> <p>in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).</p> <p>Any ideas? Should I use Json-lib for that? Or better if I write my own parser?</p>
<p>I hope you were joking about writing your own parser. :-)</p> <p>For such a simple mapping, most tools from <a href="http://json.org" rel="noreferrer">http://json.org</a> (section java) would work. For one of them (Jackson <a href="https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator" rel="noreferrer">https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator</a>), you'd do:</p> <pre><code>Map&lt;String,Object&gt; result = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class); </code></pre> <p>(where JSON_SOURCE is a File, input stream, reader, or json content String)</p>
{ "question_id": 443499, "question_date": "2009-01-14T16:00:38.773Z", "question_score": 232, "tags": "java|json|parsing|collections", "answer_id": 583634, "answer_date": "2009-02-24T21:11:56.707Z", "answer_score": 416 }
Please answer the following Stack Overflow question: Title: Reading Excel files from C# <p>Is there a free or open source library to read Excel files (.xls) directly from a C# program? </p> <p>It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.</p>
<pre><code>var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory()); var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "anyNameHere"); DataTable data = ds.Tables["anyNameHere"]; </code></pre> <p>This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables: </p> <pre><code>var data = ds.Tables["anyNameHere"].AsEnumerable(); </code></pre> <p>as this lets me use LINQ to search and build structs from the fields.</p> <pre><code>var query = data.Where(x =&gt; x.Field&lt;string&gt;("phoneNumber") != string.Empty).Select(x =&gt; new MyContact { firstName= x.Field&lt;string&gt;("First Name"), lastName = x.Field&lt;string&gt;("Last Name"), phoneNumber =x.Field&lt;string&gt;("Phone Number"), }); </code></pre>
{ "question_id": 15828, "question_date": "2008-08-19T07:23:46.703Z", "question_score": 232, "tags": "c#|.net|excel|ms-office", "answer_id": 16051, "answer_date": "2008-08-19T12:18:20.197Z", "answer_score": 152 }
Please answer the following Stack Overflow question: Title: Linq style "For Each" <p>Is there any Linq style syntax for "For each" operations?</p> <p>For instance, add values based on one collection to another, already existing one:</p> <pre><code>IEnumerable&lt;int&gt; someValues = new List&lt;int&gt;() { 1, 2, 3 }; IList&lt;int&gt; list = new List&lt;int&gt;(); someValues.ForEach(x =&gt; list.Add(x + 1)); </code></pre> <p>Instead of </p> <pre><code>foreach(int value in someValues) { list.Add(value + 1); } </code></pre>
<p>Using the ToList() extension method is your best option:</p> <pre><code>someValues.ToList().ForEach(x =&gt; list.Add(x + 1)); </code></pre> <p>There is no extension method in the BCL that implements ForEach directly.</p> <hr> <p>Although there's no extension method in the <em>BCL</em> that does this, there <em>is</em> still an option in the <code>System</code> namespace... if you add <a href="https://www.nuget.org/packages/Rx-Main" rel="noreferrer">Reactive Extensions</a> to your project:</p> <pre><code>using System.Reactive.Linq; someValues.ToObservable().Subscribe(x =&gt; list.Add(x + 1)); </code></pre> <p>This has the same end result as the above use of <code>ToList</code>, but is (in theory) more efficient, because it streams the values directly to the delegate.</p>
{ "question_id": 1509442, "question_date": "2009-10-02T13:16:39.067Z", "question_score": 232, "tags": "c#|.net|linq|foreach", "answer_id": 1509450, "answer_date": "2009-10-02T13:17:48.277Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: Changing the maximum length of a varchar column? <p>I'm trying to update the length of a varchar column from 255 characters to 500 without losing the contents. I've dropped and re-created tables before but I've never been exposed to the alter statement which is what I believe I need to use to do this. I found the documentation here: <a href="http://msdn.microsoft.com/en-us/library/ms190273.aspx" rel="noreferrer">ALTER TABLE (Transfact-SQL)</a> however I can't make heads or tails of it.</p> <p>I have the following so far (essentially nothing unfortunately):</p> <pre><code>alter table [progennet_dev].PROGEN.LE alter column UR_VALUE_3 </code></pre> <p>How do I approach this? Is there better documentation for this statement out there (I did some searches for an example statement but came up empty)?</p>
<p>You need </p> <pre><code>ALTER TABLE YourTable ALTER COLUMN YourColumn &lt;&lt;new_datatype&gt;&gt; [NULL | NOT NULL] </code></pre> <p>But remember to specify <code>NOT NULL</code> explicitly if desired. </p> <pre><code>ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL; </code></pre> <p>If you leave it unspecified as below...</p> <pre><code>ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500); </code></pre> <p>Then the column will default to allowing nulls even if it was originally defined as <code>NOT NULL</code>. i.e. omitting the specification in an <code>ALTER TABLE ... ALTER COLUMN</code> is always treated as.</p> <pre><code>ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL; </code></pre> <p>This behaviour is different from that used for new columns created with <code>ALTER TABLE</code> (or at <code>CREATE TABLE</code> time). There the default nullability depends on the <a href="https://msdn.microsoft.com/en-us/library/ms187375.aspx" rel="noreferrer"><code>ANSI_NULL_DFLT</code></a> settings.</p>
{ "question_id": 8829053, "question_date": "2012-01-12T01:34:48.317Z", "question_score": 232, "tags": "sql|sql-server|sql-server-2008|tsql|varchar", "answer_id": 8829066, "answer_date": "2012-01-12T01:36:21.267Z", "answer_score": 448 }
Please answer the following Stack Overflow question: Title: Can I apply a CSS style to an element name? <p>I'm currently working on a project where I have no control over the HTML that I am applying CSS styles to. And the HTML is not very well labelled, in the sense that there are not enough id and class declarations to differentiate between elements.</p> <p>So, I'm looking for ways I can apply styles to objects that don't have an id or class attribute.</p> <p>Sometimes, form items have a "name" or "value" attribute:</p> <pre><code>&lt;input type="submit" value="Go" name="goButton"&gt; </code></pre> <p>Is there a way I can apply a style based on name="goButton"? What about "value"?</p> <p>It's the kind of thing that's hard to find out because a Google search will find all sorts of instances in which broad terms like "name" and "value" will appear in web pages.</p> <p>I'm kind of suspecting the answer is no... but perhaps someone has a clever hack?</p> <p>Any advice would be greatly appreciated.</p>
<p>You can use the attribute selector, </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>input[name="goButton"] { background: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input name="goButton"&gt;</code></pre> </div> </div> </p> <p>Be aware that it isn't supported in IE6.</p> <p>Update: In 2016 you can pretty much use them as you want, since IE6 is dead. <a href="http://quirksmode.org/css/selectors/" rel="noreferrer">http://quirksmode.org/css/selectors/</a></p> <p><a href="http://reference.sitepoint.com/css/attributeselector" rel="noreferrer">http://reference.sitepoint.com/css/attributeselector</a></p>
{ "question_id": 5468766, "question_date": "2011-03-29T06:32:33.653Z", "question_score": 232, "tags": "html|css|css-selectors", "answer_id": 5468771, "answer_date": "2011-03-29T06:33:14.153Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: JavaScript get window X/Y position for scroll <p>I'm hoping to find a way to get the current viewable window's position (relative to the total page width/height) so I can use it to force a scroll from one section to another. However, there seems to be a tremendous amount of options when it comes to guessing which object holds the true X/Y for your browser.</p> <p>Which of these do I need to make sure IE 6+, FF 2+, and Chrome/Safari work?</p> <pre><code>window.innerWidth window.innerHeight window.pageXOffset window.pageYOffset document.documentElement.clientWidth document.documentElement.clientHeight document.documentElement.scrollLeft document.documentElement.scrollTop document.body.clientWidth document.body.clientHeight document.body.scrollLeft document.body.scrollTop </code></pre> <p>And are there any others? Once I know where the window is I can set an event chain that will slowly call <code>window.scrollBy(x,y);</code> until it reaches my desired point.</p>
<p>The method jQuery (v1.10) uses to find this is:</p> <pre><code>var doc = document.documentElement; var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); </code></pre> <p>That is:</p> <ul> <li>It tests for <code>window.pageXOffset</code> first and uses that if it exists.</li> <li>Otherwise, it uses <code>document.documentElement.scrollLeft</code>.</li> <li>It then subtracts <code>document.documentElement.clientLeft</code> if it exists.</li> </ul> <p>The subtraction of <code>document.documentElement.clientLeft</code> / <code>Top</code> only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.</p>
{ "question_id": 3464876, "question_date": "2010-08-12T05:03:28.990Z", "question_score": 232, "tags": "javascript", "answer_id": 3464890, "answer_date": "2010-08-12T05:09:33.140Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: How do I retrieve the number of columns in a Pandas data frame? <p>How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like:</p> <pre><code>df.num_columns </code></pre>
<p>Like so:</p> <pre><code>import pandas as pd df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]}) len(df.columns) 3 </code></pre>
{ "question_id": 20297332, "question_date": "2013-11-30T06:28:21.307Z", "question_score": 232, "tags": "python|pandas|dataframe", "answer_id": 20297639, "answer_date": "2013-11-30T07:11:45.840Z", "answer_score": 387 }
Please answer the following Stack Overflow question: Title: Write to UTF-8 file in Python <p>I'm really confused with the <code>codecs.open function</code>. When I do:</p> <pre><code>file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It gives me the error</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)</p> </blockquote> <p>If I do:</p> <pre><code>file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It works fine.</p> <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p> <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>
<p>I believe the problem is that <a href="https://docs.python.org/library/codecs.html#codecs.BOM_UTF8" rel="noreferrer"><code>codecs.BOM_UTF8</code></a> is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"</p> <p>Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:</p> <pre><code>import codecs file = codecs.open("lol", "w", "utf-8") file.write(u'\ufeff') file.close() </code></pre> <p>(That seems to give the right answer - a file with bytes EF BB BF.)</p> <p>EDIT: S. Lott's <a href="https://stackoverflow.com/a/934203/12892">suggestion</a> of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.</p>
{ "question_id": 934160, "question_date": "2009-06-01T09:42:23.530Z", "question_score": 232, "tags": "python|utf-8|character-encoding|byte-order-mark", "answer_id": 934173, "answer_date": "2009-06-01T09:46:58.933Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions <p>I am building a website specifically for mobile devices. There is one page in particular which is best viewed in landscape mode. </p> <p>Is there a way to detect if the user visiting that page is viewing it in Portrait mode and if so, display a message informing the user that the page is best viewed in landscape mode? If the user is already viewing it in landscape mode then no message will appear.</p> <p>So basically, I want the site to detect the viewport orientation, if orientation is <strong>Portrait</strong>, then display an alert message advising the user that this page is best viewed in <strong>Landscape</strong> mode.</p>
<pre><code>if(window.innerHeight &gt; window.innerWidth){ alert(&quot;Please use Landscape!&quot;); } </code></pre> <p>jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - <a href="http://jquerymobile.com/demos/1.0a2/#docs/api/events.html" rel="noreferrer"><code>orientationchange</code></a></p> <p>Also, after some googling, check out <code>window.orientation</code> (which is I believe measured in degrees...)</p> <p><strong>EDIT</strong>: On mobile devices, if you open a keyboard then the above may fail, so can use <code>screen.availHeight</code> and <code>screen.availWidth</code>, which gives proper height and width even after the keyboard is opened.</p> <pre class="lang-JS prettyprint-override"><code>if(screen.availHeight &gt; screen.availWidth){ alert(&quot;Please use Landscape!&quot;); } </code></pre>
{ "question_id": 4917664, "question_date": "2011-02-07T02:29:08.170Z", "question_score": 232, "tags": "javascript|jquery|mobile|viewport|device-orientation", "answer_id": 4917796, "answer_date": "2011-02-07T03:10:50.863Z", "answer_score": 323 }
Please answer the following Stack Overflow question: Title: Add icon to submit button in twitter bootstrap 2 <p>I want to use the twitter bootstrap icons on my form input submit buttons. </p> <p>The examples on <a href="http://twitter.github.com/bootstrap/base-css.html#icons" rel="noreferrer">http://twitter.github.com/bootstrap/base-css.html#icons</a> mainly show styled hyperlinks. </p> <p>The closest I've come is getting the icon displayed next to the button, but not inside.</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="input-prepend"&gt; &lt;span class="add-on"&gt;&lt;i class="icon-user icon-white"&gt;&lt;/i&gt;&lt;/span&gt; &lt;input type="submit" class="btn-primary" value="Login" &gt; &lt;/div&gt; </code></pre>
<p>You can use a button tag instead of input</p> <pre class="lang-html prettyprint-override"><code>&lt;button type="submit" class="btn btn-primary"&gt; &lt;i class="icon-user icon-white"&gt;&lt;/i&gt; Sign in &lt;/button&gt; </code></pre>
{ "question_id": 9376192, "question_date": "2012-02-21T10:47:26.203Z", "question_score": 232, "tags": "twitter-bootstrap|twitter-bootstrap-2", "answer_id": 9393978, "answer_date": "2012-02-22T11:33:46.343Z", "answer_score": 409 }
Please answer the following Stack Overflow question: Title: My docker container has no internet <p>I had it working allright but now it stopped. I tried the following commands with no avail:</p> <p><code>docker run -dns 8.8.8.8 base ping google.com</code></p> <p><code>docker run base ping google.com</code></p> <p><code>sysctl -w net.ipv4.ip_forward=1</code> - both on the host and on the container</p> <p>All I get is <code>unknown host google.com</code>. Docker version 0.7.0</p> <p>Any ideas?</p> <p>P.S. <code>ufw</code> disabled as well</p>
<p>Fixed by following this advice:</p> <blockquote> <p>[...] can you try to reset everything?</p> </blockquote> <pre><code>pkill docker iptables -t nat -F ifconfig docker0 down brctl delbr docker0 docker -d </code></pre> <blockquote> <p>It will force docker to recreate the bridge and reinit all the network rules</p> </blockquote> <p><a href="https://github.com/dotcloud/docker/issues/866#issuecomment-19218300" rel="noreferrer">https://github.com/dotcloud/docker/issues/866#issuecomment-19218300</a></p> <p>Seems the interface was 'hung' somehow.</p> <p><strong>Update for more recent versions of docker:</strong></p> <p>The above answer might still get the job done for you but it has been quite a long time since this answer was posted and docker is more polished now so make sure you try these first before going into mangling with <code>iptables</code> and all.</p> <p><code>sudo service docker restart</code> or (if you are in a linux distro that does not use upstart) <code>sudo systemctl restart docker</code></p>
{ "question_id": 20430371, "question_date": "2013-12-06T17:51:37.230Z", "question_score": 232, "tags": "docker|devops", "answer_id": 20431030, "answer_date": "2013-12-06T18:27:09.713Z", "answer_score": 146 }