input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to tell if UIViewController's view is visible <p>I have a tab bar application, with many views. Is there a way to know if a particular <code>UIViewController</code> is currently visible from within the <code>UIViewController</code>? (looking for a property)</p>
<p>The view's <a href="https://developer.apple.com/documentation/uikit/uiview/1622456-window" rel="noreferrer">window property</a> is non-nil if a view is currently visible, so check the main view in the view controller:</p> <p><em>Invoking the <a href="https://developer.apple.com/documentation/uikit/uiviewcontroller/1621460-view" rel="noreferrer">view</a> method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded. I've added the call to isViewLoaded to avoid this problem.</em></p> <pre><code>if (viewController.isViewLoaded &amp;&amp; viewController.view.window) { // viewController is visible } </code></pre> <p>Since iOS9 it has became easier:</p> <pre><code>if viewController.viewIfLoaded?.window != nil { // viewController is visible } </code></pre> <hr> <p>Or if you have a UINavigationController managing the view controllers, you could check its <a href="https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621862-visibleviewcontroller" rel="noreferrer">visibleViewController</a> property instead.</p>
{ "question_id": 2777438, "question_date": "2010-05-05T23:25:09.953Z", "question_score": 621, "tags": "ios|uiview|uiviewcontroller|uiwindow", "answer_id": 2777460, "answer_date": "2010-05-05T23:35:31.987Z", "answer_score": 1184 }
Please answer the following Stack Overflow question: Title: Unstage a deleted file in git <p>Usually, to discard changes to a file you would do:</p> <pre><code>git checkout -- &lt;file&gt; </code></pre> <p>What if the change I want to discard is deleting the file? The above line would give an error:</p> <pre><code>error: pathspec '&lt;file&gt;' did not match any file(s) known to git. </code></pre> <p>What command will restore that single file without undoing other changes?</p> <p><strong>bonus point:</strong> Also, what if the change I want to discard is <em>adding</em> a file? I would like to know how to unstage that change as well.</p>
<p>Assuming you're wanting to undo the effects of <code>git rm &lt;file&gt;</code> or <code>rm &lt;file&gt;</code> followed by <code>git add -A</code> or something similar:</p> <pre><code># this restores the file status in the index git reset -- &lt;file&gt; # then check out a copy from the index git checkout -- &lt;file&gt; </code></pre> <p>To undo <code>git add &lt;file&gt;</code>, the first line above suffices, assuming you haven't committed yet.</p>
{ "question_id": 9591407, "question_date": "2012-03-06T20:33:42.410Z", "question_score": 621, "tags": "git|git-checkout", "answer_id": 9591612, "answer_date": "2012-03-06T20:46:25.653Z", "answer_score": 969 }
Please answer the following Stack Overflow question: Title: What REALLY happens when you don't free after malloc before program termination? <p>We are all taught that you MUST free every pointer that is allocated. I'm a bit curious, though, about the real cost of not freeing memory. In some obvious cases, like when <code>malloc()</code> is called inside a loop or part of a thread execution, it's very important to free so there are no memory leaks. But consider the following two examples:</p> <p>First, if I have code that's something like this:</p> <pre><code>int main() { char *a = malloc(1024); /* Do some arbitrary stuff with 'a' (no alloc functions) */ return 0; } </code></pre> <p>What's the real result here? My thinking is that the process dies and then the heap space is gone anyway so there's no harm in missing the call to <code>free</code> (however, I do recognize the importance of having it anyway for closure, maintainability, and good practice). Am I right in this thinking?</p> <p>Second, let's say I have a program that acts a bit like a shell. Users can declare variables like <code>aaa = 123</code> and those are stored in some dynamic data structure for later use. Clearly, it seems obvious that you'd use some solution that will calls some *alloc function (hashmap, linked list, something like that). For this kind of program, it doesn't make sense to ever free after calling <code>malloc</code> because these variables must be present at all times during the program's execution and there's no good way (that I can see) to implement this with statically allocated space. Is it bad design to have a bunch of memory that's allocated but only freed as part of the process ending? If so, what's the alternative?</p>
<p>Just about every modern operating system will recover all the allocated memory space after a program exits. The only exception I can think of might be something like Palm OS where the program's static storage and runtime memory are pretty much the same thing, so not freeing might cause the program to take up more storage. (I'm only speculating here.)</p> <p>So generally, there's no harm in it, except the runtime cost of having more storage than you need. Certainly in the example you give, you want to keep the memory for a variable that might be used until it's cleared.</p> <p>However, it's considered good style to free memory as soon as you don't need it any more, and to free anything you still have around on program exit. It's more of an exercise in knowing what memory you're using, and thinking about whether you still need it. If you don't keep track, you might have memory leaks.</p> <p>On the other hand, the similar admonition to close your files on exit has a much more concrete result - if you don't, the data you wrote to them might not get flushed, or if they're a temp file, they might not get deleted when you're done. Also, database handles should have their transactions committed and then closed when you're done with them. Similarly, if you're using an object oriented language like C++ or Objective C, not freeing an object when you're done with it will mean the destructor will never get called, and any resources the class is responsible might not get cleaned up.</p>
{ "question_id": 654754, "question_date": "2009-03-17T15:29:09.207Z", "question_score": 621, "tags": "c|malloc|free", "answer_id": 654766, "answer_date": "2009-03-17T15:32:32.927Z", "answer_score": 431 }
Please answer the following Stack Overflow question: Title: What is the explicit promise construction antipattern and how do I avoid it? <p>I was writing code that does something that looks like:</p> <pre><code>function getStuffDone(param) { | function getStuffDone(param) { var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) { // or = new $.Deferred() etc. | // using a promise constructor myPromiseFn(param+1) | myPromiseFn(param+1) .then(function(val) { /* or .done */ | .then(function(val) { d.resolve(val); | resolve(val); }).catch(function(err) { /* .fail */ | }).catch(function(err) { d.reject(err); | reject(err); }); | }); return d.promise; /* or promise() */ | }); } | } </code></pre> <p>Someone told me this is called the "<strong>deferred antipattern</strong>" or the "<strong><code>Promise</code> constructor antipattern</strong>" respectively, what's bad about this code and why is this called an <a href="https://en.wikipedia.org/wiki/Anti-pattern" rel="noreferrer">antipattern</a>?</p>
<p>The <a href="https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern" rel="noreferrer">deferred antipattern (now explicit-construction anti-pattern)</a> coined by <a href="https://stackoverflow.com/users/995876/esailija">Esailija</a> is a common anti-pattern people who are new to promises make, I've made it myself when I first used promises. The problem with the above code is that is fails to utilize the fact that promises chain.</p> <p>Promises can chain with <code>.then</code> and you can return promises directly. Your code in <code>getStuffDone</code> can be rewritten as:</p> <pre><code>function getStuffDone(param){ return myPromiseFn(param+1); // much nicer, right? } </code></pre> <p>Promises are all about making asynchronous code more readable and behave like synchronous code without hiding that fact. Promises represent an abstraction over a value of one time operation, they abstract the notion of a statement or expression in a programming language.</p> <p>You should only use deferred objects when you are <a href="https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises">converting an API to promises</a> and can't do it automatically, or when you're writing aggregation functions that are easier expressed this way. </p> <p>Quoting Esailija:</p> <blockquote> <p>This is the most common anti-pattern. It is easy to fall into this when you don't really understand promises and think of them as glorified event emitters or callback utility. Let's recap: promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel.</p> </blockquote>
{ "question_id": 23803743, "question_date": "2014-05-22T10:07:00.857Z", "question_score": 621, "tags": "javascript|promise|q|bluebird|es6-promise", "answer_id": 23803744, "answer_date": "2014-05-22T10:07:00.857Z", "answer_score": 426 }
Please answer the following Stack Overflow question: Title: What are the best use cases for Akka framework <p>I have heard lots of raving about <a href="http://akka.io/" rel="noreferrer">Akka</a> framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.</p> <p>Only one limitation: please do not include case of writing a chat server. (why? since this has been overused as an example for lots of similar things)</p>
<p>I have used it so far in two real projects very successfully. both are in the near real-time traffic information field (traffic as in cars on highways), distributed over several nodes, integrating messages between several parties, reliable backend systems. I'm not at liberty to give specifics on clients yet, when I do get the OK maybe it can be added as a reference. </p> <p>Akka has really pulled through on those projects, even though we started when it was on version 0.7. (we are using scala by the way)</p> <p>One of the big advantages is the ease at which you can compose a system out of actors and messages with almost no boilerplating, it scales extremely well without all the complexities of hand-rolled threading and you get asynchronous message passing between objects almost for free.</p> <p>It is very good in modeling any type of asynchronous message handling. I would prefer to write any type of (web) services system in this style than any other style. (Have you ever tried to write an asynchronous web service (server side) with JAX-WS? that's a lot of plumbing). So I would say any system that does not want to hang on one of its components because everything is implicitly called using synchronous methods, and that one component is locking on something. It is very stable and the let-it-crash + supervisor solution to failure really works well. Everything is easy to setup programmatically and not hard to unit test.</p> <p>Then there are the excellent add-on modules. The Camel module really plugs in well into Akka and enables such easy development of asynchronous services with configurable endpoints. </p> <p>I'm very happy with the framework and it is becoming a defacto standard for the connected systems that we build.</p>
{ "question_id": 4493001, "question_date": "2010-12-20T19:15:54.403Z", "question_score": 620, "tags": "java|scala|asynchronous|akka", "answer_id": 4494522, "answer_date": "2010-12-20T22:17:33.810Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: if else in a list comprehension <p>Given a list <code>xs</code>:</p> <pre><code>xs = [22, 13, 45, 50, 98, 69, 43, 44, 1] </code></pre> <p>For numbers above 45 inclusive, add 1; and for numbers less than 45, add 5.</p>
<pre><code>&gt;&gt;&gt; xs = [22, 13, 45, 50, 98, 69, 43, 44, 1] &gt;&gt;&gt; [x+1 if x &gt;= 45 else x+5 for x in xs] [27, 18, 46, 51, 99, 70, 48, 49, 6] </code></pre> <p>Do-something if <code>&lt;condition&gt;</code>, else do-something else.</p>
{ "question_id": 4406389, "question_date": "2010-12-10T06:45:51.960Z", "question_score": 619, "tags": "python|list|list-comprehension|if-statement", "answer_id": 4406399, "answer_date": "2010-12-10T06:48:13.097Z", "answer_score": 724 }
Please answer the following Stack Overflow question: Title: MySQL string replace <p>I have a column containing urls (id, url):</p> <pre><code>http://www.example.com/articles/updates/43 http://www.example.com/articles/updates/866 http://www.example.com/articles/updates/323 http://www.example.com/articles/updates/seo-url http://www.example.com/articles/updates/4?something=test </code></pre> <p>I'd like to change the word "updates" to "news". Is it possible to do this with a script?</p>
<pre><code>UPDATE your_table SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/') WHERE your_field LIKE '%articles/updates/%' </code></pre> <p>Now rows that were like </p> <p><code>http://www.example.com/articles/updates/43</code> </p> <p>will be </p> <p><code>http://www.example.com/articles/news/43</code></p> <p><a href="http://www.electrictoolbox.com/mysql-find-replace-text/" rel="noreferrer">http://www.electrictoolbox.com/mysql-find-replace-text/</a></p>
{ "question_id": 5956993, "question_date": "2011-05-10T21:58:03.040Z", "question_score": 619, "tags": "mysql|replace", "answer_id": 14586441, "answer_date": "2013-01-29T15:31:09.300Z", "answer_score": 1415 }
Please answer the following Stack Overflow question: Title: How do I get an apk file from an Android device? <p>How do I get the apk file from an android device? Or how do I transfer the apk file from device to system?</p>
<p>Use <a href="http://developer.android.com/guide/developing/tools/adb.html" rel="noreferrer">adb</a>. With <em>adb pull </em> you can copy files from your device to your system, when the device is attached with USB.</p> <p>Of course you also need the right permissions to access the directory your file is in. If not, you will need to root the device first.</p> <hr /> <p>If you find that many of the APKs are named &quot;base.apk&quot; you can also use this one line command to pull all the APKs off a phone you can access while renaming any &quot;base.apk&quot; names to the package name. This also fixes the directory not found issue for APK paths with seemingly random characters after the name:</p> <pre class="lang-sh prettyprint-override"><code>for i in $(adb shell pm list packages | awk -F':' '{print $2}'); do adb pull &quot;$(adb shell pm path $i | awk -F':' '{print $2}')&quot; mv base.apk $i.apk &amp;&gt; /dev/null done </code></pre> <p>If you get &quot;adb: error: failed to stat remote object&quot; that indicates you don't have the needed permissions. I ran this on a NON-rooted Moto Z2 and was able to download ALL the APKs I did not uninstall (see below) except youtube.</p> <pre class="lang-bash prettyprint-override"><code>adb shell pm uninstall --user 0 com.android.cellbroadcastreceiver &lt;--- kills presidential alert app! </code></pre> <p>(to view users run adb shell pm list users) This is a way to remove/uninstall (not from the phone as it comes back with factory reset) almost <em>ANY</em> app WITHOUT root INCLUDING system apps (hint the annoying update app that updates your phone line it or not can be found by grepping for &quot;ccc&quot;)</p>
{ "question_id": 4032960, "question_date": "2010-10-27T12:06:20.340Z", "question_score": 619, "tags": "android|adb|apk", "answer_id": 4033005, "answer_date": "2010-10-27T12:12:09.970Z", "answer_score": 166 }
Please answer the following Stack Overflow question: Title: How to draw checkbox or tick mark in GitHub Markdown table? <p>I am able to draw checkbox in Github README.md lists using</p> <pre><code>- [ ] (for unchecked checkbox) - [x] (for checked checkbox) </code></pre> <p>But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?</p>
<p>Try adding a <code>-</code> before the <code>[]</code> or <code>[x]</code>. That's an <code>-</code> followed by a blank space <code></code>.</p> <p>Below is an example from Github blog.</p> <pre><code>### Solar System Exploration, 1950s – 1960s - [ ] Mercury - [x] Venus - [x] Earth (Orbit/Moon) - [x] Mars - [ ] Jupiter - [ ] Saturn - [ ] Uranus - [ ] Neptune - [ ] Comet Haley </code></pre> <p>It appears like below:</p> <p><a href="https://i.stack.imgur.com/GOySK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GOySK.png" alt="Resultant Image"></a></p> <p>Here's how one could do the same in a table:</p> <pre><code>| Task | Time required | Assigned to | Current Status | Finished | |----------------|---------------|---------------|----------------|-----------| | Calendar Cache | &gt; 5 hours | | in progress | - [x] ok? | Object Cache | &gt; 5 hours | | in progress | [x] item1&lt;br/&gt;[ ] item2 | Object Cache | &gt; 5 hours | | in progress | &lt;ul&gt;&lt;li&gt;- [x] item1&lt;/li&gt;&lt;li&gt;- [ ] item2&lt;/li&gt;&lt;/ul&gt; | Object Cache | &gt; 5 hours | | in progress | &lt;ul&gt;&lt;li&gt;[x] item1&lt;/li&gt;&lt;li&gt;[ ] item2&lt;/li&gt;&lt;/ul&gt; - [x] works - [x] works too </code></pre> <p>Here's how it looks:</p> <p><a href="https://i.stack.imgur.com/aWZ2t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aWZ2t.png" alt="enter image description here"></a></p>
{ "question_id": 47344571, "question_date": "2017-11-17T06:30:16.020Z", "question_score": 619, "tags": "github|markdown|github-flavored-markdown", "answer_id": 47344640, "answer_date": "2017-11-17T06:35:29.257Z", "answer_score": 840 }
Please answer the following Stack Overflow question: Title: Difference between abstract class and interface in Python <p>What is the difference between abstract class and interface in Python?</p>
<p>What you'll see sometimes is the following:</p> <pre class="lang-py prettyprint-override"><code>class Abstract1: &quot;&quot;&quot;Some description that tells you it's abstract, often listing the methods you're expected to supply.&quot;&quot;&quot; def aMethod(self): raise NotImplementedError(&quot;Should have implemented this&quot;) </code></pre> <p>Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.</p> <p>And the difference between abstract and interface is a hairsplitting thing when you have duck typing.</p> <p>Java uses interfaces because it doesn't have multiple inheritance.</p> <p>Because Python has multiple inheritance, you may also see something like this</p> <pre class="lang-py prettyprint-override"><code>class SomeAbstraction: pass # lots of stuff - but missing something class Mixin1: def something(self): pass # one implementation class Mixin2: def something(self): pass # another class Concrete1(SomeAbstraction, Mixin1): pass class Concrete2(SomeAbstraction, Mixin2): pass </code></pre> <p>This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.</p>
{ "question_id": 372042, "question_date": "2008-12-16T17:32:27.833Z", "question_score": 619, "tags": "python|interface|abstract-class", "answer_id": 372121, "answer_date": "2008-12-16T17:59:23.253Z", "answer_score": 665 }
Please answer the following Stack Overflow question: Title: How many files can I put in a directory? <p>Does it matter how many files I keep in a single directory? If so, how many files in a directory is too many, and what are the impacts of having too many files? (This is on a Linux server.)</p> <p>Background: I have a photo album website, and every image uploaded is renamed to an 8-hex-digit id (say, a58f375c.jpg). This is to avoid filename conflicts (if lots of "IMG0001.JPG" files are uploaded, for example). The original filename and any useful metadata is stored in a database. Right now, I have somewhere around 1500 files in the images directory. This makes listing the files in the directory (through FTP or SSH client) take a few seconds. But I can't see that it has any effect other than that. In particular, there doesn't seem to be any impact on how quickly an image file is served to the user.</p> <p>I've thought about reducing the number of images by making 16 subdirectories: 0-9 and a-f. Then I'd move the images into the subdirectories based on what the first hex digit of the filename was. But I'm not sure that there's any reason to do so except for the occasional listing of the directory through FTP/SSH.</p>
<h1><a href="http://en.wikipedia.org/wiki/File_Allocation_Table#FAT32" rel="noreferrer">FAT32</a>:</h1> <ul> <li>Maximum number of files: 268,173,300</li> <li>Maximum number of files per directory: 2<sup>16</sup>&nbsp;-&nbsp;1 (65,535)</li> <li>Maximum file size: 2&nbsp;GiB&nbsp;-&nbsp;1 without <a href="http://en.wikipedia.org/wiki/Large_file_support" rel="noreferrer">LFS</a>, 4&nbsp;GiB&nbsp;-&nbsp;1 with </li> </ul> <h1><a href="http://en.wikipedia.org/wiki/NTFS" rel="noreferrer">NTFS</a>:</h1> <ul> <li>Maximum number of files: 2<sup>32</sup>&nbsp;-&nbsp;1 (4,294,967,295) </li> <li>Maximum file size <ul> <li>Implementation: 2<sup>44</sup>&nbsp;-&nbsp;2<sup>6</sup> bytes (16&nbsp;TiB&nbsp;-&nbsp;64&nbsp;KiB)</li> <li>Theoretical: 2<sup>64</sup>&nbsp;-&nbsp;2<sup>6</sup> bytes (16&nbsp;EiB&nbsp;-&nbsp;64&nbsp;KiB)</li> </ul></li> <li>Maximum volume size <ul> <li>Implementation: 2<sup>32</sup>&nbsp;-&nbsp;1&nbsp;clusters (256&nbsp;TiB&nbsp;-&nbsp;64&nbsp;KiB)</li> <li>Theoretical: 2<sup>64</sup>&nbsp;-&nbsp;1&nbsp;clusters&nbsp;(1&nbsp;YiB&nbsp;-&nbsp;64 KiB)</li> </ul></li> </ul> <h1><a href="http://en.wikipedia.org/wiki/Ext2" rel="noreferrer">ext2</a>:</h1> <ul> <li>Maximum number of files: 10<sup>18</sup></li> <li>Maximum number of files per directory: ~1.3&nbsp;&times;&nbsp;10<sup>20</sup> (performance issues past 10,000)</li> <li>Maximum file size <ul> <li>16&nbsp;GiB (block size of 1&nbsp;KiB)</li> <li>256&nbsp;GiB (block size of 2&nbsp;KiB)</li> <li>2&nbsp;TiB (block size of 4&nbsp;KiB)</li> <li>2&nbsp;TiB (block size of 8&nbsp;KiB)</li> </ul></li> <li>Maximum volume size <ul> <li>4&nbsp;TiB (block size of 1&nbsp;KiB)</li> <li>8&nbsp;TiB (block size of 2&nbsp;KiB)</li> <li>16&nbsp;TiB (block size of 4&nbsp;KiB)</li> <li>32&nbsp;TiB (block size of 8&nbsp;KiB)</li> </ul></li> </ul> <h1><a href="http://en.wikipedia.org/wiki/Ext3" rel="noreferrer">ext3</a>:</h1> <ul> <li>Maximum number of files: min(volumeSize&nbsp;/&nbsp;2<sup>13</sup>,&nbsp;numberOfBlocks) </li> <li>Maximum file size: <em>same as ext2</em></li> <li>Maximum volume size: <em>same as ext2</em></li> </ul> <h1><a href="http://en.wikipedia.org/wiki/Ext4" rel="noreferrer">ext4</a>:</h1> <ul> <li>Maximum number of files: 2<sup>32</sup>&nbsp;-&nbsp;1 (4,294,967,295)</li> <li>Maximum number of files per directory: unlimited</li> <li>Maximum file size: 2<sup>44</sup>&nbsp;-&nbsp;1&nbsp;bytes (16&nbsp;TiB&nbsp;-&nbsp;1)</li> <li>Maximum volume size: 2<sup>48</sup>&nbsp;-&nbsp;1&nbsp;bytes (256&nbsp;TiB&nbsp;-&nbsp;1)</li> </ul>
{ "question_id": 466521, "question_date": "2009-01-21T18:58:25.733Z", "question_score": 619, "tags": "filesystems|limit", "answer_id": 466596, "answer_date": "2009-01-21T19:16:51Z", "answer_score": 821 }
Please answer the following Stack Overflow question: Title: Location Services not working in iOS 8 <p>My app that worked fine on iOS&nbsp;7 doesn't work with the iOS&nbsp;8 SDK.</p> <p><code>CLLocationManager</code> doesn't return a location, and I don't see my app under <em>Settings</em> -> <em>Location Services</em> either. I did a Google search on the issue, but nothing came up. What could be wrong?</p>
<p>I ended up solving my own problem.</p> <p>Apparently in iOS 8 SDK, <code>requestAlwaysAuthorization</code> (for background location) or <code>requestWhenInUseAuthorization</code> (location only when foreground) call on <code>CLLocationManager</code> is needed before starting location updates.</p> <p>There also needs to be <code>NSLocationAlwaysUsageDescription</code> or <code>NSLocationWhenInUseUsageDescription</code> key in <code>Info.plist</code> with a message to be displayed in the prompt. Adding these solved my problem.</p> <p><a href="https://i.stack.imgur.com/iuOzB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/iuOzB.jpg" alt="enter image description here" /></a></p> <p>For more extensive information, have a look at: <a href="http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/" rel="noreferrer">Core-Location-Manager-Changes-in-ios-8</a></p>
{ "question_id": 24062509, "question_date": "2014-06-05T14:12:06.167Z", "question_score": 619, "tags": "objective-c|ios8|location|cllocationmanager", "answer_id": 24063578, "answer_date": "2014-06-05T14:58:19.103Z", "answer_score": 1095 }
Please answer the following Stack Overflow question: Title: How can I add a file to the last commit in Git? <p>Sometimes after I did a commit, I found out that I left out a file which should also be included in the commit, but was actually not. I often committed again:</p> <pre><code>git add the_left_out_file git commit &quot;include the file which should be added in the last commit&quot; </code></pre> <p>I think it might not be a good idea to do so. I want to just include the file without adding a commit. Something like this,</p> <pre><code>git add the_left_out_file git add_staged_files_to_previous_commit </code></pre> <p>Is it possible?</p>
<p>Yes, there's a command, <code>git commit --amend</code>, which is used to &quot;fix&quot; the last commit.</p> <p>In your case, it would be called as:</p> <pre><code>git add the_left_out_file git commit --amend --no-edit </code></pre> <p>The <em>--no-edit</em> flag allows to make an amendment to the commit without changing the commit message.</p> <p><strong>Warning</strong></p> <p>You should never amend public commits that you already pushed to a public repository, because amend is actually removing the last commit from the history and creating a new commit with the combined changes from that commit and new added when amending.</p>
{ "question_id": 40503417, "question_date": "2016-11-09T09:19:03.383Z", "question_score": 619, "tags": "git", "answer_id": 40503483, "answer_date": "2016-11-09T09:22:46.387Z", "answer_score": 1209 }
Please answer the following Stack Overflow question: Title: How can I indent multiple lines in Xcode? <p>When I select multiple lines of code and want to indent them as usual with <kbd>TAB</kbd> key, it just deletes them all. I come from Eclipse where I always did it that way. How's that done in Xcode? I hope not line by line ;)</p>
<p>The keyboard shortcuts are <kbd>⌘</kbd>+<kbd>]</kbd> for indent and <kbd>⌘</kbd>+<kbd>[</kbd> for un-indent. </p> <ul> <li>In Xcode's preferences window, click the Key Bindings toolbar button. The Key Bindings section is where you customize keyboard shortcuts.</li> </ul>
{ "question_id": 829954, "question_date": "2009-05-06T14:43:30.837Z", "question_score": 619, "tags": "xcode|code-formatting", "answer_id": 829980, "answer_date": "2009-05-06T14:47:51.077Z", "answer_score": 936 }
Please answer the following Stack Overflow question: Title: Sending multipart/formdata with jQuery.ajax <p>I've got a problem sending a file to a serverside PHP-script using jQuery's ajax-function. It's possible to get the File-List with <code>$('#fileinput').attr('files')</code> but how is it possible to send this Data to the server? The resulting array (<code>$_POST</code>) on the serverside php-script is 0 (<code>NULL</code>) when using the file-input.</p> <p>I know it is possible (though I didn't find any jQuery solutions until now, only Prototye code (<a href="http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html">http://webreflection.blogspot.com/2009/03/safari-4-multiple-upload-with-progress.html</a>)).</p> <p>This seems to be relatively new, so please do not mention file upload would be impossible via XHR/Ajax, because it's definitely working.</p> <p>I need the functionality in Safari 5, FF and Chrome would be nice but are not essential.</p> <p>My code for now is:</p> <pre><code>$.ajax({ url: 'php/upload.php', data: $('#file').attr('files'), cache: false, contentType: 'multipart/form-data', processData: false, type: 'POST', success: function(data){ alert(data); } }); </code></pre>
<p>Starting with Safari 5/Firefox 4, it’s easiest to use the <code>FormData</code> class:</p> <pre><code>var data = new FormData(); jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file-'+i, file); }); </code></pre> <p>So now you have a <code>FormData</code> object, ready to be sent along with the XMLHttpRequest.</p> <pre><code>jQuery.ajax({ url: 'php/upload.php', data: data, cache: false, contentType: false, processData: false, method: 'POST', type: 'POST', // For jQuery &lt; 1.9 success: function(data){ alert(data); } }); </code></pre> <p>It’s imperative that you set the <code>contentType</code> option to <code>false</code>, forcing jQuery not to add a <code>Content-Type</code> header for you, otherwise, the boundary string will be missing from it. Also, you must leave the <code>processData</code> flag set to false, otherwise, jQuery will try to convert your <code>FormData</code> into a string, which will fail.</p> <p>You may now retrieve the file in PHP using:</p> <pre><code>$_FILES['file-0'] </code></pre> <p>(There is only one file, <code>file-0</code>, unless you specified the <code>multiple</code> attribute on your file input, in which case, the numbers will increment with each file.)</p> <p><strong>Using the <a href="https://github.com/francois2metz/html5-formdata" rel="noreferrer">FormData emulation</a> for older browsers</strong></p> <pre><code>var opts = { url: 'php/upload.php', data: data, cache: false, contentType: false, processData: false, method: 'POST', type: 'POST', // For jQuery &lt; 1.9 success: function(data){ alert(data); } }; if(data.fake) { // Make sure no text encoding stuff is done by xhr opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; } opts.contentType = "multipart/form-data; boundary="+data.boundary; opts.data = data.toString(); } jQuery.ajax(opts); </code></pre> <p><strong>Create FormData from an existing form</strong></p> <p>Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:</p> <pre><code>var data = new FormData(jQuery('form')[0]); </code></pre> <p><strong>Use a PHP native array instead of a counter</strong></p> <p>Just name your file elements the same and end the name in brackets:</p> <pre><code>jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file[]', file); }); </code></pre> <p><code>$_FILES['file']</code> will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.</p>
{ "question_id": 5392344, "question_date": "2011-03-22T13:52:36.660Z", "question_score": 618, "tags": "jquery|ajax|file-upload|multipartform-data|form-data", "answer_id": 5976031, "answer_date": "2011-05-12T09:36:09.957Z", "answer_score": 945 }
Please answer the following Stack Overflow question: Title: How to capture cURL output to a file? <p>I have a text document that contains a bunch of URLs in this format:</p> <pre><code>URL = &quot;sitehere.com&quot; </code></pre> <p>What I'm looking to do is to run <code>curl -K myfile.txt</code>, and get the output of the response cURL returns, into a file.</p> <p>How can I do this?</p>
<pre><code>curl -K myconfig.txt -o output.txt </code></pre> <p>Writes the <em>first</em> output received in the file you specify (overwrites if an old one exists).</p> <pre><code>curl -K myconfig.txt &gt;&gt; output.txt </code></pre> <p>Appends all output you receive to the specified file.</p> <p><strong>Note: The -K is optional.</strong> </p>
{ "question_id": 13735051, "question_date": "2012-12-06T00:32:33.937Z", "question_score": 618, "tags": "batch-file|curl", "answer_id": 13735150, "answer_date": "2012-12-06T00:44:02.523Z", "answer_score": 871 }
Please answer the following Stack Overflow question: Title: access key and value of object using *ngFor <p>I am a bit confused about how to get the <code>key</code> and <code>value</code> of an object in angular2 while using <code>*ngFor</code> for iterating over the object. I know in angular 1.x there is a syntax like </p> <pre class="lang-html prettyprint-override"><code>ng-repeat="(key, value) in demo" </code></pre> <p>but I don't know how to do the same in angular2. I have tried something similar, without success:</p> <pre class="lang-html prettyprint-override"><code> &lt;ul&gt; &lt;li *ngFor='#key of demo'&gt;{{key}}&lt;/li&gt; &lt;/ul&gt; demo = { 'key1': [{'key11':'value11'}, {'key12':'value12'}], 'key2': [{'key21':'value21'}, {'key22':'value22'}], } </code></pre> <p>Here is a plnkr with my attempt: <a href="http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview" rel="noreferrer">http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview</a></p> <p>How can I get <code>key1</code> and <code>key2</code> dynamically using <code>*ngFor</code>? After searching extensively, I found the idea of using pipes but I don't know how to go about it. Is there any inbuilt pipe for doing the same in angular2?</p>
<p>As in <strong>latest release of Angular (v6.1.0)</strong> , Angular Team has added new built in pipe for the same named as <code>keyvalue</code> pipe to help you iterate through objects, maps, and arrays, in the <code>common</code> module of angular package. For example -</p> <pre class="lang-html prettyprint-override"><code>&lt;div *ngFor=&quot;let item of testObject | keyvalue&quot;&gt; Key: &lt;b&gt;{{item.key}}&lt;/b&gt; and Value: &lt;b&gt;{{item.value}}&lt;/b&gt; &lt;/div&gt; </code></pre> <p>To keep original order, use <code>keyvalue:onCompare</code>,<br /> and in component define callback:</p> <pre><code>// ... import {KeyValue} from '@angular/common'; @Component(/* ... */) export class MyComponent { private onCompare(_left: KeyValue&lt;any, any&gt;, _right: KeyValue&lt;any, any&gt;): number { return -1; } } </code></pre> <h1><a href="https://stackblitz.com/edit/angular6-keyvaluepipe-demo?file=src%2Fapp%2Fapp.component.ts" rel="noreferrer">Working Forked Example</a></h1> <p>check it out here for more useful information -</p> <ul> <li><a href="https://github.com/angular/angular/blob/master/CHANGELOG.md#features-3" rel="noreferrer">https://github.com/angular/angular/blob/master/CHANGELOG.md#features-3</a></li> <li><a href="https://github.com/angular/angular/commit/2b49bf7" rel="noreferrer">https://github.com/angular/angular/commit/2b49bf7</a></li> </ul> <p>If you are using Angular v5 or below or you want to achieve using pipe follow this answer</p> <ul> <li><a href="https://stackoverflow.com/a/35536052/5043867">access key and value of object using ngfor</a></li> </ul>
{ "question_id": 35534959, "question_date": "2016-02-21T10:28:24.517Z", "question_score": 618, "tags": "angular|typescript|object", "answer_id": 51491848, "answer_date": "2018-07-24T06:28:43.673Z", "answer_score": 736 }
Please answer the following Stack Overflow question: Title: How to install a gem or update RubyGems if it fails with a permissions error <p>I'm trying to install a gem using <code>gem install mygem</code> or update RubyGems using <code>gem update --system</code>, and it fails with this error:</p> <pre class="lang-none prettyprint-override"><code>ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory. </code></pre> <p>Does anyone have an idea how to solve this?</p>
<blockquote> <p>You don't have write permissions into the /Library/Ruby/Gems/1.8 directory.</p> </blockquote> <p>means exactly that, you don't have permission to write there.</p> <p>That is the version of Ruby installed by Apple, for their own use. While it's OK to make minor modifications to that <em>if you know what you're doing</em>, because you are not sure about the permissions problem, I'd say it's not a good idea to continue along that track.</p> <p>Instead, I'll strongly suggest you look into using either <a href="https://github.com/sstephenson/rbenv/" rel="noreferrer">rbenv</a> or <a href="https://rvm.io/rvm/install/" rel="noreferrer">RVM</a> to manage a separate Ruby, installed into a sandbox in your home directory, that you can modify/fold/spindle/change without worrying about messing up the system Ruby.</p> <p>Between the two, I use rbenv, though I used RVM a lot in the past. rbenv takes a more "hands-off" approach to managing your Ruby installation. RVM has a lot of features and is very powerful, but, as a result is more intrusive. In either case, <em>READ</em> the installation documentation for them a couple times before starting to install whichever you pick.</p>
{ "question_id": 14607193, "question_date": "2013-01-30T15:10:14.503Z", "question_score": 618, "tags": "ruby|macos|rubygems", "answer_id": 14607772, "answer_date": "2013-01-30T15:36:52.900Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: npm install vs. update - what's the difference? <p>What is the practical difference between <code>npm install</code> and <code>npm update</code>? When should I use which?</p>
<p>The difference between <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">npm install</a> and <a href="https://docs.npmjs.com/cli/update" rel="noreferrer">npm update</a> handling of package versions specified in <strong>package.json</strong>:</p> <pre><code>{ "name": "my-project", "version": "1.0", // install update "dependencies": { // ------------------ "already-installed-versionless-module": "*", // ignores "1.0" -&gt; "1.1" "already-installed-semver-module": "^1.4.3" // ignores "1.4.3" -&gt; "1.5.2" "already-installed-versioned-module": "3.4.1" // ignores ignores "not-yet-installed-versionless-module": "*", // installs installs "not-yet-installed-semver-module": "^4.2.1" // installs installs "not-yet-installed-versioned-module": "2.7.8" // installs installs } } </code></pre> <p><strong>Summary</strong>: The only big difference is that <strong>an already installed module with fuzzy versioning</strong> ...</p> <ul> <li>gets ignored by <code>npm install</code></li> <li>gets updated by <code>npm update</code></li> </ul> <p><strong>Additionally</strong>: <code>install</code> and <code>update</code> by default handle devDependencies differently</p> <ul> <li><code>npm install</code> will <strong>install/update</strong> devDependencies unless <code>--production</code> flag is added</li> <li><code>npm update</code> will <strong>ignore</strong> devDependencies unless <code>--dev</code> flag is added</li> </ul> <hr> <p><strong>Why use <code>npm install</code> at all?</strong></p> <p>Because <code>npm install</code> does more when you look besides handling your dependencies in <code>package.json</code>. As you can see in <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">npm install</a> you can ...</p> <ul> <li>manually install node-modules</li> <li>set them as <em>global</em> (which puts them in the shell's <code>PATH</code>) using <code>npm install -g &lt;name&gt;</code></li> <li>install certain versions described by git tags</li> <li>install from a git url</li> <li>force a reinstall with <code>--force</code></li> </ul>
{ "question_id": 12478679, "question_date": "2012-09-18T14:07:54.633Z", "question_score": 618, "tags": "node.js|npm", "answer_id": 19824154, "answer_date": "2013-11-06T22:26:10.017Z", "answer_score": 754 }
Please answer the following Stack Overflow question: Title: What is the difference between Normalize.css and Reset CSS? <p>I know what CSS Reset is, but recently I heard about this new thing called Normalize.css</p> <p>What is the difference between the <a href="https://necolas.github.io/normalize.css/" rel="noreferrer">Normalize.css</a> and <a href="http://meyerweb.com/eric/tools/css/reset/" rel="noreferrer">Reset CSS</a>?</p> <p>What is the difference between normalizing CSS and resetting CSS?</p> <p>Is it just a new buzz word for the CSS Reset?</p>
<p>I work on normalize.css.</p> <p>The main differences are:</p> <ol> <li><p><strong>Normalize.css preserves useful defaults rather than "unstyling" everything.</strong> For example, elements like <code>sup</code> or <code>sub</code> "just work" after including normalize.css (and are actually made more robust) whereas they are visually indistinguishable from normal text after including reset.css. So, normalize.css does not impose a visual starting point (homogeny) upon you. This may not be to everyone's taste. The best thing to do is experiment with both and see which gels with your preferences.</p></li> <li><p><strong>Normalize.css corrects some common bugs that are out of scope for reset.css.</strong> It has a wider scope than reset.css, and also provides bug fixes for common problems like: display settings for HTML5 elements, the lack of <code>font</code> inheritance by form elements, correcting <code>font-size</code> rendering for <code>pre</code>, SVG overflow in IE9, and the <code>button</code> styling bug in iOS.</p></li> <li><p><strong>Normalize.css doesn't clutter your dev tools.</strong> A common irritation when using reset.css is the large inheritance chain that is displayed in browser CSS debugging tools. This is not such an issue with normalize.css because of the targeted stylings.</p></li> <li><p><strong>Normalize.css is more modular.</strong> The project is broken down into relatively independent sections, making it easy for you to potentially remove sections (like the form normalizations) if you know they will never be needed by your website.</p></li> <li><p><strong>Normalize.css has better documentation.</strong> The normalize.css code is documented inline as well as more comprehensively in the <a href="https://github.com/necolas/normalize.css/wiki">GitHub Wiki</a>. This means you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests. The project aims to help educate people on how browsers render elements by default, and make it easier for them to be involved in submitting improvements.</p></li> </ol> <p>I've written in greater detail about this in an article <a href="http://nicolasgallagher.com/about-normalize-css/">about normalize.css</a></p>
{ "question_id": 6887336, "question_date": "2011-07-31T03:17:53.080Z", "question_score": 618, "tags": "css|normalize-css", "answer_id": 8357635, "answer_date": "2011-12-02T14:13:47.610Z", "answer_score": 848 }
Please answer the following Stack Overflow question: Title: How to remove RVM (Ruby Version Manager) from my system <p>How can I remove RVM (Ruby Version Manager) from my system?</p>
<p>There's a simple command built-in that will pull it:</p> <pre><code>rvm implode </code></pre> <p>This will remove the <code>rvm/</code> directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too, if you installed that:</p> <pre><code>gem uninstall rvm </code></pre> <p>There may be elements left over from a Homebrew, Apt or DNF install of it that require removal as well. This depends on how you installed it in the first place. That clean-up step is optional, as RVM will no longer be involved in Ruby, but can help keep things organized.</p> <p>If you've made modifications to your <code>PATH</code> you might want to pull those, too. Check your <code>.bashrc</code>, <code>.profile</code> and <code>.bash_profile</code> files, among other things.</p> <p>You may also have an <code>/etc/rvmrc</code> file, or one in your home directory <code>~/.rvmrc</code> that may need to be removed as well.</p>
{ "question_id": 3558656, "question_date": "2010-08-24T16:26:32.893Z", "question_score": 618, "tags": "ruby|rubygems|rvm", "answer_id": 3558763, "answer_date": "2010-08-24T16:38:42.120Z", "answer_score": 998 }
Please answer the following Stack Overflow question: Title: Xcode Product -> Archive disabled <p>I have been archiving for ad hoc distribution fine for many months and suddenly today I cannot do so as the Archive menu item is disabled. I have not changed anything. I went through the provisioning setup for the project and it looks ok.</p> <p>My Ad Hoc profile is about to expire in 14 days. Could this be the problem? I don't believe I can renew it until the day it expires. There is a a "renew" button for my ad hoc profile in the organizer but when I click it I get... </p> <blockquote> <p>The given profile was not found on the provisioning portal. Please refresh your provisioning profiles before attempting to renew “MyAddHocProfile”</p> </blockquote> <p>The profile in the provisioning portal shows active, expiring on the 30th. I noticed that I had not yet upgraded to 4.6.2 and did so. Then I downloaded my profile and double cliked it thinking that would refresh the profile in Xcode, still no joy. I also tried manually replacing the profile file MyAddHocProfile.mobileprovision in the Library.</p> <p>What do they mean "refresh your provisioning profile"?</p> <p>Even so, I would think that as long as the profile is active, I should be able to create an archive. I must be doing something else wrong.</p>
<p>You've changed your scheme destination to a simulator instead of <strong>Generic iOS Device</strong>.</p> <p>That's why it is greyed out.</p> <p><img src="https://i.stack.imgur.com/bvn1f.png" alt="Change from a simulator to Generic iOS Device"></p>
{ "question_id": 16050640, "question_date": "2013-04-17T02:53:52.540Z", "question_score": 618, "tags": "xcode|provisioning|ad-hoc-distribution", "answer_id": 18791703, "answer_date": "2013-09-13T17:09:57.890Z", "answer_score": 1710 }
Please answer the following Stack Overflow question: Title: Can the Android layout folder contain subfolders? <p>Right now, I'm storing every XML layout file inside the 'res/layout' folder, so it is feasible and simple to manage small projects, but when there is a case of large and heavy projects, then there should be a hierarchy and sub-folders needed inside the layout folder.</p> <p>for e.g.</p> <pre><code>layout -- layout_personal -- personal_detail.xml -- personal_other.xml --layout_address -- address1.xml -- address2.xml </code></pre> <p>Like the same way, we would like to have sub-folders for the large application, so is there any way to do so inside the Android project?</p> <p>I am able to create layout-personal and layout_address sub-folders inside the layout folder, but when the time comes to access the XML layout file using R.layout._______ , at that time there is no any XML layout pop-up inside the menu.</p>
<p>You CAN do this with gradle. I've made a <a href="https://github.com/eskimoapps/ResourceNestingExample" rel="noreferrer">demo project</a> showing how.</p> <p>The trick is to use gradle's ability to <a href="http://tools.android.com/tech-docs/new-build-system/resource-merging" rel="noreferrer">merge multiple resource folders</a>, and set the res folder as well as the nested subfolders in the sourceSets block. </p> <p>The quirk is that you can't declare a container resource folder before you declare that folder's child resource folders.</p> <p>Below is the sourceSets block from the build.gradle file from the demo. Notice that the subfolders are declared first.</p> <pre><code>sourceSets { main { res.srcDirs = [ 'src/main/res/layouts/layouts_category2', 'src/main/res/layouts', 'src/main/res' ] } } </code></pre> <p><img src="https://i.stack.imgur.com/yzj01.png" alt="nested resources picture"></p> <p>Also, the direct parent of your actual resource files (pngs, xml layouts, etc..) does still need to correspond with the <a href="https://developer.android.com/guide/topics/resources/providing-resources.html" rel="noreferrer">specification</a>.</p>
{ "question_id": 4930398, "question_date": "2011-02-08T06:58:08.037Z", "question_score": 618, "tags": "android|xml|android-layout|gradle|build.gradle", "answer_id": 22426467, "answer_date": "2014-03-15T16:26:22.677Z", "answer_score": 519 }
Please answer the following Stack Overflow question: Title: How can I create a "Please Wait, Loading..." animation using jQuery? <p>I would like to place a "please wait, loading" spinning circle animation on my site. How should I accomplish this using jQuery?</p>
<p>You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.</p> <h3>The Setup</h3> <p>Let's start by getting us a nice "loading" animation from <a href="http://ajaxload.info" rel="noreferrer">http://ajaxload.info</a> I'll be using <img src="https://i.stack.imgur.com/FhHRx.gif" alt="enter image description here"> </p> <p>Let's create an element that we can show/hide anytime we're making an ajax request:</p> <pre><code>&lt;div class="modal"&gt;&lt;!-- Place at bottom of page --&gt;&lt;/div&gt; </code></pre> <h3>The CSS</h3> <p>Next let's give it some flair:</p> <pre><code>/* Start by setting display:none to make this hidden. Then we position it in relation to the viewport window with position:fixed. Width, height, top and left speak for themselves. Background we set to 80% white with our animation centered, and no-repeating */ .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .8 ) url('http://i.stack.imgur.com/FhHRx.gif') 50% 50% no-repeat; } /* When the body has the loading class, we turn the scrollbar off with overflow:hidden */ body.loading .modal { overflow: hidden; } /* Anytime the body has the loading class, our modal element will be visible */ body.loading .modal { display: block; } </code></pre> <h3>And finally, the jQuery</h3> <p>Alright, on to the jQuery. This next part is actually really simple:</p> <pre><code>$body = $("body"); $(document).on({ ajaxStart: function() { $body.addClass("loading"); }, ajaxStop: function() { $body.removeClass("loading"); } }); </code></pre> <p>That's it! We're attaching some events to the body element anytime the <code>ajaxStart</code> or <code>ajaxStop</code> events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.</p> <p>See it in action: <a href="http://jsfiddle.net/VpDUG/4952/" rel="noreferrer">http://jsfiddle.net/VpDUG/4952/</a></p>
{ "question_id": 1964839, "question_date": "2009-12-27T01:10:29.457Z", "question_score": 617, "tags": "jquery|animation", "answer_id": 1964871, "answer_date": "2009-12-27T01:23:57.527Z", "answer_score": 1283 }
Please answer the following Stack Overflow question: Title: How do I declare a 2d array in C++ using new? <p>How do i declare a 2d array using new?</p> <p>Like, for a "normal" array I would:</p> <pre><code>int* ary = new int[Size] </code></pre> <p>but</p> <pre><code>int** ary = new int[sizeY][sizeX] </code></pre> <p>a) doesn't work/compile and b) doesn't accomplish what:</p> <pre><code>int ary[sizeY][sizeX] </code></pre> <p>does.</p>
<p>If your row length is a compile time constant, C++11 allows</p> <pre><code>auto arr2d = new int [nrows][CONSTANT]; </code></pre> <p>See <a href="https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new/16239446#16239446">this answer</a>. Compilers like gcc that allow variable-length arrays as an extension to C++ can use <code>new</code> <a href="https://stackoverflow.com/a/8837664/224132">as shown here</a> to get fully runtime-variable array dimension functionality like C99 allows, but portable ISO C++ is limited to only the first dimension being variable.</p> <p>Another efficient option is to do the 2d indexing manually into a big 1d array, as <a href="https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new/28841507#28841507">another answer shows</a>, allowing the same compiler optimizations as a real 2D array (e.g. proving or checking that arrays don't alias each other / overlap).</p> <hr /> <p>Otherwise, you can use an array of <em>pointers to arrays</em> to allow 2D syntax like contiguous 2D arrays, even though it's not an efficient single large allocation. You can initialize it using a loop, like this:</p> <pre><code>int** a = new int*[rowCount]; for(int i = 0; i &lt; rowCount; ++i) a[i] = new int[colCount]; </code></pre> <p>The above, for <code>colCount= 5</code> and <code>rowCount = 4</code>, would produce the following:</p> <p><img src="https://i.stack.imgur.com/M75kn.png" alt="enter image description here" /></p> <p>Don't forget to <code>delete</code> each row separately with a loop, before deleting the array of pointers. Example in <a href="https://stackoverflow.com/a/936709/224132">another answer</a>.</p>
{ "question_id": 936687, "question_date": "2009-06-01T20:42:20.013Z", "question_score": 617, "tags": "c++|arrays|multidimensional-array|dynamic-allocation", "answer_id": 936702, "answer_date": "2009-06-01T20:45:15.920Z", "answer_score": 865 }
Please answer the following Stack Overflow question: Title: How do I split a string, breaking at a particular character? <p>I have this string</p> <pre><code>'john smith~123 Street~Apt 4~New York~NY~12345' </code></pre> <p>Using JavaScript, what is the fastest way to parse this into</p> <pre><code>var name = "john smith"; var street= "123 Street"; //etc... </code></pre>
<p>With JavaScript’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="noreferrer"><code>String.prototype.split</code></a> function:</p> <pre><code>var input = 'john smith~123 Street~Apt 4~New York~NY~12345'; var fields = input.split('~'); var name = fields[0]; var street = fields[1]; // etc. </code></pre>
{ "question_id": 96428, "question_date": "2008-09-18T20:14:13.643Z", "question_score": 617, "tags": "javascript|string-split", "answer_id": 96452, "answer_date": "2008-09-18T20:17:59.233Z", "answer_score": 966 }
Please answer the following Stack Overflow question: Title: Is there a command to refresh environment variables from the command prompt in Windows? <p>If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?</p>
<p>You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.</p> <p>Create a file named <code>resetvars.vbs</code> containing this code, and save it on the path:</p> <pre class="lang-vb prettyprint-override"><code>Set oShell = WScript.CreateObject("WScript.Shell") filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat") Set objFileSystem = CreateObject("Scripting.fileSystemObject") Set oFile = objFileSystem.CreateTextFile(filename, TRUE) set oEnv=oShell.Environment("System") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next path = oEnv("PATH") set oEnv=oShell.Environment("User") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next path = path &amp; ";" &amp; oEnv("PATH") oFile.WriteLine("SET PATH=" &amp; path) oFile.Close </code></pre> <p>create another file name resetvars.bat containing this code, same location:</p> <pre class="lang-vb prettyprint-override"><code>@echo off %~dp0resetvars.vbs call "%TEMP%\resetvars.bat" </code></pre> <p>When you want to refresh the environment variables, just run <code>resetvars.bat</code></p> <hr> <p><em>Apologetics</em>:</p> <p>The two main problems I had coming up with this solution were</p> <p><strong>a.</strong> I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and </p> <p><strong>b.</strong> the PATH environment variable is a concatenation of the user and the system PATH variables.</p> <p>I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.</p> <p>I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.</p> <p><strong>Note</strong>: this script does not delete variables.</p> <p>This can probably be improved.</p> <p><strong>ADDED</strong></p> <p>If you need to export the environment from one cmd window to another, use this script (let's call it <code>exportvars.vbs</code>):</p> <pre class="lang-vb prettyprint-override"><code>Set oShell = WScript.CreateObject("WScript.Shell") filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat") Set objFileSystem = CreateObject("Scripting.fileSystemObject") Set oFile = objFileSystem.CreateTextFile(filename, TRUE) set oEnv=oShell.Environment("Process") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next oFile.Close </code></pre> <p>Run <code>exportvars.vbs</code> in the window you want to export <strong>from</strong>, then switch to the window you want to export <strong>to</strong>, and type:</p> <pre class="lang-vb prettyprint-override"><code>"%TEMP%\resetvars.bat" </code></pre>
{ "question_id": 171588, "question_date": "2008-10-05T06:49:38.407Z", "question_score": 617, "tags": "windows|cmd|environment-variables", "answer_id": 171737, "answer_date": "2008-10-05T09:10:28.247Z", "answer_score": 150 }
Please answer the following Stack Overflow question: Title: What issues should be considered when overriding equals and hashCode in Java? <p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>
<h3>The theory (for the language lawyers and the mathematically inclined):</h3> <p><code>equals()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)" rel="noreferrer">javadoc</a>) must define an equivalence relation (it must be <em>reflexive</em>, <em>symmetric</em>, and <em>transitive</em>). In addition, it must be <em>consistent</em> (if the objects are not modified, then it must keep returning the same value). Furthermore, <code>o.equals(null)</code> must always return false.</p> <p><code>hashCode()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()" rel="noreferrer">javadoc</a>) must also be <em>consistent</em> (if the object is not modified in terms of <code>equals()</code>, it must keep returning the same value).</p> <p>The <strong>relation</strong> between the two methods is:</p> <blockquote> <p><em>Whenever <code>a.equals(b)</code>, then <code>a.hashCode()</code> must be same as <code>b.hashCode()</code>.</em></p> </blockquote> <h3>In practice:</h3> <p>If you override one, then you should override the other.</p> <p>Use the same set of fields that you use to compute <code>equals()</code> to compute <code>hashCode()</code>.</p> <p>Use the excellent helper classes <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html" rel="noreferrer">EqualsBuilder</a> and <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html" rel="noreferrer">HashCodeBuilder</a> from the <a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a> library. An example:</p> <pre><code>public class Person { private String name; private int age; // ... @Override public int hashCode() { return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers // if deriving: appendSuper(super.hashCode()). append(name). append(age). toHashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Person)) return false; if (obj == this) return true; Person rhs = (Person) obj; return new EqualsBuilder(). // if deriving: appendSuper(super.equals(obj)). append(name, rhs.name). append(age, rhs.age). isEquals(); } } </code></pre> <h3>Also remember:</h3> <p>When using a hash-based <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html" rel="noreferrer">Collection</a> or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html" rel="noreferrer">Map</a> such as <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html" rel="noreferrer">HashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html" rel="noreferrer">LinkedHashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html" rel="noreferrer">Hashtable</a>, or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html" rel="noreferrer">WeakHashMap</a>, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="noreferrer">which has also other benefits</a>.</p>
{ "question_id": 27581, "question_date": "2008-08-26T08:50:26.223Z", "question_score": 617, "tags": "java|overriding|equals|hashcode", "answer_id": 27609, "answer_date": "2008-08-26T09:12:42.910Z", "answer_score": 1469 }
Please answer the following Stack Overflow question: Title: Type List vs type ArrayList in Java <pre><code>(1) List&lt;?&gt; myList = new ArrayList&lt;?&gt;(); (2) ArrayList&lt;?&gt; myList = new ArrayList&lt;?&gt;(); </code></pre> <p>I understand that with (1), implementations of the <strong>List</strong> interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this). </p> <p>I am wondering if anyone uses (2)? </p> <p>Also, how often (and can I please get an example) does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside <strong><em>coding to interfaces</em></strong> and <strong><em>best practices</em></strong> etc.)</p>
<p>Almost always <code>List</code> is preferred over <code>ArrayList</code> because, for instance, <code>List</code> can be translated into a <a href="http://java.sun.com/javase/7/docs/api/java/util/LinkedList.html" rel="noreferrer"><code>LinkedList</code></a> without affecting the rest of the codebase.</p> <p>If one used <code>ArrayList</code> instead of <code>List</code>, it's hard to change the <code>ArrayList</code> implementation into a <code>LinkedList</code> one because <code>ArrayList</code> specific methods have been used in the codebase that would also require restructuring.</p> <p>You can read about the <code>List</code> implementations <a href="http://java.sun.com/docs/books/tutorial/collections/implementations/list.html" rel="noreferrer">here</a>.</p> <p>You may start with an <code>ArrayList</code>, but soon after discover that another implementation is the more appropriate choice.</p>
{ "question_id": 2279030, "question_date": "2010-02-17T07:40:13.490Z", "question_score": 617, "tags": "java|list|interface|decoupling", "answer_id": 2279059, "answer_date": "2010-02-17T07:46:11.893Z", "answer_score": 493 }
Please answer the following Stack Overflow question: Title: JavaScript variable number of arguments to function <p>Is there a way to allow "unlimited" vars for a function in JavaScript?</p> <p>Example:</p> <pre><code>load(var1, var2, var3, var4, var5, etc...) load(var1) </code></pre>
<p>Sure, just use the <code>arguments</code> object.</p> <pre><code>function foo() { for (var i = 0; i &lt; arguments.length; i++) { console.log(arguments[i]); } } </code></pre>
{ "question_id": 2141520, "question_date": "2010-01-26T18:06:29.600Z", "question_score": 617, "tags": "javascript|function|arguments|argument-passing", "answer_id": 2141530, "answer_date": "2010-01-26T18:08:04.823Z", "answer_score": 907 }
Please answer the following Stack Overflow question: Title: gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0] <p>I followed few articles over the <a href="https://coderwall.com/p/euwpig/a-better-git-log" rel="noreferrer">pretty</a> attributes on <a href="https://github.com/blog/2242-git-2-10-has-been-released" rel="noreferrer">Git 2.10</a> release note. Going through which upgraded the git to 2.10.0 and made changes to global <code>.gitconfig</code> resulting as follows - </p> <pre><code>[filter "lfs"] clean = git-lfs clean %f smudge = git-lfs smudge %f required = true [user] name = xyz email = [email protected] signingkey = AAAAAAA [core] excludesfile = /Users/xyz/.gitignore_global editor = 'subl' --wait [difftool "sourcetree"] cmd = opendiff \"$LOCAL\" \"$REMOTE\" path = [mergetool "sourcetree"] cmd = /Applications/SourceTree.app/Contents/Resources/opendiff-w.sh \"$LOCAL\" \"$REMOTE\" -ancestor \"$BASE\" -merge \"$MERGED\" trustExitCode = true [alias] lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)&lt;%an&gt;%Creset' --abbrev-commit --date=relative [color "diff"] old = red strike new = green italic </code></pre> <p>But now that I try to sign my commits using </p> <pre><code>git commit -a -S -m "message" </code></pre> <p>I get to see the following error - </p> <blockquote> <p>You need a passphrase to unlock the secret key for </p> <p>user: "XYZ (Digitally Signed) " </p> <p>2048-bit RSA key, ID AAAAAAAA, created 2016-07-01</p> <p>error: gpg failed to sign the data fatal: failed to write commit object</p> </blockquote> <p><strong><em>Note</em></strong> - I can still commit changes using <code>git commit -a -m "message"</code></p> <p><strong><em>Is there a way to overcome the same? Or any change required in <code>gpg</code> configs to get along with the upgradation of git?</em></strong></p> <hr> <p><strong><em>Update 1</em></strong></p> <p>Also seeking further usefulness, following <a href="https://stackoverflow.com/questions/10161198/is-there-a-way-to-autosign-commits-in-git-with-a-gpg-key">Is there a way to &quot;autosign&quot; commits in Git with a GPG key?</a>. I've already configured the key using </p> <pre><code>git config --global user.signingkey ED5CDE14(with my key) git config --global commit.gpgsign true </code></pre> <p>and quite obviously getting the same error anyway.</p>
<p>I ran into this issue with OSX.</p> <h3>Original answer:</h3> <p>It seems like a gpg update (of brew) changed to location of <code>gpg</code> to <code>gpg1</code>, you can change the binary where git looks up the gpg:</p> <pre><code>git config --global gpg.program gpg1 </code></pre> <p>If you don't have gpg1: <code>brew install gpg1</code>.</p> <h3>Updated answer:</h3> <p>It looks like gpg1 is being deprecated/<a href="https://github.com/Homebrew/brew/issues/708#issuecomment-239625115" rel="noreferrer">&quot;gently nudged out of usage&quot;</a>, so you probably should actually update to gpg2, unfortunately this involves quite a few more steps/a bit of time:</p> <pre><code>brew upgrade gnupg # This has a make step which takes a while brew link --overwrite gnupg brew install pinentry-mac </code></pre> <p>on old homebrew:</p> <pre><code>echo &quot;pinentry-program /usr/local/bin/pinentry-mac&quot; &gt;&gt; ~/.gnupg/gpg-agent.conf killall gpg-agent </code></pre> <p>On more recent systems like M1 macs:</p> <pre><code>echo &quot;pinentry-program /opt/homebrew/bin/pinentry-mac&quot; &gt;&gt; ~/.gnupg/gpg-agent.conf killall gpg-agent </code></pre> <p>The first part installs gpg2, and latter is <a href="https://github.com/Homebrew/homebrew-core/issues/14737#issuecomment-309547412" rel="noreferrer">a hack required to use it</a>. For troubleshooting, see <a href="https://stackoverflow.com/a/41054093/1240268">this answer</a> (though that is about linux not brew), it suggests a good test:</p> <pre><code>echo &quot;test&quot; | gpg --clearsign # on linux it's gpg2 but brew stays as gpg </code></pre> <p>If this test is successful (no error/output includes PGP signature), you have successfully updated to the latest gpg version.</p> <p>You should now be able to use git signing again!<br /> It's worth noting you'll need to have:</p> <pre><code>git config --global gpg.program gpg # perhaps you had this already? On linux maybe gpg2 git config --global commit.gpgsign true # if you want to sign every commit </code></pre> <p>Note: After you've run a signed commit, you can verify it signed with:</p> <pre><code>git log --show-signature -1 </code></pre> <p>which will include gpg info for the last commit.</p>
{ "question_id": 39494631, "question_date": "2016-09-14T15:42:05.390Z", "question_score": 617, "tags": "git|github|gpg-signature", "answer_id": 40066889, "answer_date": "2016-10-16T04:37:56.053Z", "answer_score": 840 }
Please answer the following Stack Overflow question: Title: Accessing nested JavaScript objects and arrays by string path <p>I have a data structure like this :</p> <pre><code>var someObject = { 'part1' : { 'name': 'Part 1', 'size': '20', 'qty' : '50' }, 'part2' : { 'name': 'Part 2', 'size': '15', 'qty' : '60' }, 'part3' : [ { 'name': 'Part 3A', 'size': '10', 'qty' : '20' }, { 'name': 'Part 3B', 'size': '5', 'qty' : '20' }, { 'name': 'Part 3C', 'size': '7.5', 'qty' : '20' } ] }; </code></pre> <p>And I would like to access the data using these variable :</p> <pre><code>var part1name = "part1.name"; var part2quantity = "part2.qty"; var part3name1 = "part3[0].name"; </code></pre> <p>part1name should be filled with <code>someObject.part1.name</code> 's value, which is "Part 1". Same thing with part2quantity which filled with 60.</p> <p>Is there anyway to achieve this with either pure javascript or JQuery?</p>
<p>I just made this based on some similar code I already had, it appears to work:</p> <pre><code>Object.byString = function(o, s) { s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties s = s.replace(/^\./, ''); // strip a leading dot var a = s.split('.'); for (var i = 0, n = a.length; i &lt; n; ++i) { var k = a[i]; if (k in o) { o = o[k]; } else { return; } } return o; } </code></pre> <p>Usage::</p> <pre><code>Object.byString(someObj, 'part3[0].name'); </code></pre> <p>See a working demo at <a href="http://jsfiddle.net/alnitak/hEsys/">http://jsfiddle.net/alnitak/hEsys/</a></p> <p><strong>EDIT</strong> some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a <code>try / catch</code> block when calling, rather than having this function silently return <code>undefined</code> for an invalid index.</p>
{ "question_id": 6491463, "question_date": "2011-06-27T10:25:02.653Z", "question_score": 617, "tags": "javascript|path|nested", "answer_id": 6491621, "answer_date": "2011-06-27T10:40:10.823Z", "answer_score": 650 }
Please answer the following Stack Overflow question: Title: About "*.d.ts" in TypeScript <p>I am curious about <code>.d.ts</code> declaration files because I am new to the TypeScript programming language. I was told by someone that <code>.d.ts</code> files are are similar to <code>.h</code> header files in the C &amp; C++ programming languages, however, the <code>.d.ts</code> files don't seem to work quite the same. Currently, I am failing to understand how to properly use the .d.ts files. It would appear that I cant add my <code>.js</code> or <code>.ts</code> files to the <code>.d.ts</code> files, so the only way my project will work is if it contains all three file types. That seems like a lot of files. To help me better understand how the .d.ts files are related to JavaScript &amp; TypeScript, I have some questions I would like to ask.</p> <hr /> <ol> <li><p>What is the relationship between the three files? the relationship between them?</p> </li> <li><p>How can I use the <code>*.d.ts</code> file? Does it mean I can delete the <code>*.ts</code> file permanently?</p> </li> <li><p>If so, how can the <code>*.d.ts</code> file know which JS file is mapping to itself?</p> </li> </ol> <hr /> <p>It would be very nice if someone can give me an example.</p>
<p>The &quot;d.ts&quot; file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.</p> <p>Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.</p> <p>This works thanks to TypeScript's constraint of not letting you add the &quot;.ts&quot; extension at the end of the <code>import</code> statement. Because of that, when you reference some file, let's say, <code>my-module.js</code>, if there is a <code>my-module.d.ts</code> next to it, then TypeScript will include its content:</p> <pre class="lang-yaml prettyprint-override"><code>src/ my-module.js my-module.d.ts index.ts </code></pre> <p><sub><i>my-module.js</i></sub></p> <pre class="lang-js prettyprint-override"><code>const thing = 42; module.exports = { thing }; </code></pre> <p><sub><i>my-module.d.ts</i></sub></p> <pre><code>export declare const thing: number; </code></pre> <p><sub><i>index.ts</i></sub></p> <pre><code>import { thing } from &quot;./my-module&quot;; // &lt;- no extension // runtime implementation of `thing` is taken from &quot;.js&quot; console.log(thing); // 42 // type declaration of `thing` is taken from &quot;.d.ts&quot; type TypeOfThing = typeof thing; // number </code></pre>
{ "question_id": 21247278, "question_date": "2014-01-21T01:05:15.707Z", "question_score": 617, "tags": "typescript|.d.ts", "answer_id": 21247316, "answer_date": "2014-01-21T01:10:31.293Z", "answer_score": 738 }
Please answer the following Stack Overflow question: Title: JWT (JSON Web Token) automatic prolongation of expiration <p>I would like to implement JWT-based authentication to our new REST API. But since the expiration is set in the token, is it possible to automatically prolong it? I don't want users to need to sign in after every X minutes if they were actively using the application in that period. That would be a huge UX fail.</p> <p>But prolonging the expiration creates a new token (and the old one is still valid until it expires). And generating a new token after each request sounds silly to me. Sounds like a security issue when more than one token is valid at the same time. Of course I could invalidate the old used one using a blacklist but I would need to store the tokens. And one of the benefits of JWT is no storage.</p> <p>I found how Auth0 solved it. They use not only JWT token but also a refresh token: <a href="https://auth0.com/docs/tokens/refresh-tokens" rel="noreferrer">https://auth0.com/docs/tokens/refresh-tokens</a></p> <p>But again, to implement this (without Auth0) I'd need to store refresh tokens and maintain their expiration. What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?</p> <p>Are there other options? Is using JWT not suited for this scenario?</p>
<p>I work at Auth0 and I was involved in the design of the refresh token feature.</p> <p>It all depends on the type of application and here is our recommended approach.</p> <h3>Web applications</h3> <p>A good pattern is to refresh the token before it expires.</p> <p>Set the token expiration to one week and refresh the token every time the user opens the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.</p> <p>To refresh the token, your API needs a new endpoint that receives a valid, not expired JWT and returns the same signed JWT with the new expiration field. Then the web application will store the token somewhere.</p> <h3>Mobile/Native applications</h3> <p>Most native applications do login once and only once.</p> <p>The idea is that the refresh token never expires and it can be exchanged always for a valid JWT.</p> <p>The problem with a token that never expires is that <strong>never</strong> means never. What do you do if you lose your phone? So, it needs to be identifiable by the user somehow and the application needs to provide a way to revoke access. We decided to use the device's name, e.g. &quot;maryo's iPad&quot;. Then the user can go to the application and revoke access to &quot;maryo's iPad&quot;.</p> <p>Another approach is to revoke the refresh token on specific events. An interesting event is changing the password.</p> <p>We believe that JWT is not useful for these use cases, so we use a random generated string and we store it on our side.</p>
{ "question_id": 26739167, "question_date": "2014-11-04T15:41:22.550Z", "question_score": 617, "tags": "security|authentication|jwt", "answer_id": 26834685, "answer_date": "2014-11-09T23:45:30.803Z", "answer_score": 707 }
Please answer the following Stack Overflow question: Title: How to debug JavaScript / jQuery event bindings with Firebug or similar tools? <p>I need to debug a web application that uses jQuery to do some fairly complex and messy <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="noreferrer">DOM</a> manipulation. At one point, some of the events that were bound to particular elements, are not fired and simply stop working.</p> <p>If I had a capability to edit the application source, I would drill down and add a bunch of <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> <code>console.log()</code> statements and comment/uncomment pieces of code to try to pinpoint the problem. But let's assume I cannot edit the application code and need to work entirely in Firefox using Firebug or similar tools.</p> <p>Firebug is very good at letting me navigate and manipulate the DOM. So far, though, I have not been able to figure out how to do event debugging with Firebug. Specifically, I just want to see a list of event handlers bound to a particular element at a given time (using Firebug JavaScript breakpoints to trace the changes). But either Firebug does not have the capability to see bound events, or I'm too dumb to find it. :-)</p> <p>Any recommendations or ideas? Ideally, I would just like to see and edit events bound to elements, similarly to how I can edit DOM today.</p>
<p>See <a href="https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node/447106#447106">How to find event listeners on a DOM node</a>.</p> <p>In a nutshell, assuming at some point an event handler is attached to your element (eg): <code>$('#foo').click(function() { console.log('clicked!') });</code></p> <p>You inspect it like so:</p> <ul> <li><p>jQuery 1.3.x</p> <pre><code>var clickEvents = $('#foo').data("events").click; jQuery.each(clickEvents, function(key, value) { console.log(value) // prints "function() { console.log('clicked!') }" }) </code></pre></li> <li><p>jQuery 1.4.x</p> <pre><code>var clickEvents = $('#foo').data("events").click; jQuery.each(clickEvents, function(key, handlerObj) { console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }" }) </code></pre></li> </ul> <p>See <a href="http://docs.jquery.com/Core/data#name" rel="noreferrer"><code>jQuery.fn.data</code></a> (where jQuery stores your handler internally).</p> <ul> <li><p>jQuery 1.8.x</p> <pre><code>var clickEvents = $._data($('#foo')[0], "events").click; jQuery.each(clickEvents, function(key, handlerObj) { console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }" }) </code></pre></li> </ul>
{ "question_id": 570960, "question_date": "2009-02-20T19:42:51.523Z", "question_score": 617, "tags": "javascript|jquery|event-handling|firebug|jquery-events", "answer_id": 571087, "answer_date": "2009-02-20T20:21:09.293Z", "answer_score": 356 }
Please answer the following Stack Overflow question: Title: Update Eclipse with Android development tools v. 23 <p>I updated Eclipse with the new SDK tools (rev. 23), but now when Eclipse starts I receive the error:</p> <blockquote> <p>This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.</p> </blockquote> <p>No updates were found with <strong>"Check for updates"</strong>. If I try <strong>"Install new software"</strong>, I can see version 23, but I can't upgrade due to the following error:</p> <pre><code>Cannot complete the install because of a conflicting dependency. Software being installed: Android Development Tools 23.0.0.1245622 (com.android.ide.eclipse.adt.feature.feature.group 23.0.0.1245622) Software currently installed: Android Developer Tools 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.product 22.2.1.v201309180102-833290) Only one of the following can be installed at once: ADT Package 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.package 22.6.3.v201404151837-1123206) ADT Package 23.0.0.1245622 (com.android.ide.eclipse.adt.package 23.0.0.1245622) Cannot satisfy dependency: From: Android Development Tools 23.0.0.1245622 (com.android.ide.eclipse.adt.feature.feature.group 23.0.0.1245622) To: com.android.ide.eclipse.adt.package [23.0.0.1245622] Cannot satisfy dependency: From: Android Development Tools 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.feature.group 22.6.3.v201404151837-1123206) To: com.android.ide.eclipse.adt.package [22.6.3.v201404151837-1123206] Cannot satisfy dependency: From: ADT Package 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.feature.group 22.2.1.v201309180102-833290) To: com.android.ide.eclipse.adt.feature.group 22.2.0 Cannot satisfy dependency: From: Android Developer Tools 22.2.1.v201309180102-833290 (com.android.ide.eclipse.adt.package.product 22.2.1.v201309180102-833290) To: com.android.ide.eclipse.adt.package.feature.group [22.2.1.v201309180102-833290] </code></pre> <p>After download of the last ADT from the web site, it seems there's another problem.</p> <p>With SDK Tools rev. 23 proguard is not installed, the folder SDK <code>dir/tools/proguard</code> is missing, and other tools are missing. This version contains several bugs.</p>
<p><a href="http://code.google.com/p/android/issues/detail?id=72419" rel="noreferrer">Google response</a>:</p> <p><strong>This is a packaging bug. The entire proguard file is missing. We'll have an update asap, but until then just copy it over from a previous version of the tools:</strong></p> <ul> <li><a href="http://dl.google.com/android/android-sdk_r22.6.2-linux.tgz" rel="noreferrer">http://dl.google.com/android/android-sdk_r22.6.2-linux.tgz</a></li> <li><a href="http://dl.google.com/android/android-sdk_r22.6.2-windows.zip" rel="noreferrer">http://dl.google.com/android/android-sdk_r22.6.2-windows.zip</a></li> <li><a href="http://dl.google.com/android/android-sdk_r22.6.2-macosx.zip" rel="noreferrer">http://dl.google.com/android/android-sdk_r22.6.2-macosx.zip</a></li> </ul> <p>and copy over the following files:</p> <ul> <li>tools/hprof-conv </li> <li>tools/support/annotations.jar </li> <li>tools/proguard</li> </ul> <p>So at the end if you started from a new ADT copy by hand the files :)</p> <p><strong>Edit:</strong> with the latest ADT release, the bundle should now work with auto-update, so <strong>install these new versions</strong>:</p> <ul> <li>linux 64 bit vm: <a href="http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip" rel="noreferrer">http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.zip</a></li> <li>linux 32 bit vm: <a href="http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip" rel="noreferrer">http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zip</a></li> <li>mac: <a href="http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip" rel="noreferrer">http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zip</a></li> <li>win32: <a href="http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip" rel="noreferrer">http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zip</a></li> <li>win64: <a href="http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip" rel="noreferrer">http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zip</a></li> </ul> <p><strong>Don't try to upgrade from previous version</strong> because it doesn’t work at all. If you have got problems with zipalign, it's now under build-tools and no more under tools/ so you can do a symbolic link or just copy it into the expected folder.</p>
{ "question_id": 24437564, "question_date": "2014-06-26T18:21:46.443Z", "question_score": 617, "tags": "java|android|eclipse|adt", "answer_id": 24455640, "answer_date": "2014-06-27T15:35:10.080Z", "answer_score": 115 }
Please answer the following Stack Overflow question: Title: Where does pip install its packages? <p>I activated a <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> which has pip installed. I did</p> <pre class="lang-none prettyprint-override"><code>pip3 install Django==1.8 </code></pre> <p>and Django successfully downloaded. Now, I want to open up the Django folder. Where is the folder located?</p> <p>Normally it would be in &quot;downloads&quot;, but I'm not sure where it would be if I installed it using pip in a virtualenv.</p>
<p><em>pip</em> when used with <em>virtualenv</em> will generally install packages in the path <code>&lt;virtualenv_name&gt;/lib/&lt;python_ver&gt;/site-packages</code>.</p> <p>For example, I created a test virtualenv named <strong>venv_test</strong> with <em>Python</em> 2.7, and the <code>django</code> folder is in <code>venv_test/lib/python2.7/site-packages/django</code>.</p>
{ "question_id": 29980798, "question_date": "2015-05-01T02:25:16.247Z", "question_score": 616, "tags": "python|django|pip|virtualenv", "answer_id": 29980912, "answer_date": "2015-05-01T02:41:07.407Z", "answer_score": 168 }
Please answer the following Stack Overflow question: Title: Comparing two byte arrays in .NET <p>How can I do this fast?</p> <p>Sure I can do this:</p> <pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i=0; i&lt;a1.Length; i++) if (a1[i]!=a2[i]) return false; return true; } </code></pre> <p>But I'm looking for either a <a href="https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library" rel="noreferrer">BCL</a> function or some highly optimized proven way to do this.</p> <pre><code>java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); </code></pre> <p>works nicely, but it doesn't look like that would work for x64.</p> <p>Note my super-fast answer <a href="https://stackoverflow.com/a/8808245/4489">here</a>.</p>
<p>Edit: modern fast way is to use <code>a1.SequenceEquals(a2)</code></p> <p>User <em>gil</em> suggested unsafe code which spawned this solution:</p> <pre><code>// Copyright (c) 2008-2013 Hafthor Stefansson // Distributed under the MIT/X11 software license // Ref: http://www.opensource.org/licenses/mit-license.php. static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) { unchecked { if(a1==a2) return true; if(a1==null || a2==null || a1.Length!=a2.Length) return false; fixed (byte* p1=a1, p2=a2) { byte* x1=p1, x2=p2; int l = a1.Length; for (int i=0; i &lt; l/8; i++, x1+=8, x2+=8) if (*((long*)x1) != *((long*)x2)) return false; if ((l &amp; 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; } if ((l &amp; 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; } if ((l &amp; 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false; return true; } } } </code></pre> <p>which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.</p> <p>It performs about seven timers faster than the simple `for` loop. Using the J# library performed equivalently to the original `for` loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.
{ "question_id": 43289, "question_date": "2008-09-04T07:33:25.387Z", "question_score": 616, "tags": "c#|.net|arrays|performance|j#", "answer_id": 8808245, "answer_date": "2012-01-10T18:11:39.770Z", "answer_score": 85 }
Please answer the following Stack Overflow question: Title: How to avoid using Select in Excel VBA <p>I've heard much about the understandable abhorrence of using <code>.Select</code> in Excel VBA, but I am unsure of how to avoid using it. I am finding that my code would be more re-usable if I were able to use variables instead of <code>Select</code> functions. However, I am not sure how to refer to things (like the <code>ActiveCell</code>, etc.) if not using <code>Select</code>.</p> <p>I have found <a href="http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx" rel="noreferrer">this article on ranges</a> and <a href="http://www.businessprogrammer.com/201105/power-excel-vba-secret-avoid-using-select/" rel="noreferrer">this example on the benefits of not using select</a>, but I can't find anything on <em>how</em>.</p>
<h3>Some examples of how to avoid select</h3> <p>Use <code>Dim</code>'d variables</p> <pre><code>Dim rng as Range </code></pre> <p><code>Set</code> the variable to the required range. There are many ways to refer to a single-cell range:</p> <pre><code>Set rng = Range(&quot;A1&quot;) Set rng = Cells(1, 1) Set rng = Range(&quot;NamedRange&quot;) </code></pre> <p>Or a multi-cell range:</p> <pre><code>Set rng = Range(&quot;A1:B10&quot;) Set rng = Range(&quot;A1&quot;, &quot;B10&quot;) Set rng = Range(Cells(1, 1), Cells(10, 2)) Set rng = Range(&quot;AnotherNamedRange&quot;) Set rng = Range(&quot;A1&quot;).Resize(10, 2) </code></pre> <p>You <em>can</em> use the shortcut to the <code>Evaluate</code> method, but this is less efficient and should generally be avoided in production code.</p> <pre><code>Set rng = [A1] Set rng = [A1:B10] </code></pre> <p>All the above examples refer to cells on the <em>active sheet</em>. Unless you specifically want to work only with the active sheet, it is better to Dim a <code>Worksheet</code> variable too:</p> <pre><code>Dim ws As Worksheet Set ws = Worksheets(&quot;Sheet1&quot;) Set rng = ws.Cells(1, 1) With ws Set rng = .Range(.Cells(1, 1), .Cells(2, 10)) End With </code></pre> <p>If you <em>do</em> want to work with the <code>ActiveSheet</code>, for clarity it's best to be explicit. But take care, as some <code>Worksheet</code> methods change the active sheet.</p> <pre><code>Set rng = ActiveSheet.Range(&quot;A1&quot;) </code></pre> <p>Again, this refers to the <em>active workbook</em>. Unless you specifically want to work only with the <code>ActiveWorkbook</code> or <code>ThisWorkbook</code>, it is better to Dim a <code>Workbook</code> variable too.</p> <pre><code>Dim wb As Workbook Set wb = Application.Workbooks(&quot;Book1&quot;) Set rng = wb.Worksheets(&quot;Sheet1&quot;).Range(&quot;A1&quot;) </code></pre> <p>If you <em>do</em> want to work with the <code>ActiveWorkbook</code>, for clarity it's best to be explicit. But take care, as many <code>WorkBook</code> methods change the active book.</p> <pre><code>Set rng = ActiveWorkbook.Worksheets(&quot;Sheet1&quot;).Range(&quot;A1&quot;) </code></pre> <p>You can also use the <code>ThisWorkbook</code> object to refer to the book containing the running code.</p> <pre><code>Set rng = ThisWorkbook.Worksheets(&quot;Sheet1&quot;).Range(&quot;A1&quot;) </code></pre> <p>A common (bad) piece of code is to open a book, get some data then close again</p> <p>This is bad:</p> <pre><code>Sub foo() Dim v as Variant Workbooks(&quot;Book1.xlsx&quot;).Sheets(1).Range(&quot;A1&quot;).Clear Workbooks.Open(&quot;C:\Path\To\SomeClosedBook.xlsx&quot;) v = ActiveWorkbook.Sheets(1).Range(&quot;A1&quot;).Value Workbooks(&quot;SomeAlreadyOpenBook.xlsx&quot;).Activate ActiveWorkbook.Sheets(&quot;SomeSheet&quot;).Range(&quot;A1&quot;).Value = v Workbooks(2).Activate ActiveWorkbook.Close() End Sub </code></pre> <p>And it would be better like:</p> <pre><code>Sub foo() Dim v as Variant Dim wb1 as Workbook Dim wb2 as Workbook Set wb1 = Workbooks(&quot;SomeAlreadyOpenBook.xlsx&quot;) Set wb2 = Workbooks.Open(&quot;C:\Path\To\SomeClosedBook.xlsx&quot;) v = wb2.Sheets(&quot;SomeSheet&quot;).Range(&quot;A1&quot;).Value wb1.Sheets(&quot;SomeOtherSheet&quot;).Range(&quot;A1&quot;).Value = v wb2.Close() End Sub </code></pre> <p>Pass ranges to your <code>Sub</code>s and <code>Function</code>s as Range variables:</p> <pre><code>Sub ClearRange(r as Range) r.ClearContents '.... End Sub Sub MyMacro() Dim rng as Range Set rng = ThisWorkbook.Worksheets(&quot;SomeSheet&quot;).Range(&quot;A1:B10&quot;) ClearRange rng End Sub </code></pre> <p>You should also apply Methods (such as <code>Find</code> and <code>Copy</code>) to variables:</p> <pre><code>Dim rng1 As Range Dim rng2 As Range Set rng1 = ThisWorkbook.Worksheets(&quot;SomeSheet&quot;).Range(&quot;A1:A10&quot;) Set rng2 = ThisWorkbook.Worksheets(&quot;SomeSheet&quot;).Range(&quot;B1:B10&quot;) rng1.Copy rng2 </code></pre> <p>If you are looping over a range of cells it is often better (faster) to copy the range values to a variant array first and loop over that:</p> <pre><code>Dim dat As Variant Dim rng As Range Dim i As Long Set rng = ThisWorkbook.Worksheets(&quot;SomeSheet&quot;).Range(&quot;A1:A10000&quot;) dat = rng.Value ' dat is now array (1 to 10000, 1 to 1) for i = LBound(dat, 1) to UBound(dat, 1) dat(i,1) = dat(i, 1) * 10 ' Or whatever operation you need to perform next rng.Value = dat ' put new values back on sheet </code></pre> <p>This is a small taster for what's possible.</p>
{ "question_id": 10714251, "question_date": "2012-05-23T05:57:58.193Z", "question_score": 616, "tags": "excel|vba", "answer_id": 10717999, "answer_date": "2012-05-23T10:23:22.667Z", "answer_score": 642 }
Please answer the following Stack Overflow question: Title: System.Timers.Timer vs System.Threading.Timer <p>I have been checking out some of the possible timers lately, and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.timer" rel="noreferrer"><code>System.Threading.Timer</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer" rel="noreferrer"><code>System.Timers.Timer</code></a> are the ones that look needful to me (since they support thread pooling). </p> <p>I am making a game, and I plan on using all types of events, with different intervals, etc. </p> <p>Which would be the best?</p>
<p>This article offers a fairly comprehensive explanation:</p> <p>"<a href="https://web.archive.org/web/20150329101415/https://msdn.microsoft.com/en-us/magazine/cc164015.aspx" rel="noreferrer">Comparing the Timer Classes in the .NET Framework Class Library</a>" - also available <a href="http://download.microsoft.com/download/3/a/7/3a7fa450-1f33-41f7-9e6d-3aa95b5a6aea/MSDNMagazineFebruary2004en-us.chm" rel="noreferrer">as a .chm file</a></p> <p>The specific difference appears to be that <code>System.Timers.Timer</code> is geared towards multithreaded applications and is therefore thread-safe via its <code>SynchronizationObject</code> property, whereas <code>System.Threading.Timer</code> is ironically not thread-safe out-of-the-box.</p> <p>I don't believe that there is a difference between the two as it pertains to how small your intervals can be.</p>
{ "question_id": 1416803, "question_date": "2009-09-13T03:56:10.070Z", "question_score": 616, "tags": ".net|timer", "answer_id": 1416809, "answer_date": "2009-09-13T03:59:28.037Z", "answer_score": 399 }
Please answer the following Stack Overflow question: Title: Convert a list to a data frame <p>I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a <em>quick</em> way to convert this structure into a data frame that has 132 rows and 20 columns of data?</p> <p>Here is some sample data to work with:</p> <pre><code>l &lt;- replicate( 132, as.list(sample(letters, 20)), simplify = FALSE ) </code></pre>
<p><strong>Update July 2020:</strong></p> <p>The default for the parameter <code>stringsAsFactors</code> is now <code>default.stringsAsFactors()</code> which in turn yields <code>FALSE</code> as its default.</p> <hr /> <p>Assuming your list of lists is called <code>l</code>:</p> <pre><code>df &lt;- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE)) </code></pre> <p>The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:</p> <pre><code>df &lt;- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE) </code></pre>
{ "question_id": 4227223, "question_date": "2010-11-19T16:40:52.897Z", "question_score": 615, "tags": "r|list|dataframe", "answer_id": 4227273, "answer_date": "2010-11-19T16:46:09.317Z", "answer_score": 473 }
Please answer the following Stack Overflow question: Title: How to interpolate variables in strings in JavaScript, without concatenation? <p>I know in PHP we can do something like this:</p> <pre><code>$hello = "foo"; $my_string = "I pity the $hello"; </code></pre> <p>Output: <code>"I pity the foo"</code></p> <p>I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.</p>
<p>You can take advantage of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals" rel="noreferrer">Template Literals</a> and use this syntax:</p> <pre><code>`String text ${expression}` </code></pre> <blockquote> <p>Template literals are enclosed by the <strong>back-tick (` `)</strong> (grave accent) instead of double or single quotes.</p> </blockquote> <p>This feature has been introduced in ES2015 (ES6).</p> <p><strong>Example</strong></p> <pre><code>var a = 5; var b = 10; console.log(`Fifteen is ${a + b}.`); // "Fifteen is 15. </code></pre> <p>How neat is that?</p> <p><em>Bonus:</em></p> <p>It also allows for multi-line strings in javascript without escaping, which is great for templates:</p> <pre><code>return ` &lt;div class="${foo}"&gt; ... &lt;/div&gt; `; </code></pre> <p><em><a href="http://kangax.github.io/compat-table/es6/#test-template_literals" rel="noreferrer">Browser support</a>:</em></p> <p>As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use <a href="https://babeljs.io/" rel="noreferrer">Babel</a>/Webpack to transpile your code into ES5 to ensure it will run everywhere. </p> <hr> <p><em>Side note:</em> </p> <p>Starting from IE8+ you can use basic string formatting inside <code>console.log</code>:</p> <pre><code>console.log('%s is %d.', 'Fifteen', 15); // Fifteen is 15. </code></pre>
{ "question_id": 3304014, "question_date": "2010-07-21T21:28:48.733Z", "question_score": 615, "tags": "javascript|string|variables|string-interpolation", "answer_id": 28088965, "answer_date": "2015-01-22T12:37:22.230Z", "answer_score": 1114 }
Please answer the following Stack Overflow question: Title: How do I make a splash screen? <p>I want my app to look more professional, so I decided to add a splash screen.</p> <p>How should I go about the implementation?</p>
<p>Further reading:</p> <ul> <li><a href="https://www.youtube.com/watch?time_continue=160&amp;v=E5Xu2iNHRkk" rel="noreferrer">App Launch time &amp; Themed launch screens (Android Performance Patterns Season 6 Ep. 4)</a></li> <li><a href="https://android.jlelse.eu/launch-screen-in-android-the-right-way-aca7e8c31f52" rel="noreferrer">Splash screen in Android: The right way</a></li> </ul> <p>Old answer:</p> <p><strong>HOW TO</strong>: <a href="http://www.anddev.org/simple_splash_screen-t811.html" rel="noreferrer">Simple splash screen</a></p> <p>This answers shows you how to display a splash screen for a fixed amount of time when your app starts for e.g. branding reasons. E.g. you might choose to show the splash screen for 3 seconds. However if you want to show the spash screen for a variable amount of time (e.g. app startup time) you should check out Abdullah's answer <a href="https://stackoverflow.com/a/15832037/401025">https://stackoverflow.com/a/15832037/401025</a>. However be aware that app startup might be very fast on new devices so the user will just see a flash which is bad UX.</p> <p>First you need to define the spash screen in your <code>layout.xml</code> file</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ImageView android:id="@+id/splashscreen" android:layout_width="wrap_content" android:layout_height="fill_parent" android:src="@drawable/splash" android:layout_gravity="center"/&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, splash"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>And your activity:</p> <pre><code>import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; public class Splash extends Activity { /** Duration of wait **/ private final int SPLASH_DISPLAY_LENGTH = 1000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.splashscreen); /* New Handler to start the Menu-Activity * and close this Splash-Screen after some seconds.*/ new Handler().postDelayed(new Runnable(){ @Override public void run() { /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(Splash.this,Menu.class); Splash.this.startActivity(mainIntent); Splash.this.finish(); } }, SPLASH_DISPLAY_LENGTH); } } </code></pre> <p>Thats all ;)</p>
{ "question_id": 5486789, "question_date": "2011-03-30T13:15:18.290Z", "question_score": 615, "tags": "android|splash-screen", "answer_id": 5486970, "answer_date": "2011-03-30T13:28:58.077Z", "answer_score": 545 }
Please answer the following Stack Overflow question: Title: For loop for HTMLCollection elements <p>I'm trying to set get id of all elements in an <code>HTMLCollectionOf</code>. I wrote the following code:</p> <pre><code>var list = document.getElementsByClassName("events"); console.log(list[0].id); for (key in list) { console.log(key.id); } </code></pre> <p>But I got the following output in console:</p> <pre><code>event1 undefined </code></pre> <p>which is not what I expected. Why is the second console output <code>undefined</code> but the first console output is <code>event1</code>?</p>
<p>In response to the original question, you are using <code>for/in</code> incorrectly. In your code, <code>key</code> is the index. So, to get the value from the pseudo-array, you'd have to do <code>list[key]</code> and to get the id, you'd do <code>list[key].id</code>. But, you should not be doing this with <code>for/in</code> in the first place.</p> <p><strong>Summary (added in Dec 2018)</strong></p> <p>Do not ever use <code>for/in</code> to iterate a nodeList or an HTMLCollection. The reasons to avoid it are described below.</p> <p>All recent versions of modern browsers (Safari, Firefox, Chrome, Edge) all support <code>for/of</code> iteration on DOM lists such <code>nodeList</code> or <code>HTMLCollection</code>.</p> <p>Here's an example:</p> <pre><code>var list = document.getElementsByClassName(&quot;events&quot;); for (let item of list) { console.log(item.id); } </code></pre> <p>To include older browsers (including things like IE), this will work everywhere:</p> <pre><code>var list = document.getElementsByClassName(&quot;events&quot;); for (var i = 0; i &lt; list.length; i++) { console.log(list[i].id); //second console output } </code></pre> <hr /> <p><strong>Explanation For Why You Should Not Use <code>for/in</code></strong></p> <p><code>for/in</code> is meant for iterating the properties of an object. That means it will return all iterable properties of an object. While it may appear to work for an array (returning array elements or pseudo-array elements), it can also return other properties of the object that are not what you are expecting from the array-like elements. And, guess what, an <code>HTMLCollection</code> or <code>nodeList</code> object can both have other properties that will be returned with a <code>for/in</code> iteration. I just tried this in Chrome and iterating it the way you were iterating it will retrieve the items in the list (indexes 0, 1, 2, etc...), but also will retrieve the <code>length</code> and <code>item</code> properties. The <code>for/in</code> iteration simply won't work for an HTMLCollection.</p> <hr /> <p>See <a href="http://jsfiddle.net/jfriend00/FzZ2H/" rel="noreferrer">http://jsfiddle.net/jfriend00/FzZ2H/</a> for why you can't iterate an HTMLCollection with <code>for/in</code>.</p> <p>In Firefox, your <code>for/in</code> iteration would return these items (all the iterable properties of the object):</p> <pre><code>0 1 2 item namedItem @@iterator length </code></pre> <p>Hopefully, now you can see why you want to use <code>for (var i = 0; i &lt; list.length; i++)</code> instead so you just get <code>0</code>, <code>1</code> and <code>2</code> in your iteration.</p> <hr /> <p><strong>Evolution of Browser Support for NodeList and HTMLCollection iteration</strong></p> <p>Following below is an evolution of how browsers have evolved through the time period 2015-2018 giving you additional ways to iterate. None of these are now needed in modern browsers since you can use the options described above.</p> <p><strong>Update for ES6 in 2015</strong></p> <p>Added to ES6 is <code>Array.from()</code> that will convert an array-like structure to an actual array. That allows one to enumerate a list directly like this:</p> <pre><code>&quot;use strict&quot;; Array.from(document.getElementsByClassName(&quot;events&quot;)).forEach(function(item) { console.log(item.id); }); </code></pre> <p>Working demo (in Firefox, Chrome, and Edge as of April 2016): <a href="https://jsfiddle.net/jfriend00/8ar4xn2s/" rel="noreferrer">https://jsfiddle.net/jfriend00/8ar4xn2s/</a></p> <hr /> <p><strong>Update for ES6 in 2016</strong></p> <p>You can now use the ES6 for/of construct with a <code>NodeList</code> and an <code>HTMLCollection</code> by just adding this to your code:</p> <pre><code>NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]; HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]; </code></pre> <p>Then, you can do:</p> <pre><code>var list = document.getElementsByClassName(&quot;events&quot;); for (var item of list) { console.log(item.id); } </code></pre> <p>This works in the current version of Chrome, Firefox, and Edge. This works because it attaches the Array iterator to both the NodeList and HTMLCollection prototypes so that when for/of iterates them, it uses the Array iterator to iterate them.</p> <p>Working demo: <a href="http://jsfiddle.net/jfriend00/joy06u4e/" rel="noreferrer">http://jsfiddle.net/jfriend00/joy06u4e/</a>.</p> <hr /> <p><strong>Second Update for ES6 in Dec 2016</strong></p> <p>As of Dec 2016, <code>Symbol.iterator</code> support has been built-in to Chrome v54 and Firefox v50 so the code below works by itself. It is not yet built-in for Edge.</p> <pre><code>var list = document.getElementsByClassName(&quot;events&quot;); for (let item of list) { console.log(item.id); } </code></pre> <p>Working demo (in Chrome and Firefox): <a href="http://jsfiddle.net/jfriend00/3ddpz8sp/" rel="noreferrer">http://jsfiddle.net/jfriend00/3ddpz8sp/</a></p> <p><strong>Third Update for ES6 in Dec 2017</strong></p> <p>As of Dec. 2017, this capability works in Edge 41.16299.15.0 for a <code>nodeList</code> as in <code>document.querySelectorAll()</code>, but not an <code>HTMLCollection</code> as in <code>document.getElementsByClassName()</code> so you have to manually assign the iterator to use it in Edge for an <code>HTMLCollection</code>. It is a total mystery why they'd fix one collection type, but not the other. But, you can at least use the result of <code>document.querySelectorAll()</code> with ES6 <code>for/of</code> syntax in current versions of Edge now.</p> <p>I've also updated the above jsFiddle so it tests both <code>HTMLCollection</code> and <code>nodeList</code> separately and captures the output in the jsFiddle itself.</p> <p><strong>Fourth Update for ES6 in Mar 2018</strong></p> <p>Per mesqueeeb, <code>Symbol.iterator</code> support has been built-in to Safari too, so you can use <code>for (let item of list)</code> for either <code>document.getElementsByClassName()</code> or <code>document.querySelectorAll()</code>.</p> <p><strong>Fifth Update for ES6 in Apr 2018</strong></p> <p>Apparently, support for iterating an <code>HTMLCollection</code> with <code>for/of</code> will be coming to Edge 18 in Fall 2018.</p> <p><strong>Sixth Update for ES6 in Nov 2018</strong></p> <p>I can confirm that with Microsoft Edge v18 (that is included in the Fall 2018 Windows Update), you can now iterate both an HTMLCollection and a NodeList with for/of in Edge.</p> <p>So, now all modern browsers contain native support for <code>for/of</code> iteration of both the HTMLCollection and NodeList objects.</p>
{ "question_id": 22754315, "question_date": "2014-03-31T05:40:03.637Z", "question_score": 615, "tags": "javascript|dom", "answer_id": 22754453, "answer_date": "2014-03-31T05:50:51.033Z", "answer_score": 1234 }
Please answer the following Stack Overflow question: Title: Getting a map() to return a list in Python 3.x <p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, in Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
<p>Do this:</p> <pre><code>list(map(chr,[66,53,0,94])) </code></pre> <p>In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster. </p> <p>If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the <code>map</code> object like so:</p> <pre><code># Prints "ABCD" for ch in map(chr,[65,66,67,68]): print(ch) </code></pre>
{ "question_id": 1303347, "question_date": "2009-08-20T00:27:26.793Z", "question_score": 615, "tags": "python|list|python-3.x|map-function", "answer_id": 1303354, "answer_date": "2009-08-20T00:28:40.710Z", "answer_score": 883 }
Please answer the following Stack Overflow question: Title: Is there a function to make a copy of a PHP array to another? <p>Is there a function to make a copy of a PHP array to another?</p> <p>I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.</p>
<p>In PHP, all variables except objects are assigned by the mechanism called copy-on-write, while objects are assigned by reference. Which means that for the arrays with scalar values simply <code>$b = $a</code> already will give you a copy:</p> <pre><code>$a = array(); $b = $a; $b['foo'] = 42; var_dump($a); </code></pre> <p>Will yield:</p> <pre><code>array(0) { } </code></pre> <p>Whereas with objects,</p> <pre><code>$a = new StdClass(); $b = $a; $b-&gt;foo = 42; var_dump($a); </code></pre> <p>Yields:</p> <pre><code>object(stdClass)#1 (1) { [&quot;foo&quot;]=&gt; int(42) } </code></pre> <p>An edge case when array elements could be objects that need to be cloned as well, is explained in <a href="https://stackoverflow.com/questions/1532618/is-there-a-function-to-make-a-copy-of-a-php-array-to-another#17729234">another answer</a></p> <p>You could get confused by intricacies such as <a href="http://php.net/manual/en/class.arrayobject.php" rel="noreferrer"><code>ArrayObject</code></a>, which is an object that acts exactly like an array. Being an object however, it has reference semantics.</p> <p>Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called &quot;references&quot;. They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.</p>
{ "question_id": 1532618, "question_date": "2009-10-07T16:11:50.393Z", "question_score": 615, "tags": "php|arrays|copy", "answer_id": 1533214, "answer_date": "2009-10-07T17:56:24.737Z", "answer_score": 1043 }
Please answer the following Stack Overflow question: Title: How unique is UUID? <p>How safe is it to use UUID to uniquely identify something (I'm using it for files uploaded to the server)? As I understand it, it is based off random numbers. However, it seems to me that given enough time, it would eventually repeat it self, just by pure chance. Is there a better system or a pattern of some type to alleviate this issue?</p>
<p>Very safe: </p> <blockquote> <p>the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10<sup>−11</sup>), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.</p> </blockquote> <p>Caveat:</p> <blockquote> <p>However, these probabilities only hold when the UUIDs are generated using sufficient entropy. Otherwise, the probability of duplicates could be significantly higher, since the statistical dispersion might be lower. Where unique identifiers are required for distributed applications, so that UUIDs do not clash even when data from many devices is merged, the randomness of the seeds and generators used on every device must be reliable for the life of the application. Where this is not feasible, RFC4122 recommends using a namespace variant instead.</p> </blockquote> <p>Source: The <a href="https://en.wikipedia.org/w/index.php?title=Universally_unique_identifier&amp;oldid=755882275#Random_UUID_probability_of_duplicates" rel="noreferrer"><em>Random UUID probability of duplicates</em> section</a> of the Wikipedia article on Universally unique identifiers (link leads to a revision from December 2016 before editing reworked the section).</p> <p>Also see the current section on the same subject on the same Universally unique identifier article, <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions" rel="noreferrer"><em>Collisions</em></a>.</p>
{ "question_id": 1155008, "question_date": "2009-07-20T18:06:40.550Z", "question_score": 615, "tags": "guid|uniqueidentifier|uuid", "answer_id": 1155027, "answer_date": "2009-07-20T18:09:50.200Z", "answer_score": 621 }
Please answer the following Stack Overflow question: Title: When to use: Java 8+ interface default method, vs. abstract method <p>Java 8 allows for default implementation of methods in interfaces called <a href="http://java.dzone.com/articles/introduction-default-methods" rel="noreferrer">Default Methods</a>.</p> <p>I am confused between when would I use that sort of <code>interface default method</code>, instead of an <code>abstract class</code> (with <code>abstract method(s)</code>).</p> <p>So when should interface with default methods be used and when should an abstract class (with abstract method(s)) be used? Are the abstract classes still useful in that scenario? </p>
<p>There's a lot more to abstract classes than default method implementations (such as private state), but as of Java 8, whenever you have the choice of either, you should go with the defender (aka. <code>default</code>) method in the interface.</p> <p>The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.</p> <p>The good thing about this new feature is that, where before you were forced to use an abstract class for the convenience methods, thus constraining the implementor to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer.</p> <p>The original motivation to introduce <code>default</code> methods to Java 8 was the desire to extend the Collections Framework interfaces with lambda-oriented methods without breaking any existing implementations. Although this is more relevant to the authors of public libraries, you may find the same feature useful in your project as well. You've got one centralized place where to add new convenience and you don't have to rely on how the rest of the type hierarchy looks.</p>
{ "question_id": 19998454, "question_date": "2013-11-15T10:06:01.923Z", "question_score": 615, "tags": "java|interface|java-8|abstract-class|default-method", "answer_id": 19998827, "answer_date": "2013-11-15T10:24:58.220Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: How do I access the ith column of a NumPy multidimensional array? <p>Given:</p> <pre><code>test = numpy.array([[1, 2], [3, 4], [5, 6]]) </code></pre> <p><code>test[i]</code> gives the <em>ith</em> row (e.g. <code>[1, 2]</code>). How do I access the <em>ith</em> column? (e.g. <code>[1, 3, 5]</code>). Also, would this be an expensive operation?</p>
<p>To access column 0:</p> <pre><code>&gt;&gt;&gt; test[:, 0] array([1, 3, 5]) </code></pre> <p>To access row 0:</p> <pre><code>&gt;&gt;&gt; test[0, :] array([1, 2]) </code></pre> <p>This is covered in Section 1.4 (Indexing) of the <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="noreferrer">NumPy reference</a>. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.</p>
{ "question_id": 4455076, "question_date": "2010-12-15T21:27:41.750Z", "question_score": 614, "tags": "python|arrays|numpy", "answer_id": 4455154, "answer_date": "2010-12-15T21:35:43.360Z", "answer_score": 909 }
Please answer the following Stack Overflow question: Title: How do I run a node.js app as a background service? <p>Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post.</p> <hr> <p><strong>Original post</strong>:</p> <p>I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this <a href="http://kevin.vanzonneveld.net/techblog/article/run_nodejs_as_a_service_on_ubuntu_karmic/" rel="noreferrer">tutorial</a>, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the <code>2&gt;&amp;1 &gt;&gt; file</code> part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.</p> <p>I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.</p> <p>So how can I leave it running when I shut down my local computer?</p> <hr> <p><strong>Top solutions</strong>:</p> <ul> <li><a href="https://stackoverflow.com/a/29042953/339122">Systemd</a> (Linux)</li> <li><a href="https://stackoverflow.com/a/25998406/339122">Launchd</a> (Mac)</li> <li><a href="https://stackoverflow.com/a/15616912/339122">node-windows</a> (Windows)</li> <li><a href="https://stackoverflow.com/a/17005935/339122">PM2</a> (Node.js)</li> </ul>
<p>Copying my own answer from <a href="https://stackoverflow.com/questions/4681067/how-to-run-a-node-js-application-as-its-own-process/28542093#28542093">How do I run a Node.js application as its own process?</a></p> <p><strong>2015 answer</strong>: nearly every Linux distro comes with systemd, which means <strong>forever, monit, PM2, etc are no longer necessary - your OS already handles these tasks</strong>.</p> <p>Make a <code>myapp.service</code> file (replacing 'myapp' with your app's name, obviously):</p> <pre><code>[Unit] Description=My app [Service] ExecStart=/var/www/myapp/app.js Restart=always User=nobody # Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody' Group=nogroup Environment=PATH=/usr/bin:/usr/local/bin Environment=NODE_ENV=production WorkingDirectory=/var/www/myapp [Install] WantedBy=multi-user.target </code></pre> <p><strong>Note if you're new to Unix:</strong> <code>/var/www/myapp/app.js</code> should have <code>#!/usr/bin/env node</code> on the very first line and have the executable mode turned on <code>chmod +x myapp.js</code>.</p> <p>Copy your service file into the <code>/etc/systemd/system</code>.</p> <p>Start it with <code>systemctl start myapp</code>.</p> <p>Enable it to run on boot with <code>systemctl enable myapp</code>.</p> <p>See logs with <code>journalctl -u myapp</code></p> <p>This is taken from <strong><a href="https://web.archive.org/web/20180212163211/https://certsimple.com/blog/deploy-node-on-linux" rel="noreferrer">How we deploy node apps on Linux, 2018 edition</a></strong>, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the <code>.service</code> file).</p>
{ "question_id": 4018154, "question_date": "2010-10-25T19:34:10.363Z", "question_score": 614, "tags": "node.js|process|background|server|daemon", "answer_id": 29042953, "answer_date": "2015-03-13T22:23:06.197Z", "answer_score": 559 }
Please answer the following Stack Overflow question: Title: What is this date format? 2011-08-12T20:17:46.384Z <p>I have the following date: <code>2011-08-12T20:17:46.384Z</code>. What format is this? I'm trying to parse it with Java 1.4 via <code>DateFormat.getDateInstance().parse(dateStr)</code> and I'm getting</p> <blockquote> <p>java.text.ParseException: Unparseable date: "2011-08-12T20:17:46.384Z"</p> </blockquote> <p>I think I should be using <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a> for parsing, but I have to know the format string first. All I have for that so far is <code>yyyy-MM-dd</code>, because I don't know what the <code>T</code> means in this string--something time zone-related? This date string is coming from the <code>lcmis:downloadedOn</code> tag shown on <a href="http://www-10.lotus.com/ldd/appdevwiki.nsf/dx/Files_CMIS_download_history_media_type" rel="noreferrer">Files CMIS download history media type</a>.</p>
<p>The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings <em>always</em> have a "Z" you can use:</p> <pre><code>SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); format.setTimeZone(TimeZone.getTimeZone("UTC")); </code></pre> <p>Or using <a href="https://www.joda.org/joda-time/" rel="noreferrer">Joda Time</a>, you can use <a href="https://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--" rel="noreferrer"><code>ISODateTimeFormat.dateTime()</code></a>.</p>
{ "question_id": 8405087, "question_date": "2011-12-06T18:45:57.073Z", "question_score": 614, "tags": "java|date|time|format|simpledateformat", "answer_id": 8405125, "answer_date": "2011-12-06T18:49:10.637Z", "answer_score": 715 }
Please answer the following Stack Overflow question: Title: How to detect a route change in Angular? <p>I am looking to detect a route change in my <code>AppComponent</code>.</p> <p>Thereafter I will check the global user token to see if the user is logged in so that I can redirect the user if the user is not logged in.</p>
<p>In Angular 2 you can <code>subscribe</code> (Rx event) to a Router instance. So you can do things like</p> <pre class="lang-js prettyprint-override"><code>class MyClass { constructor(private router: Router) { router.subscribe((val) =&gt; /*whatever*/) } } </code></pre> <p><strong>Edit</strong> (since rc.1)</p> <pre class="lang-js prettyprint-override"><code>class MyClass { constructor(private router: Router) { router.changes.subscribe((val) =&gt; /*whatever*/) } } </code></pre> <p><strong>Edit 2</strong> (since 2.0.0)</p> <p>see also : <a href="https://angular.io/api/router/RouterEvent" rel="noreferrer">Router.events doc</a></p> <pre class="lang-js prettyprint-override"><code>class MyClass { constructor(private router: Router) { router.events.subscribe((val) =&gt; { // see also console.log(val instanceof NavigationEnd) }); } } </code></pre>
{ "question_id": 33520043, "question_date": "2015-11-04T10:56:58.480Z", "question_score": 614, "tags": "angular|routes|angular2-routing", "answer_id": 33548895, "answer_date": "2015-11-05T15:44:30.927Z", "answer_score": 750 }
Please answer the following Stack Overflow question: Title: MySql export schema without data <p>I'm using a MySql database with a Java program, now I want to give the program to somebody else.</p> <p>How to export the MySql database structure without the data in it, just the structure?</p>
<p>You can do with the <code>--no-data</code> option with mysqldump command</p> <pre class="lang-sh prettyprint-override"><code>mysqldump -h yourhostnameorIP -u root -p --no-data dbname &gt; schema.sql </code></pre>
{ "question_id": 6175473, "question_date": "2011-05-30T11:06:54.273Z", "question_score": 614, "tags": "mysql|sql", "answer_id": 6175506, "answer_date": "2011-05-30T11:09:42.283Z", "answer_score": 1183 }
Please answer the following Stack Overflow question: Title: Java 8 Distinct by property <p>In Java 8 how can I filter a collection using the <code>Stream</code> API by checking the distinctness of a property of each object?</p> <p>For example I have a list of <code>Person</code> object and I want to remove people with the same name,</p> <pre><code>persons.stream().distinct(); </code></pre> <p>Will use the default equality check for a <code>Person</code> object, so I need something like,</p> <pre><code>persons.stream().distinct(p -&gt; p.getName()); </code></pre> <p>Unfortunately the <code>distinct()</code> method has no such overload. Without modifying the equality check inside the <code>Person</code> class is it possible to do this succinctly?</p>
<p>Consider <code>distinct</code> to be a <em>stateful filter</em>. Here is a function that returns a predicate that maintains state about what it's seen previously, and that returns whether the given element was seen for the first time:</p> <pre><code>public static &lt;T&gt; Predicate&lt;T&gt; distinctByKey(Function&lt;? super T, ?&gt; keyExtractor) { Set&lt;Object&gt; seen = ConcurrentHashMap.newKeySet(); return t -&gt; seen.add(keyExtractor.apply(t)); } </code></pre> <p>Then you can write:</p> <pre><code>persons.stream().filter(distinctByKey(Person::getName)) </code></pre> <p>Note that if the stream is ordered and is run in parallel, this will preserve an <em>arbitrary</em> element from among the duplicates, instead of the first one, as <code>distinct()</code> does.</p> <p>(This is essentially the same as <a href="https://stackoverflow.com/a/27872086/1441122">my answer</a> to this question: <a href="https://stackoverflow.com/questions/27870136/java-lambda-stream-distinct-on-arbitrary-key">Java Lambda Stream Distinct() on arbitrary key?</a>)</p>
{ "question_id": 23699371, "question_date": "2014-05-16T15:40:12.070Z", "question_score": 614, "tags": "java|collections|java-8|java-stream|distinct-values", "answer_id": 27872852, "answer_date": "2015-01-10T04:28:32.780Z", "answer_score": 826 }
Please answer the following Stack Overflow question: Title: Should I use 'border: none' or 'border: 0'? <p>Which of the two methods conforms to W3C standards? Do they both behave as expected across browsers?</p> <blockquote> <p>border: none;<br> border: 0;</p> </blockquote>
<p><strong>Both are valid.</strong> It's your choice.</p> <p>I prefer <code>border:0</code> because it's shorter; I find that easier to read. You may find <code>none</code> more legible. We live in a world of very capable CSS post-processors so I'd recommend you use whatever you prefer and then run it through a &quot;compressor&quot;. There's no holy war worth fighting here but Webpack→LESS→PostCSS→PurgeCSS is a good 2020 stack.</p> <p>That all said, if you're hand-writing all your production CSS, I maintain —despite the grumbling in the comments— <strong>it does not hurt to be bandwidth conscious</strong>. Using <code>border:0</code> <em>will</em> save an infinitesimal amount of bandwidth on its own, but if you <em>make every byte count</em>, you will make your website faster.</p> <hr /> <p>The CSS2 specs <a href="http://www.w3.org/TR/CSS2/box.html#propdef-border" rel="noreferrer">are here</a>. These are extended in CSS3 but not in any way relevant to this.</p> <pre><code>'border' Value: [ &lt;border-width&gt; || &lt;border-style&gt; || &lt;'border-top-color'&gt; ] | inherit Initial: see individual properties Applies to: all elements Inherited: no Percentages: N/A Media: visual Computed value: see individual properties </code></pre> <p>You can use any combination of width, style and colour.<br /> Here, <code>0</code> sets the width, <code>none</code> the style. They have the same rendering result: nothing is shown.</p>
{ "question_id": 2922909, "question_date": "2010-05-27T16:25:24.100Z", "question_score": 614, "tags": "css|border", "answer_id": 2922923, "answer_date": "2010-05-27T16:27:13.753Z", "answer_score": 507 }
Please answer the following Stack Overflow question: Title: Interface defining a constructor signature? <p>It's weird that this is the first time I've bumped into this problem, but:</p> <p>How do you define a constructor in a C# interface?</p> <p><strong>Edit</strong><br> Some people wanted an example (it's a free time project, so yes, it's a game)</p> <p>IDrawable<br> +Update<br> +Draw</p> <p>To be able to Update (check for edge of screen etc) and draw itself it will always need a <code>GraphicsDeviceManager</code>. So I want to make sure the object has a reference to it. This would belong in the constructor.</p> <p>Now that I wrote this down I think what I'm implementing here is <code>IObservable</code> and the <code>GraphicsDeviceManager</code> should take the <code>IDrawable</code>... It seems either I don't get the XNA framework, or the framework is not thought out very well.</p> <p><strong>Edit</strong><br> There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.</p>
<p>As already well noted, you can't have constructors on an Interface. But since this is such a highly ranked result in Google some 7 years later, I thought I would chip in here - specifically to show how you could use an abstract base class in tandem with your existing Interface and maybe cut down on the amount of refactoring needed in the future for similar situations. This concept has already been hinted at in some of the comments but I thought it would be worth showing how to actually do it.</p> <p>So you have your main interface that looks like this so far:</p> <pre><code>public interface IDrawable { void Update(); void Draw(); } </code></pre> <p>Now create an abstract class with the constructor you want to enforce. Actually, since it's now available since the time you wrote your original question, we can get a little fancy here and use generics in this situation so that we can adapt this to other interfaces that might need the same functionality but have different constructor requirements:</p> <pre><code>public abstract class MustInitialize&lt;T&gt; { public MustInitialize(T parameters) { } } </code></pre> <p>Now you'll need to create a new class that inherits from both the IDrawable interface and the MustInitialize abstract class:</p> <pre><code>public class Drawable : MustInitialize&lt;GraphicsDeviceManager&gt;, IDrawable { GraphicsDeviceManager _graphicsDeviceManager; public Drawable(GraphicsDeviceManager graphicsDeviceManager) : base (graphicsDeviceManager) { _graphicsDeviceManager = graphicsDeviceManager; } public void Update() { //use _graphicsDeviceManager here to do whatever } public void Draw() { //use _graphicsDeviceManager here to do whatever } } </code></pre> <p>Then just create an instance of Drawable and you're good to go:</p> <pre><code>IDrawable drawableService = new Drawable(myGraphicsDeviceManager); </code></pre> <p>The cool thing here is that the new Drawable class we created still behaves just like what we would expect from an IDrawable.</p> <p>If you need to pass more than one parameter to the MustInitialize constructor, you can create a class that defines properties for all of the fields you'll need to pass in.</p>
{ "question_id": 619856, "question_date": "2009-03-06T18:13:27.020Z", "question_score": 614, "tags": "c#|interface|constructor", "answer_id": 41685659, "answer_date": "2017-01-16T21:57:06.417Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: How can I update the current line in a C# Windows Console App? <p>When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to show a percentage representing how close a process is to completion, I'd just like to update the value on the same line as the cursor, and not have to put each percentage on a new line.</p> <p>Can this be done with a "standard" C# console app?</p>
<p>If you print only <code>"\r"</code> to the console the cursor goes back to the beginning of the current line and then you can rewrite it. This should do the trick:</p> <pre><code>for(int i = 0; i &lt; 100; ++i) { Console.Write("\r{0}% ", i); } </code></pre> <p>Notice the few spaces after the number to make sure that whatever was there before is erased.<br> Also notice the use of <code>Write()</code> instead of <code>WriteLine()</code> since you don't want to add an "\n" at the end of the line.</p>
{ "question_id": 888533, "question_date": "2009-05-20T15:12:53.160Z", "question_score": 614, "tags": "c#|windows|console", "answer_id": 888569, "answer_date": "2009-05-20T15:18:58.140Z", "answer_score": 914 }
Please answer the following Stack Overflow question: Title: Scroll Automatically to the Bottom of the Page <p>I have a list of questions. When I click on the first question, it should automatically take me to a specific element at the bottom of the page.</p> <p>How can I do this with jQuery?</p>
<p>jQuery isn't necessary. Most of the top results I got from a Google search gave me this answer:</p> <pre><code>window.scrollTo(0, document.body.scrollHeight); </code></pre> <p>Where you have nested elements, the document might not scroll. <strong>In this case</strong>, you need to target the element that scrolls and use it's scroll height instead.</p> <p><code>window.scrollTo(0, document.querySelector(&quot;.scrollingContainer&quot;).scrollHeight);</code></p> <p>You can tie that to the <code>onclick</code> event of your question (i.e. <code>&lt;div onclick=&quot;ScrollToBottom()&quot; ...</code>).</p> <p>Some additional sources you can take a look at:</p> <ul> <li><a href="http://www.sourcetricks.com/2010/07/javascript-scroll-to-bottom-of-page.html" rel="noreferrer">http://www.sourcetricks.com/2010/07/javascript-scroll-to-bottom-of-page.html</a></li> <li><a href="http://www.alecjacobson.com/weblog/?p=753" rel="noreferrer">http://www.alecjacobson.com/weblog/?p=753</a></li> <li><a href="http://www.mediacollege.com/internet/javascript/page/scroll.html" rel="noreferrer">http://www.mediacollege.com/internet/javascript/page/scroll.html</a></li> <li><a href="http://www.electrictoolbox.com/jquery-scroll-bottom/" rel="noreferrer">http://www.electrictoolbox.com/jquery-scroll-bottom/</a></li> </ul>
{ "question_id": 11715646, "question_date": "2012-07-30T05:03:10.600Z", "question_score": 613, "tags": "javascript|jquery|scroll|scrollto|js-scrollintoview", "answer_id": 11715670, "answer_date": "2012-07-30T05:05:57.413Z", "answer_score": 1177 }
Please answer the following Stack Overflow question: Title: How can I use pickle to save a dict (or any other Python object)? <p>I have looked through the information that the <a href="https://docs.python.org/3/library/pickle.html" rel="noreferrer">Python docs</a> give, but I'm still a little confused. Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it?</p>
<p>Try this:</p> <pre><code>import pickle a = {'hello': 'world'} with open('filename.pickle', 'wb') as handle: pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL) with open('filename.pickle', 'rb') as handle: b = pickle.load(handle) print(a == b) </code></pre> <p>There's nothing about the above solution that is specific to a <code>dict</code> object. This same approach will will work for many Python objects, including instances of arbitrary classes and arbitrarily complex nestings of data structures. For example, replacing the second line with these lines:</p> <pre><code>import datetime today = datetime.datetime.now() a = [{'hello': 'world'}, 1, 2.3333, 4, True, &quot;x&quot;, (&quot;y&quot;, [[[&quot;z&quot;], &quot;y&quot;], &quot;x&quot;]), {'today', today}] </code></pre> <p>will produce a result of <code>True</code> as well.</p> <p>Some objects can't be pickled due to their very nature. For example, it doesn't make sense to pickle a structure containing a handle to an open file.</p>
{ "question_id": 11218477, "question_date": "2012-06-27T02:12:44.003Z", "question_score": 613, "tags": "python|dictionary|pickle", "answer_id": 11218504, "answer_date": "2012-06-27T02:16:11.663Z", "answer_score": 1175 }
Please answer the following Stack Overflow question: Title: What's the easiest way to call a function every 5 seconds in jQuery? <p>JQuery, how to call a function every 5 seconds.</p> <p>I'm looking for a way to automate the changing of images in a slideshow. </p> <p>I'd rather not install any other 3rd party plugins if possible.</p>
<p>You don't need jquery for this, in plain javascript, the following will work!</p> <pre><code>var intervalId = window.setInterval(function(){ /// call your function here }, 5000); </code></pre> <p>To stop the loop you can use</p> <pre><code>clearInterval(intervalId) </code></pre>
{ "question_id": 2170923, "question_date": "2010-01-31T07:31:35.097Z", "question_score": 613, "tags": "javascript|jquery|jquery-plugins|timer", "answer_id": 2170924, "answer_date": "2010-01-31T07:32:31.977Z", "answer_score": 1091 }
Please answer the following Stack Overflow question: Title: How to convert Milliseconds to "X mins, x seconds" in Java? <p>I want to record the time using <code>System.currentTimeMillis()</code> when a user begins something in my program. When he finishes, I will subtract the current <code>System.currentTimeMillis()</code> from the <code>start</code> variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.</p> <p>What's the best way to do this?</p>
<p>Use the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html#toMinutes(long)" rel="noreferrer"><code>java.util.concurrent.TimeUnit</code></a> class:</p> <pre><code>String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ); </code></pre> <p>Note: <code>TimeUnit</code> is part of the Java 1.5 specification, but <code>toMinutes</code> was added as of Java 1.6.</p> <p>To add a leading zero for values 0-9, just do:</p> <pre><code>String.format("%02d min, %02d sec", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ); </code></pre> <p>If <code>TimeUnit</code> or <code>toMinutes</code> are unsupported (such as on Android before API version 9), use the following equations:</p> <pre><code>int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); //etc... </code></pre>
{ "question_id": 625433, "question_date": "2009-03-09T08:41:06.200Z", "question_score": 613, "tags": "java|time", "answer_id": 625624, "answer_date": "2009-03-09T10:01:19.360Z", "answer_score": 1309 }
Please answer the following Stack Overflow question: Title: Get HTML source of WebElement in Selenium WebDriver using Python <p>I'm using the Python bindings to run Selenium WebDriver:</p> <pre><code>from selenium import webdriver wd = webdriver.Firefox() </code></pre> <p>I know I can grab a webelement like so:</p> <pre><code>elem = wd.find_element_by_css_selector('#my-id') </code></pre> <p>And I know I can get the full page source with...</p> <pre><code>wd.page_source </code></pre> <p>But is there a way to get the &quot;element source&quot;?</p> <pre><code>elem.source # &lt;-- returns the HTML as a string </code></pre> <p>The Selenium WebDriver documentation for Python are basically non-existent and I don't see anything in the code that seems to enable that functionality.</p> <p>What is the best way to access the HTML of an element (and its children)?</p>
<p>You can read the <code>innerHTML</code> attribute to get the source of the <em>content</em> of the element or <code>outerHTML</code> for the source with the current element.</p> <p>Python:</p> <pre><code>element.get_attribute('innerHTML') </code></pre> <p>Java:</p> <pre><code>elem.getAttribute(&quot;innerHTML&quot;); </code></pre> <p>C#:</p> <pre><code>element.GetAttribute(&quot;innerHTML&quot;); </code></pre> <p>Ruby:</p> <pre><code>element.attribute(&quot;innerHTML&quot;) </code></pre> <p>JavaScript:</p> <pre><code>element.getAttribute('innerHTML'); </code></pre> <p>PHP:</p> <pre><code>$element-&gt;getAttribute('innerHTML'); </code></pre> <p>It was tested and worked with the <code>ChromeDriver</code>.</p>
{ "question_id": 7263824, "question_date": "2011-08-31T21:44:11.100Z", "question_score": 613, "tags": "python|selenium|selenium-webdriver|webdriver|automated-tests", "answer_id": 8575709, "answer_date": "2011-12-20T12:49:48.737Z", "answer_score": 944 }
Please answer the following Stack Overflow question: Title: Finding what methods a Python object has <p>Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?</p> <p>Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
<p><strong>For many objects</strong>, you can use this code, replacing 'object' with the object you're interested in:</p> <pre class="lang-py prettyprint-override"><code>object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name))] </code></pre> <p>I discovered it at <a href="https://web.archive.org/web/20180901124519/http://www.diveintopython.net/power_of_introspection/index.html" rel="noreferrer">diveintopython.net</a> (now archived), that should provide some further details!</p> <p><strong>If you get an <code>AttributeError</code>, you can use this instead</strong>:</p> <p><code>getattr()</code> is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame([[10, 20, 30], [100, 200, 300]], columns=['foo', 'bar', 'baz']) def get_methods(object, spacing=20): methodList = [] for method_name in dir(object): try: if callable(getattr(object, method_name)): methodList.append(str(method_name)) except Exception: methodList.append(str(method_name)) processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s) for method in methodList: try: print(str(method.ljust(spacing)) + ' ' + processFunc(str(getattr(object, method).__doc__)[0:90])) except Exception: print(method.ljust(spacing) + ' ' + ' getattr() failed') get_methods(df['foo']) </code></pre>
{ "question_id": 34439, "question_date": "2008-08-29T15:05:17.237Z", "question_score": 613, "tags": "python|introspection", "answer_id": 34452, "answer_date": "2008-08-29T15:09:05.667Z", "answer_score": 697 }
Please answer the following Stack Overflow question: Title: How do I attach events to dynamic HTML elements with jQuery? <p>Suppose I have some jQuery code that attaches an event handler to all elements with class <code>.myclass</code>. </p> <p><strong>For example:</strong></p> <pre><code>$(function(){ $(".myclass").click( function() { // do something }); }); </code></pre> <p>And my HTML might be as follows:</p> <pre><code>&lt;a class="myclass" href="#"&gt;test1&lt;/a&gt; &lt;a class="myclass" href="#"&gt;test2&lt;/a&gt; &lt;a class="myclass" href="#"&gt;test3&lt;/a&gt; </code></pre> <p>That works with no problem. However, consider if the <code>.myclass</code> elements were written to the page at some future time.</p> <p><strong>For example:</strong></p> <pre><code>&lt;a id="anchor1" href="#"&gt;create link dynamically&lt;/a&gt; &lt;script type="text/javascript"&gt; $(function(){ $("#anchor1").click( function() { $("#anchor1").append('&lt;a class="myclass" href="#"&gt;test4&lt;/a&gt;'); }); }); &lt;/script&gt; </code></pre> <p>In this case, the <code>test4</code> link is created when a user clicks on <code>a#anchor1</code>.</p> <p>The <code>test4</code> link does not have the <code>click()</code> handler associated with it, even though it has <code>class="myclass"</code>.</p> <p>Basically, I would like to write the <code>click()</code> handler once and have it apply to both content present at page load, and content brought in later via <strong>AJAX / DHTML</strong>. Any idea how I can fix this? </p>
<p>I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7. </p> <p>From <a href="http://api.jquery.com/live/">http://api.jquery.com/live/</a></p> <blockquote> <p>As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). </p> </blockquote> <p>For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.</p> <p>See <a href="http://api.jquery.com/on/">http://api.jquery.com/on/</a></p> <p>So instead of...</p> <pre><code>$(".myclass").click( function() { // do something }); </code></pre> <p>You can write...</p> <pre><code>$('body').on('click', 'a.myclass', function() { // do something }); </code></pre> <p>This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.</p> <p>The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:</p> <pre><code>$('ul').on('click', 'li', function() { alert( $(this).text() ); }); </code></pre> <p>As long as the ul tag exists this will work (no li elements need exist yet).</p>
{ "question_id": 1359018, "question_date": "2009-08-31T19:29:03.347Z", "question_score": 613, "tags": "javascript|jquery|events|dhtml", "answer_id": 9331127, "answer_date": "2012-02-17T15:37:53.910Z", "answer_score": 1034 }
Please answer the following Stack Overflow question: Title: How do I check if a string contains another string in Swift? <p>In <code>Objective-C</code> the code to check for a substring in an <code>NSString</code> is: </p> <pre><code>NSString *string = @"hello Swift"; NSRange textRange =[string rangeOfString:@"Swift"]; if(textRange.location != NSNotFound) { NSLog(@"exists"); } </code></pre> <p>But how do I do this in Swift?</p>
<p>You can do exactly the same call with Swift:</p> <h3>Swift 4 &amp; Swift 5</h3> <p>In Swift 4 String is a collection of <code>Character</code> values, it wasn't like this in Swift 2 and 3, so you can use this more concise code<sup>1</sup>:</p> <pre><code>let string = "hello Swift" if string.contains("Swift") { print("exists") } </code></pre> <h3>Swift 3.0+</h3> <pre><code>var string = "hello Swift" if string.range(of:"Swift") != nil { print("exists") } // alternative: not case sensitive if string.lowercased().range(of:"swift") != nil { print("exists") } </code></pre> <h3>Older Swift</h3> <pre><code>var string = "hello Swift" if string.rangeOfString("Swift") != nil{ println("exists") } // alternative: not case sensitive if string.lowercaseString.rangeOfString("swift") != nil { println("exists") } </code></pre> <p>I hope this is a helpful solution since some people, including me, encountered some strange problems by calling <code>containsString()</code>.<sup>1</sup></p> <p>PS. Don't forget to <code>import Foundation</code></p> <h3>Footnotes</h3> <ol> <li>Just remember that using collection functions on Strings has some <a href="https://developer.apple.com/documentation/swift/string#2905661" rel="noreferrer">edge cases</a> which can give you unexpected results, e. g. when dealing with emojis or other grapheme clusters like accented letters.</li> </ol>
{ "question_id": 24034043, "question_date": "2014-06-04T09:43:33.473Z", "question_score": 613, "tags": "swift|string|nsstring|substring", "answer_id": 24161872, "answer_date": "2014-06-11T11:34:08.413Z", "answer_score": 1207 }
Please answer the following Stack Overflow question: Title: Postgres could not connect to server <p>After I did <code>brew update</code> and <code>brew upgrade</code>, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well.</p> <p>This is the error message. (I also got this error message when I try to do <code>rake db:migrate</code>)</p> <pre class="lang-none prettyprint-override"><code>$ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket &quot;/tmp/.s.PGSQL.5432&quot;? </code></pre> <p>How can I solve it?</p> <p>Mac version: Mountain lion.</p> <p>homebrew version: 0.9.3</p> <p>postgres version: psql (PostgreSQL) 9.2.1</p> <p>And this is what I did:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$ brew uninstall postgresql Uninstalling /usr/local/Cellar/postgresql/9.2.1... $ brew uninstall postgresql Uninstalling /usr/local/Cellar/postgresql/9.1.4... $ psql --version bash: /usr/local/bin/psql: No such file or directory $ brew install postgresql ==&gt; Downloading http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2 Already downloaded: /Library/Caches/Homebrew/postgresql-9.2.1.tar.bz2 ...... ...... ==&gt; Summary /usr/local/Cellar/postgresql/9.2.1: 2814 files, 38M, built in 2.7 minutes $ initdb /usr/local/var/postgres -E utf8 The files belonging to this database system will be owned by user "laigary". This user must also own the server process. The database cluster will be initialized with locale "en_US.UTF-8". The default text search configuration will be set to "english". initdb: directory "/usr/local/var/postgres" exists but is not empty If you want to create a new database system, either remove or empty the directory "/usr/local/var/postgres" or run initdb with an argument other than "/usr/local/var/postgres". $ mkdir -p ~/Library/LaunchAgents $ cp /usr/local/Cellar/postgresql/9.2.1/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/ $ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist homebrew.mxcl.postgresql: Already loaded $ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start server starting $ env ARCHFLAGS="-arch x86_64" gem install pg Building native extensions. This could take a while... Successfully installed pg-0.14.1 1 gem installed $ psql --version psql (PostgreSQL) 9.2.1 $ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?</code></pre> </div> </div> </p> <p>Now, after I reinstalled homebrew, when I use <code>$ psql</code>, it doesn't show any error message.</p> <p>But I run <code>rake db:migrate</code> in my Rails app, it shows:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"? /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in &lt;top (required)&gt;' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in &lt;top (required)&gt;' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `call' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `each' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `execute' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:144:in `invoke' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `each' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:88:in `top_level' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:66:in `block in run' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling' /usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:63:in `run' /usr/local/bin/rake:32:in `&lt;main&gt;' Couldn't create database for {"adapter"=&gt;"postgresql", "encoding"=&gt;"unicode", "database"=&gt;"riy_development", "pool"=&gt;5, "username"=&gt;nil, "password"=&gt;nil}</code></pre> </div> </div> </p> <p><strong>Finally I've found a solution.</strong></p> <pre class="lang-sh prettyprint-override"><code>sudo mkdir /var/pgsql_socket/ sudo ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/ </code></pre> <p>This solution is a little tricky, but it works. Hope anyone has a better solution</p> <p><strong>Update</strong></p> <p>This works for me as well.</p> <pre class="lang-sh prettyprint-override"><code>rm /usr/local/var/postgres/postmaster.pid </code></pre>
<p>Had a similar problem; a pid file was blocking postgres from starting up. To fix it:</p> <pre><code>$ rm /usr/local/var/postgres/postmaster.pid $ brew services restart postgresql </code></pre> <p>and then all is well.</p> <hr /> <p><strong>UPDATE:</strong></p> <p>For <strong>Apple M1</strong> (Big Sur) users, do this instead:</p> <pre><code>$ rm /opt/homebrew/var/postgres/postmaster.pid $ brew services restart postgresql </code></pre>
{ "question_id": 13410686, "question_date": "2012-11-16T04:53:39.753Z", "question_score": 613, "tags": "ruby-on-rails|database|postgresql|macos|homebrew", "answer_id": 18832331, "answer_date": "2013-09-16T15:55:50.157Z", "answer_score": 1202 }
Please answer the following Stack Overflow question: Title: How to sum array of numbers in Ruby? <p>I have an array of integers.</p> <p>For example:</p> <pre><code>array = [123,321,12389] </code></pre> <p>Is there any nice way to get the sum of them?</p> <p>I know, that </p> <pre><code>sum = 0 array.each { |a| sum+=a } </code></pre> <p>would work.</p>
<p>Try this:</p> <pre><code>array.inject(0){ |sum, x| sum + x } </code></pre> <p><a href="https://ruby-doc.org/core/Enumerable.html#method-i-inject" rel="nofollow noreferrer">See Ruby's Enumerable Documentation</a></p> <p>(note: the <code>0</code> base case is needed so that <code>0</code> will be returned on an empty array instead of <code>nil</code>)</p>
{ "question_id": 1538789, "question_date": "2009-10-08T16:04:57.870Z", "question_score": 613, "tags": "ruby|arrays|math|sum", "answer_id": 1538801, "answer_date": "2009-10-08T16:07:04.170Z", "answer_score": 643 }
Please answer the following Stack Overflow question: Title: What is the equivalent of Java's final in C#? <p>What is the equivalent of Java's <code>final</code> in C#?</p>
<p>The <a href="http://en.wikipedia.org/wiki/Final_%28Java%29" rel="noreferrer"><code>final</code></a> keyword has several usages in Java. It corresponds to both the <a href="http://msdn.microsoft.com/en-us/library/88c54tsw.aspx" rel="noreferrer"><code>sealed</code></a> and <a href="http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx" rel="noreferrer"><code>readonly</code></a> keywords in C#, depending on the context in which it is used.</p> <h2>Classes</h2> <p>To prevent subclassing (inheritance from the defined class):</p> <p><strong>Java</strong></p> <pre class="lang-java prettyprint-override"><code>public final class MyFinalClass {...} </code></pre> <p><strong>C#</strong></p> <pre class="lang-cs prettyprint-override"><code>public sealed class MyFinalClass {...} </code></pre> <h2>Methods</h2> <p>Prevent overriding of a <code>virtual</code> method.</p> <p><strong>Java</strong></p> <pre class="lang-java prettyprint-override"><code>public class MyClass { public final void myFinalMethod() {...} } </code></pre> <p><strong>C#</strong></p> <pre class="lang-cs prettyprint-override"><code>public class MyClass : MyBaseClass { public sealed override void MyFinalMethod() {...} } </code></pre> <p>As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as <code>virtual</code>, whereas C# marks them as <code>sealed</code>. Hence, you only need to use the <code>sealed</code> keyword in C# if you want to stop further overriding of a method that has been explicitly marked <code>virtual</code> in the base class.</p> <h2>Variables</h2> <p>To only allow a variable to be assigned once:</p> <p><strong>Java</strong></p> <pre class="lang-java prettyprint-override"><code>public final double pi = 3.14; // essentially a constant </code></pre> <p><strong>C#</strong></p> <pre class="lang-cs prettyprint-override"><code>public readonly double pi = 3.14; // essentially a constant </code></pre> <p>As a side note, the effect of the <code>readonly</code> keyword differs from that of the <a href="http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx" rel="noreferrer"><code>const</code></a> keyword in that the <code>readonly</code> expression is evaluated at <em>runtime</em> rather than <em>compile-time</em>, hence allowing arbitrary expressions.</p>
{ "question_id": 1327544, "question_date": "2009-08-25T11:05:43.990Z", "question_score": 613, "tags": "c#|access-modifiers|reserved-words", "answer_id": 1327549, "answer_date": "2009-08-25T11:06:32.087Z", "answer_score": 924 }
Please answer the following Stack Overflow question: Title: Unnamed/anonymous namespaces vs. static functions <p>A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:</p> <pre><code>namespace { int cannotAccessOutsideThisFile() { ... } } // namespace </code></pre> <p>You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces <em>are</em> accessible within the file they're created in, as if you had an implicit using-clause to them.</p> <p>My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?</p>
<p><s>The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:</s> <s></p> <blockquote> <p>The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. </s></p> </blockquote> <p>Static only applies to names of objects, functions, and anonymous unions, not to type declarations.</p> <h2>Edit:</h2> <p>The decision to deprecate this use of the <code>static</code> keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1012" rel="noreferrer">ref</a>). In this case using a <code>static</code> or an unnamed <code>namespace</code> are back to being essentially two ways of doing the exact same thing. For more discussion please see <a href="https://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more">this</a> SO question.</p> <p>Unnamed <code>namespace</code>'s still have the advantage of allowing you to define translation-unit-local types. Please see <a href="https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static">this</a> SO question for more details.</p> <p>Credit goes to <a href="https://stackoverflow.com/users/1220179/mike-percy">Mike Percy</a> for bringing this to my attention.</p>
{ "question_id": 154469, "question_date": "2008-09-30T19:02:00.437Z", "question_score": 613, "tags": "c++|namespaces", "answer_id": 154482, "answer_date": "2008-09-30T19:06:19.613Z", "answer_score": 399 }
Please answer the following Stack Overflow question: Title: How to format an inline code in Confluence? <p>How can I format an <code>inline code</code> in Confluence <code>like this</code>? I mean, not a separate code block, but just inline <code>classname</code>, for example.</p>
<p>To insert inline monospace font in Confluence, surround the text in double curly-braces.</p> <p>This is an <code>{{example}}</code>.</p> <p>If you're using Confluence 4.x or higher, you can also just select the "Preformatted" option from the paragraph style menu. Please note that will apply to the <em>entire</em> line.</p> <p>Full reference <a href="https://confluence.atlassian.com/display/CONF56/Quick+Reference+Guide+for+the+Confluence+Editor" rel="noreferrer">here</a>.</p>
{ "question_id": 13104501, "question_date": "2012-10-27T21:51:28.920Z", "question_score": 613, "tags": "confluence", "answer_id": 13116392, "answer_date": "2012-10-29T05:38:23.807Z", "answer_score": 740 }
Please answer the following Stack Overflow question: Title: MongoDB relationships: embed or reference? <p>I'm new to MongoDB--coming from a relational database background. I want to design a question structure with some comments, but I don't know which relationship to use for comments: <code>embed</code> or <code>reference</code>?</p> <p>A question with some comments, like <a href="https://stackoverflow.com/">stackoverflow</a>, would have a structure like this:</p> <pre><code>Question title = 'aaa' content = bbb' comments = ??? </code></pre> <p>At first, I want to use embeded comments (I think <code>embed</code> is recommended in MongoDB), like this:</p> <pre><code>Question title = 'aaa' content = 'bbb' comments = [ { content = 'xxx', createdAt = 'yyy'}, { content = 'xxx', createdAt = 'yyy'}, { content = 'xxx', createdAt = 'yyy'} ] </code></pre> <p>It clear, but I'm worried about this case: <strong>If I want to edit a specified comment, how do I get its content and its question?</strong> There is no <code>_id</code> to let me find one, nor <code>question_ref</code> to let me find its question. (I'm so newbie, that I don't know if there's any way to do this without <code>_id</code> and <code>question_ref</code>.)</p> <p>Do I have to use <code>ref</code> not <code>embed</code>? Then I have to create a new collection for comments?</p>
<p>This is more an art than a science. The <a href="http://docs.mongodb.org/manual/data-modeling/" rel="noreferrer">Mongo Documentation on Schemas</a> is a good reference, but here are some things to consider:</p> <ul> <li><p>Put as much in as possible</p> <p>The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure (this means that you can take the part of the document that you need, so document size shouldn't worry you much) there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.</p> </li> <li><p>Separate data that can be referred to from multiple places into its own collection.</p> <p>This is not so much a &quot;storage space&quot; issue as it is a &quot;data consistency&quot; issue. If many records will refer to the same data it is more efficient and less error prone to update a single record and keep references to it in other places.</p> </li> <li><p>Document size considerations</p> <p>MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document. In a world of GB of data this sounds small, but it is also 30 thousand tweets or 250 typical Stack Overflow answers or 20 flicker photos. On the other hand, this is far more information than one might want to present at one time on a typical web page. First consider what will make your queries easier. In many cases concern about document sizes will be premature optimization.</p> </li> <li><p>Complex data structures:</p> <p>MongoDB can store arbitrary deep nested data structures, but cannot search them efficiently. If your data forms a tree, forest or graph, you effectively need to store each node and its edges in a separate document. (Note that there are data stores specifically designed for this type of data that one should consider as well)</p> <p>It has also <a href="http://seanhess.github.com/2012/02/01/mongodb_relational.html" rel="noreferrer">been pointed out</a> than it is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.</p> </li> <li><p>Data Consistency</p> <p>MongoDB makes a trade off between efficiency and consistency. The rule is changes to a single document are <strong>always</strong> <a href="https://stackoverflow.com/questions/52196678/what-are-atomic-operations-for-newbies">atomic</a>, while updates to multiple documents should never be assumed to be atomic. There is also no way to &quot;lock&quot; a record on the server (you can build this into the client's logic using for example a &quot;lock&quot; field). When you design your schema consider how you will keep your data consistent. Generally, the more that you keep in a document the better.</p> </li> </ul> <p>For what you are describing, I would embed the comments, and give each comment an id field with an ObjectID. The ObjectID has a time stamp embedded in it so you can use that instead of created at if you like.</p>
{ "question_id": 5373198, "question_date": "2011-03-21T02:19:21.610Z", "question_score": 613, "tags": "mongodb|reference|embed", "answer_id": 5373969, "answer_date": "2011-03-21T04:55:58.703Z", "answer_score": 864 }
Please answer the following Stack Overflow question: Title: Getting current date and time in JavaScript <p>I have a script that prints the current date and time in JavaScript, but the <code>DATE</code> is always wrong. Here is the code:</p> <pre><code>var currentdate = new Date(); var datetime = &quot;Last Sync: &quot; + currentdate.getDay() + &quot;/&quot; + currentdate.getMonth() + &quot;/&quot; + currentdate.getFullYear() + &quot; @ &quot; + currentdate.getHours() + &quot;:&quot; + currentdate.getMinutes() + &quot;:&quot; + currentdate.getSeconds(); </code></pre> <p>It should print <code>18/04/2012 15:07:33</code> and prints <code>3/3/2012 15:07:33</code></p>
<p><code>.getMonth()</code> returns a zero-based number so to get the correct month you need to add 1, so calling <code>.getMonth()</code> in may will return <code>4</code> and not <code>5</code>.</p> <p>So in your code we can use <code>currentdate.getMonth()+1</code> to output the correct value. In addition:</p> <ul> <li><code>.getDate()</code> returns the day of the month <strong>&lt;- this is the one you want</strong></li> <li><code>.getDay()</code> is a separate method of the <code>Date</code> object which will return an integer representing the current day of the week (0-6) <code>0 == Sunday</code> etc</li> </ul> <p>so your code should look like this:</p> <pre><code>var currentdate = new Date(); var datetime = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth()+1) + "/" + currentdate.getFullYear() + " @ " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); </code></pre> <hr> <blockquote> <p>JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances</p> </blockquote> <p>You can make use of the <code>Date</code> prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the <code>Date</code> object thus making it especially useful if you need to re-use this functionality.</p> <pre><code>// For todays date; Date.prototype.today = function () { return ((this.getDate() &lt; 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) &lt; 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear(); } // For the time now Date.prototype.timeNow = function () { return ((this.getHours() &lt; 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() &lt; 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() &lt; 10)?"0":"") + this.getSeconds(); } </code></pre> <p>You can then simply retrieve the date and time by doing the following:</p> <pre><code>var newDate = new Date(); var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow(); </code></pre> <p>Or call the method inline so it would simply be -</p> <pre><code>var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow(); </code></pre>
{ "question_id": 10211145, "question_date": "2012-04-18T14:08:44.027Z", "question_score": 612, "tags": "javascript|date|time|concatenation", "answer_id": 10211214, "answer_date": "2012-04-18T14:11:58.877Z", "answer_score": 722 }
Please answer the following Stack Overflow question: Title: Alphabet range in Python <p>How do I create a list of alphabet characters, without doing it manually like this?</p> <pre><code>['a', 'b', 'c', 'd', ..., 'z'] </code></pre>
<pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' &gt;&gt;&gt; list(string.ascii_lowercase) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] </code></pre> <hr /> <p>Alternatively, using <code>range</code>:</p> <pre><code>&gt;&gt;&gt; list(map(chr, range(97, 123))) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] </code></pre> <p>Or equivalently:</p> <pre><code>&gt;&gt;&gt; list(map(chr, range(ord('a'), ord('z')+1))) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] </code></pre> <hr /> <p>Other helpful <code>string</code> module features:</p> <pre><code>&gt;&gt;&gt; help(string) .... DATA ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!&quot;#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~ \t\n\r\x0b\x0c' punctuation = '!&quot;#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~' whitespace = ' \t\n\r\x0b\x0c' </code></pre>
{ "question_id": 16060899, "question_date": "2013-04-17T13:06:49.193Z", "question_score": 612, "tags": "python|string|list|alphabet", "answer_id": 16060908, "answer_date": "2013-04-17T13:07:13.743Z", "answer_score": 1108 }
Please answer the following Stack Overflow question: Title: What is the difference between Integrated Security = True and Integrated Security = SSPI? <p>I have two apps that use Integrated Security. One assigns <code>Integrated Security = true</code> in the connection string, and the other sets <code>Integrated Security = SSPI</code>.</p> <p>What is the difference between <code>SSPI</code> and <code>true</code> in the context of Integrated Security?</p>
<p>According to <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax" rel="noreferrer">Microsoft</a> they are the same thing.</p> <blockquote> <p>When <code>false</code>, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.<br> Recognized values are <code>true</code>, <code>false</code>, <code>yes</code>, <code>no</code>, and <code>sspi</code> (strongly recommended), which is equivalent to <code>true</code>.</p> </blockquote>
{ "question_id": 1229691, "question_date": "2009-08-04T20:15:32.283Z", "question_score": 612, "tags": "sql-server|security|connection-string|database-security", "answer_id": 1229745, "answer_date": "2009-08-04T20:23:53Z", "answer_score": 478 }
Please answer the following Stack Overflow question: Title: How can I get a recursive full-path listing, one line per file? <p>How can I get <code>ls</code> to spit out a flat list of recursive one-per-line paths?</p> <p>For example, I just want a flat listing of files with their full paths:</p> <pre><code>/home/dreftymac/. /home/dreftymac/foo.txt /home/dreftymac/bar.txt /home/dreftymac/stackoverflow /home/dreftymac/stackoverflow/alpha.txt /home/dreftymac/stackoverflow/bravo.txt /home/dreftymac/stackoverflow/charlie.txt </code></pre> <p><code>ls -a1</code> almost does what I need, but I do not want path fragments, I want full paths.</p>
<p>If you really want to use <code>ls</code>, then format its output using awk:</p> <pre><code>ls -R /path | awk ' /:$/&amp;&amp;f{s=$0;f=0} /:$/&amp;&amp;!f{sub(/:$/,"");s=$0;f=1;next} NF&amp;&amp;f{ print s"/"$0 }' </code></pre>
{ "question_id": 1767384, "question_date": "2009-11-19T23:39:07.333Z", "question_score": 612, "tags": "bash|command-line|find|ls", "answer_id": 1767559, "answer_date": "2009-11-20T00:20:17.780Z", "answer_score": 434 }
Please answer the following Stack Overflow question: Title: How to use 'cp' command to exclude a specific directory? <p>I want to copy all files in a directory except some files in a specific sub-directory. I have noticed that <code>cp</code> command didn't have the <code>--exclude</code> option. So, how can I achieve this?</p>
<p><code>rsync</code> is fast and easy:</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude </code></pre> <p>You can use <code>--exclude</code> multiples times.</p> <pre><code>rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude </code></pre> <p><strong>Note that the dir <code>thefoldertoexclude</code> after <code>--exclude</code> option is relative to the <code>sourcefolder</code>, i.e., <code>sourcefolder/thefoldertoexclude</code>.</strong></p> <p>Also you can add <code>-n</code> for dry run to see what will be copied before performing real operation, and if everything is ok, remove <code>-n</code> from command line.</p>
{ "question_id": 4585929, "question_date": "2011-01-03T15:53:52.997Z", "question_score": 612, "tags": "linux|bash|terminal|command|cp", "answer_id": 14789400, "answer_date": "2013-02-09T15:04:45.373Z", "answer_score": 1044 }
Please answer the following Stack Overflow question: Title: What's the difference between git clone --mirror and git clone --bare <p>The git clone help page has this to say about <code>--mirror</code>:</p> <blockquote> <p>Set up a mirror of the remote repository. This implies <code>--bare</code>.</p> </blockquote> <p>But doesn't go into detail about how the <code>--mirror</code> clone is different from a <code>--bare</code> clone.</p>
<p>The difference is that when using <code>--mirror</code>, <em>all</em> refs are copied <em>as-is</em>. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.</p> <p>The new <a href="https://git-scm.com/docs/git-clone#git-clone---mirror" rel="noreferrer">documentation</a> pretty much says all this:</p> <blockquote> <p><code>--mirror</code></p> <p>Set up a mirror of the source repository. This implies <code>--bare</code>. Compared to <code>--bare</code>, <code>--mirror</code> not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a <code>git remote update</code> in the target repository.</p> </blockquote> <p>My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for <code>HEAD</code>, while the bare clone copies the branches directly.</p> <p>Suppose origin has a few branches (<code>master (HEAD)</code>, <code>next</code>, <code>pu</code>, and <code>maint</code>), some tags (<code>v1</code>, <code>v2</code>, <code>v3</code>), some remote branches (<code>devA/master</code>, <code>devB/master</code>), and some other refs (<code>refs/foo/bar</code>, <code>refs/foo/baz</code>, which might be notes, stashes, other devs' namespaces, who knows). </p> <ul> <li><p><strong><code>git clone origin-url</code> (non-bare):</strong> You will get all of the tags copied, a local branch <code>master (HEAD)</code> tracking a remote branch <code>origin/master</code>, and remote branches <code>origin/next</code>, <code>origin/pu</code>, and <code>origin/maint</code>. The tracking branches are set up so that if you do something like <code>git fetch origin</code>, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.</p></li> <li><p><strong><code>git clone --bare origin-url</code>:</strong> You will get all of the tags copied, local branches <code>master (HEAD)</code>, <code>next</code>, <code>pu</code>, and <code>maint</code>, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.</p></li> <li><p><strong><code>git clone --mirror origin-url</code>:</strong> Every last one of those refs will be copied as-is. You'll get all the tags, local branches <code>master (HEAD)</code>, <code>next</code>, <code>pu</code>, and <code>maint</code>, remote branches <code>devA/master</code> and <code>devB/master</code>, other refs <code>refs/foo/bar</code> and <code>refs/foo/baz</code>. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run <code>git remote update</code> all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.</p></li> </ul>
{ "question_id": 3959924, "question_date": "2010-10-18T13:59:38.667Z", "question_score": 612, "tags": "git|git-clone", "answer_id": 3960063, "answer_date": "2010-10-18T14:14:50.150Z", "answer_score": 693 }
Please answer the following Stack Overflow question: Title: jQuery.click() vs onClick <p>I have a huge jQuery application, and I'm using the below two methods for click events.</p> <p><strong>First method</strong></p> <h3>HTML</h3> <pre><code>&lt;div id="myDiv"&gt;Some Content&lt;/div&gt; </code></pre> <h3>jQuery</h3> <pre><code>$('#myDiv').click(function(){ //Some code }); </code></pre> <p><strong>Second method</strong></p> <h3>HTML</h3> <pre><code>&lt;div id="myDiv" onClick="divFunction()"&gt;Some Content&lt;/div&gt; </code></pre> <h3>JavaScript function call</h3> <pre><code>function divFunction(){ //Some code } </code></pre> <p>I use either the first or second method in my application. Which one is better? Better for performance? And standard?</p>
<p>Using <code>$('#myDiv').click(function(){</code> is <strong>better</strong> as it follows standard event registration model. (jQuery <a href="https://github.com/jquery/jquery/blob/6e995583a11b63bf1d94142da6408955ee93e7cc/src/event.js#L97-102">internally</a> uses <a href="https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener"><code>addEventListener</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx"><code>attachEvent</code></a>). </p> <p>Basically registering an event in <a href="http://www.quirksmode.org/js/events_advanced.html">modern way</a> is the <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript">unobtrusive</a> way of handling events. Also to register more than one event listener for the target you can call <code>addEventListener()</code> for the same target. </p> <pre><code>var myEl = document.getElementById('myelement'); myEl.addEventListener('click', function() { alert('Hello world'); }, false); myEl.addEventListener('click', function() { alert('Hello world again!!!'); }, false); </code></pre> <p><a href="http://jsfiddle.net/aj55x/1/">http://jsfiddle.net/aj55x/1/</a> </p> <blockquote> <p><strong><a href="https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener#Why_use_addEventListener.3F">Why use addEventListener?</a></strong> (From MDN)</p> <p>addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:</p> <ul> <li>It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.</li> <li>It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)</li> <li>It works on any DOM element, not just HTML elements.</li> </ul> </blockquote> <p>More about Modern event registration -> <a href="http://www.quirksmode.org/js/events_advanced.html">http://www.quirksmode.org/js/events_advanced.html</a></p> <p>Other methods such as setting the <a href="https://developer.mozilla.org/en-US/docs/DOM/event#HTML_attribute">HTML attributes</a>, example: </p> <pre><code>&lt;button onclick="alert('Hello world!')"&gt; </code></pre> <p>Or <a href="https://developer.mozilla.org/en-US/docs/DOM/event#DOM_element_properties">DOM element properties</a>, example: </p> <pre><code>myEl.onclick = function(event){alert('Hello world');}; </code></pre> <p>are old and they can be over written easily. </p> <p><strong><em>HTML attribute</em></strong> should be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.</p> <p>The problem with the <strong><em>DOM element properties</em></strong> method is that only one event handler can be bound to an element per event.</p> <p>More about Traditional event handling -> <a href="http://www.quirksmode.org/js/events_tradmod.html">http://www.quirksmode.org/js/events_tradmod.html</a></p> <p>MDN Reference: <a href="https://developer.mozilla.org/en-US/docs/DOM/event">https://developer.mozilla.org/en-US/docs/DOM/event</a></p>
{ "question_id": 12627443, "question_date": "2012-09-27T18:02:02.273Z", "question_score": 611, "tags": "javascript|html|jquery|dom-events|jquery-events", "answer_id": 12627478, "answer_date": "2012-09-27T18:04:14.090Z", "answer_score": 605 }
Please answer the following Stack Overflow question: Title: How to find the foreach index? <p>Is it possible to find the <code>foreach</code> index?</p> <p>in a <code>for</code> loop as follows:</p> <pre><code>for ($i = 0; $i &lt; 10; ++$i) { echo $i . ' '; } </code></pre> <p><code>$i</code> will give you the index.</p> <p>Do I have to use the <code>for</code> loop or is there some way to get the index in the <code>foreach</code> loop?</p>
<pre><code>foreach($array as $key=&gt;$value) { // do stuff } </code></pre> <p><code>$key</code> is the index of each <code>$array</code> element</p>
{ "question_id": 141108, "question_date": "2008-09-26T18:23:15.413Z", "question_score": 611, "tags": "php|loops|foreach", "answer_id": 141114, "answer_date": "2008-09-26T18:24:33.833Z", "answer_score": 1127 }
Please answer the following Stack Overflow question: Title: What is the current directory in a batch file? <p>I want to create a few batch files to automate a program.</p> <p>My question is when I create the batch file, what is the current directory? Is it the directory where the file is located or is it the same directory that appears in the command prompt, or something else?</p>
<p>From within your batch file:</p> <ul> <li><code>%cd%</code> refers to the <a href="http://en.wikipedia.org/wiki/Working_directory" rel="noreferrer">current working directory</a> (variable)</li> <li><code>%~dp0</code> refers to the full path to the batch file's directory (static)</li> <li><code>%~dpnx0</code> and <code>%~f0</code> both refer to the full path to the batch directory and file name (static).</li> </ul> <p>See also: <a href="https://stackoverflow.com/questions/5034076/what-does-dp0-mean-and-how-does-it-work">What does %~dp0 mean, and how does it work?</a></p>
{ "question_id": 4419868, "question_date": "2010-12-12T00:54:59.493Z", "question_score": 611, "tags": "batch-file|directory", "answer_id": 4420078, "answer_date": "2010-12-12T02:09:54.813Z", "answer_score": 1189 }
Please answer the following Stack Overflow question: Title: What is a user agent stylesheet? <p>I'm working on a web page in Google Chrome. It displays correctly with the following styles.</p> <pre><code>table { display: table; border-collapse: separate; border-spacing: 2px; border-color: gray; } </code></pre> <p>It is important to note that I didn't define these styles. In Chrome developer tools, it says <strong>user agent stylesheet</strong> in place of the CSS file name.</p> <p>Now if I submit a form and some validation error occurs, I get the following stylesheet:</p> <pre><code>table { white-space: normal; line-height: normal; font-weight: normal; font-size: medium; font-variant: normal; font-style: normal; color: -webkit-text; text-align: -webkit-auto; } table { display: table; border-collapse: separate; border-spacing: 2px; border-color: gray; } </code></pre> <p>The <code>font-size</code> from these new styles is disturbing my design. Is there a way to force my stylesheets and if possible, completely overwrite Chrome's default stylesheet?</p>
<p>What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the <a href="https://meyerweb.com/eric/tools/css/reset/" rel="noreferrer">meyerweb CSS reset</a> or <a href="https://necolas.github.io/normalize.css/" rel="noreferrer">normalize.css</a>, to remove those defaults. Google "CSS reset vs normalize" to see the differences.</p>
{ "question_id": 12582624, "question_date": "2012-09-25T12:05:49.380Z", "question_score": 611, "tags": "css|google-chrome", "answer_id": 12582723, "answer_date": "2012-09-25T12:12:15.223Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: How to get a random number between a float range? <p><code>randrange(start, stop)</code> only takes integer arguments. So how would I get a random number between two float values?</p>
<p>Use <a href="http://docs.python.org/library/random.html#random.uniform" rel="noreferrer">random.uniform(a, b)</a>:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.uniform(1.5, 1.9) 1.8733202628557872 </code></pre>
{ "question_id": 6088077, "question_date": "2011-05-22T13:00:50.053Z", "question_score": 611, "tags": "python|random|floating-point", "answer_id": 6088092, "answer_date": "2011-05-22T13:04:33.973Z", "answer_score": 910 }
Please answer the following Stack Overflow question: Title: Begin, Rescue and Ensure in Ruby? <p>I've recently started programming in Ruby, and I am looking at exception handling.</p> <p>I was wondering if <code>ensure</code> was the Ruby equivalent of <code>finally</code> in C#? Should I have:</p> <pre><code>file = File.open("myFile.txt", "w") begin file &lt;&lt; "#{content} \n" rescue #handle the error here ensure file.close unless file.nil? end </code></pre> <p>or should I do this?</p> <pre><code>#store the file file = File.open("myFile.txt", "w") begin file &lt;&lt; "#{content} \n" file.close rescue #handle the error here ensure file.close unless file.nil? end </code></pre> <p>Does <code>ensure</code> get called no matter what, even if an exception isn't raised?</p>
<p>Yes, <code>ensure</code> ensures that the code is always evaluated. That's why it's called <code>ensure</code>. So, it is equivalent to Java's and C#'s <code>finally</code>.</p> <p>The general flow of <code>begin</code>/<code>rescue</code>/<code>else</code>/<code>ensure</code>/<code>end</code> looks like this:</p> <pre><code>begin # something which might raise an exception rescue SomeExceptionClass =&gt; some_variable # code that deals with some exception rescue SomeOtherException =&gt; some_other_variable # code that deals with some other exception else # code that runs only if *no* exception was raised ensure # ensure that this code always runs, no matter what # does not change the final value of the block end </code></pre> <p>You can leave out <code>rescue</code>, <code>ensure</code> or <code>else</code>. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from <code>StandardError</code> will be caught. (Please note that this does not mean that <em>all</em> exceptions are caught, because there are exceptions which are instances of <code>Exception</code> but not <code>StandardError</code>. Mostly very severe exceptions that compromise the integrity of the program such as <code>SystemStackError</code>, <code>NoMemoryError</code>, <code>SecurityError</code>, <code>NotImplementedError</code>, <code>LoadError</code>, <code>SyntaxError</code>, <code>ScriptError</code>, <code>Interrupt</code>, <code>SignalException</code> or <code>SystemExit</code>.)</p> <p>Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing</p> <pre><code>def foo begin # ... rescue # ... end end </code></pre> <p>you write just</p> <pre><code>def foo # ... rescue # ... end </code></pre> <p>or</p> <pre><code>def foo # ... ensure # ... end </code></pre> <p>The same applies to <code>class</code> definitions and <code>module</code> definitions.</p> <p>However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a <code>using</code> block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:</p> <pre><code># This is what you want to do: File.open('myFile.txt', 'w') do |file| file.puts content end # And this is how you might implement it: def File.open(filename, mode='r', perm=nil, opt=nil) yield filehandle = new(filename, mode, perm, opt) ensure filehandle&amp;.close end </code></pre> <p>And what do you know: this is <em>already</em> available in the core library as <code>File.open</code>. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la <code>using</code> in C#) or transactions or whatever else you might think of.</p> <p>The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.</p> <hr> <p>BTW: in modern C#, <code>using</code> is actually superfluous, because you can implement Ruby-style resource blocks yourself:</p> <pre><code>class File { static T open&lt;T&gt;(string filename, string mode, Func&lt;File, T&gt; block) { var handle = new File(filename, mode); try { return block(handle); } finally { handle.Dispose(); } } } // Usage: File.open("myFile.txt", "w", (file) =&gt; { file.WriteLine(contents); }); </code></pre>
{ "question_id": 2191632, "question_date": "2010-02-03T11:54:15.120Z", "question_score": 611, "tags": "ruby-on-rails|ruby|exception|exception-handling|error-handling", "answer_id": 2192010, "answer_date": "2010-02-03T13:04:35.493Z", "answer_score": 1291 }
Please answer the following Stack Overflow question: Title: How to distinguish between left and right mouse click with jQuery <p>How do you obtain the clicked mouse button using jQuery?</p> <pre><code>$('div').bind('click', function(){ alert('clicked'); }); </code></pre> <p>this is triggered by both right and left click, what is the way of being able to catch right mouse click? I'd be happy if something like below exists:</p> <pre><code>$('div').bind('rightclick', function(){ alert('right mouse button is pressed'); }); </code></pre>
<p>As of jQuery version 1.1.3, <code>event.which</code> normalizes <code>event.keyCode</code> and <code>event.charCode</code> so you don't have to worry about browser compatibility issues. <a href="http://api.jquery.com/event.which/" rel="noreferrer">Documentation on <code>event.which</code></a></p> <p><code>event.which</code> will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:</p> <pre><code>$('#element').mousedown(function(event) { switch (event.which) { case 1: alert('Left Mouse button pressed.'); break; case 2: alert('Middle Mouse button pressed.'); break; case 3: alert('Right Mouse button pressed.'); break; default: alert('You have a strange Mouse!'); } }); </code></pre>
{ "question_id": 1206203, "question_date": "2009-07-30T12:11:20.370Z", "question_score": 611, "tags": "javascript|jquery|jquery-events|right-click", "answer_id": 2725963, "answer_date": "2010-04-27T23:52:26.963Z", "answer_score": 942 }
Please answer the following Stack Overflow question: Title: Undo git update-index --assume-unchanged <file> <p>I have run the following command to ignore watching/tracking a particular directory/file:</p> <pre><code>git update-index --assume-unchanged &lt;file&gt; </code></pre> <p>How can I undo this, so that <code>&lt;file&gt;</code> is watched/tracked again?</p>
<p><strong>To get undo/show dir's/files that are set to assume-unchanged run this</strong>:</p> <pre><code>git update-index --no-assume-unchanged &lt;file&gt; </code></pre> <p><strong>To get a list of dir's/files that are <code>assume-unchanged</code> run this</strong>:</p> <pre><code>git ls-files -v|grep '^h' </code></pre>
{ "question_id": 17195861, "question_date": "2013-06-19T15:57:09.280Z", "question_score": 611, "tags": "git|version-control|git-index", "answer_id": 17195901, "answer_date": "2013-06-19T15:58:36.427Z", "answer_score": 780 }
Please answer the following Stack Overflow question: Title: Do you use source control for your database items? <p>I feel that my shop has a hole because we don't have a solid process in place for versioning our database schema changes. We do a lot of backups so we're more or less covered, but it's bad practice to rely on your last line of defense in this way. </p> <p>Surprisingly, this seems to be a common thread. Many shops I have spoken to ignore this issue because their databases don't change often, and they basically just try to be meticulous.</p> <p>However, I know how that story goes. It's only a matter of time before things line up just wrong and something goes missing. </p> <p>Are there any best practices for this? What are some strategies that have worked for you? </p>
<p>Must read <a href="http://blog.codinghorror.com/get-your-database-under-version-control/" rel="noreferrer">Get your database under version control</a>. Check the series of posts by K. Scott Allen.</p> <blockquote> <p>When it comes to version control, the database is often a second or even third-class citizen. From what I've seen, teams that would never think of writing code without version control in a million years-- and rightly so-- can somehow be completely oblivious to the need for version control around the critical databases their applications rely on. I don't know how you can call yourself a software engineer and maintain a straight face when your database isn't under exactly the same rigorous level of source control as the rest of your code. Don't let this happen to you. Get your database under version control.</p> </blockquote>
{ "question_id": 115369, "question_date": "2008-09-22T15:07:33.273Z", "question_score": 611, "tags": "database|version-control", "answer_id": 115382, "answer_date": "2008-09-22T15:09:55.827Z", "answer_score": 397 }
Please answer the following Stack Overflow question: Title: Install an apk file from command prompt? <p>I want to install a file using the Windows command line. First I want to build after compiling all the .jar files to create an .apk file for an Android application without using Eclipse.</p> <p>Does anyone know how this can be done without the use of Eclipse &amp; only by making use of command line.</p>
<p>You can use the code below to install application from command line</p> <pre><code>adb install example.apk </code></pre> <p>this apk is installed in the internal memory of current opened emulator.</p> <pre><code>adb install -s example.apk </code></pre> <p>this apk is installed in the sd-card of current opened emulator.</p> <p>You can also install an apk to specific device in connected device list to the adb.</p> <pre><code>adb -s emulator-5554 install myapp.apk </code></pre> <p>Refer also to <a href="http://developer.android.com/tools/help/adb.html#shellcommands"><strong>adb help</strong></a> for other options.</p>
{ "question_id": 7076240, "question_date": "2011-08-16T09:38:32.617Z", "question_score": 610, "tags": "android|cmd|apk", "answer_id": 7076679, "answer_date": "2011-08-16T10:20:21.307Z", "answer_score": 939 }
Please answer the following Stack Overflow question: Title: How to rename a file using Python <p>I want to change <code>a.txt</code> to <code>b.kml</code>.</p>
<p>Use <a href="http://docs.python.org/library/os.html#os.rename" rel="noreferrer"><code>os.rename</code></a>:</p> <pre><code>import os os.rename('a.txt', 'b.kml') </code></pre> <p>Usage:</p> <pre><code>os.rename('from.extension.whatever','to.another.extension') </code></pre>
{ "question_id": 2491222, "question_date": "2010-03-22T09:59:23.517Z", "question_score": 610, "tags": "python|file-rename", "answer_id": 2491232, "answer_date": "2010-03-22T10:00:52.207Z", "answer_score": 952 }
Please answer the following Stack Overflow question: Title: How do I measure execution time of a command on the Windows command line? <p>Is there a built-in way to measure execution time of a command on the Windows command line?</p>
<p>If you are using Windows 2003 (note that windows server 2008 and later are not supported) you can use The Windows Server 2003 Resource Kit, which contains timeit.exe that displays detailed execution stats. Here is an example, timing the command &quot;timeit -?&quot;:</p> <pre><code>C:\&gt;timeit timeit -? Invalid switch -? Usage: TIMEIT [-f filename] [-a] [-c] [-i] [-d] [-s] [-t] [-k keyname | -r keyname] [-m mask] [commandline...] where: -f specifies the name of the database file where TIMEIT keeps a history of previous timings. Default is .\timeit.dat -k specifies the keyname to use for this timing run -r specifies the keyname to remove from the database. If keyname is followed by a comma and a number then it will remove the slowest (positive number) or fastest (negative) times for that keyname. -a specifies that timeit should display average of all timings for the specified key. -i specifies to ignore non-zero return codes from program -d specifies to show detail for average -s specifies to suppress system wide counters -t specifies to tabular output -c specifies to force a resort of the data base -m specifies the processor affinity mask Version Number: Windows NT 5.2 (Build 3790) Exit Time: 7:38 am, Wednesday, April 15 2009 Elapsed Time: 0:00:00.000 Process Time: 0:00:00.015 System Calls: 731 Context Switches: 299 Page Faults: 515 Bytes Read: 0 Bytes Written: 0 Bytes Other: 298 </code></pre> <p>You can get TimeIt in the Windows 2003 Resource Kit. It's not available for direct download from the Microsoft Download Center, but one can still get it from the <a href="http://web.archive.org/web/20150327014146/http://www.microsoft.com/en-us/download/details.aspx?id=17657" rel="nofollow noreferrer" title="Windows 2003 Resource Kit">archive.org - Windows Server 2003 Resource Kit Tools</a>.</p>
{ "question_id": 673523, "question_date": "2009-03-23T14:13:43.520Z", "question_score": 610, "tags": "windows|batch-file|time|cmd|windows-server-2003", "answer_id": 752307, "answer_date": "2009-04-15T15:44:29.010Z", "answer_score": 118 }
Please answer the following Stack Overflow question: Title: How do you create a custom AuthorizeAttribute in ASP.NET Core? <p>I'm trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was possible to override <code>bool AuthorizeCore(HttpContextBase httpContext)</code>. But this no longer exists in <a href="https://github.com/aspnet/Security/blob/3a8ea672eae590785a78d74777abb76bb9664130/src/Microsoft.AspNet.Authorization/AuthorizeAttribute.cs"><code>AuthorizeAttribute</code></a>.</p> <p>What is the current approach to make a custom AuthorizeAttribute?</p> <p>What I am trying to accomplish: I am receiving a session ID in the Header Authorization. From that ID I'll know whether a particular action is valid.</p>
<p>The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/" rel="noreferrer">here</a>. The basic idea behind the new approach is to use the new <code>[Authorize]</code> attribute to designate a &quot;policy&quot; (e.g. <code>[Authorize( Policy = &quot;YouNeedToBe18ToDoThis&quot;)]</code> where the policy is registered in the application's <code>Startup.cs</code> to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).</p> <p>The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources (&quot;CanCreateOrder&quot;, &quot;CanReadOrder&quot;, &quot;CanUpdateOrder&quot;, &quot;CanDeleteOrder&quot;, etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. <code>options.AddPolicy(&quot;CanUpdateOrder&quot;, policy =&gt; policy.RequireClaim(MyClaimTypes.Permission, &quot;CanUpdateOrder));</code>), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.</p> <p>While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.</p> <p>The following is an implementation which uses the <code>IAuthorizationFilter</code> to provide a simple way to express a claim requirement for a given controller or action:</p> <pre><code>public class ClaimRequirementAttribute : TypeFilterAttribute { public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter)) { Arguments = new object[] {new Claim(claimType, claimValue) }; } } public class ClaimRequirementFilter : IAuthorizationFilter { readonly Claim _claim; public ClaimRequirementFilter(Claim claim) { _claim = claim; } public void OnAuthorization(AuthorizationFilterContext context) { var hasClaim = context.HttpContext.User.Claims.Any(c =&gt; c.Type == _claim.Type &amp;&amp; c.Value == _claim.Value); if (!hasClaim) { context.Result = new ForbidResult(); } } } [Route(&quot;api/resource&quot;)] public class MyController : Controller { [ClaimRequirement(MyClaimTypes.Permission, &quot;CanReadResource&quot;)] [HttpGet] public IActionResult GetResource() { return Ok(); } } </code></pre>
{ "question_id": 31464359, "question_date": "2015-07-16T20:55:54.477Z", "question_score": 610, "tags": "c#|asp.net-core|asp.net-core-mvc|authorization", "answer_id": 41348219, "answer_date": "2016-12-27T15:54:44.797Z", "answer_score": 659 }
Please answer the following Stack Overflow question: Title: If REST applications are supposed to be stateless, how do you manage sessions? <p>I'm in need of some clarification. I've been reading about REST, and building RESTful applications. According to wikipedia, REST itself is defined to be <em>Representational State Transfer</em>. I therefore don't understand all this stateless <em>gobbledeygook</em> that everyone keeps spewing.</p> <p>From wikipedia:</p> <blockquote> <p>At any particular time, a client can either be in transition between application states or &quot;at rest&quot;. A client in a rest state is able to interact with its user, but creates no load and consumes no per-client storage on the set of servers or on the network.</p> </blockquote> <p>Are they just saying don't use session/application level data store???</p> <p>I get that one goal of REST is to make URI access consistent and available, for instance, instead of hiding paging requests inside posts, making the page number of a request a part of the GET URI. Makes sense to me. But it seems like it is just going overboard saying that <em>no per client data</em> (session data) should ever be stored server side.</p> <p>What if I had a queue of messages, and my user wanted to read the messages, but as he read them, wanted to block certain senders messages coming through for the duration of his session? Wouldn't it make sense to store this in a place on the server side, and have the server only send messages (or message ID's) that were not blocked by the user?</p> <p>Do I really have to send the entire list of message senders to block each time I request the new message list? The message list pertinent to me wouldn't/shouldn't even be a publicly available resource in the first place..</p> <p>Again, just trying to understand this. Someone <em>please</em> clarify.</p> <hr /> <p><strong>Update:</strong></p> <p>I have found a stack overflow question that has an answer that doesn't quite get me all the way there: <a href="https://stackoverflow.com/questions/2641901/how-to-manage-state-in-rest">How to manage state in REST</a> which says that the client state that is important <em>should</em> all be transferred on every request.... Ugg.. seems like a lot of overhead... Is this right??</p>
<h3>The fundamental explanation is:</h3> <blockquote> <p>No client session state on the server.</p> </blockquote> <p>By stateless it means that the <strong>server</strong> does not store any state about the <strong>client session</strong> on the server side.</p> <p>The <em>client session</em> is stored on the client. The server is stateless means that every server can service any client at any time, there is no <em>session affinity</em> or <em>sticky sessions</em>. The relevant session information is stored on the client and passed to the server as needed.</p> <p>That does not preclude other services that the web server talks to from maintaining state about business objects such as shopping carts, just not about the client's current application/session state.</p> <p>The <strong>client's</strong> application state should never be stored on the server, but passed around from the <strong>client</strong> to every place that needs it.</p> <p>That is where the <em>ST</em> in <em>REST</em> comes from, <em>State Transfer</em>. You transfer the state around instead of having the server store it. <strong>This is the only way to scale to millions of concurrent users.</strong> If for no other reason than because millions of sessions is millions of sessions.</p> <p>The load of session management is amortized across all the clients, the clients store their session state and the servers can service many orders of magnitude or more clients in a stateless fashion.</p> <p>Even for a service that you think will <em>only</em> need in the 10's of thousands of concurrent users, you still should make your service stateless. Tens of thousands is still tens of thousands and there will be time and space cost associated with it.</p> <p>Stateless is how the HTTP protocol and the web in general was designed to operate and is an overall simpler implementation and you have a single code path instead of a bunch of server side logic to maintain a bunch of session state.</p> <h3>There are some very basic implementation principles:</h3> <p>These are principles not implementations, how you meet these principles may vary.</p> <p>In summary, the <a href="https://www.infoq.com/articles/rest-introduction" rel="noreferrer">five key principles</a> are:</p> <ol> <li>Give every “thing” an ID</li> <li>Link things together</li> <li>Use standard methods</li> <li>Resources with multiple representations</li> <li>Communicate statelessly</li> </ol> <h3>There is nothing about authentication or authorization in the REST <a href="https://www.ics.uci.edu/%7Efielding/pubs/dissertation/rest_arch_style.htm" rel="noreferrer">dissertation</a>.</h3> <p>Because there is nothing different from authenticating a request that is RESTful from one that is not. Authentication is irrelevant to the RESTful discussion.</p> <p>Explaining how to create a stateless application for your particular requirements, is <em>too-broad</em> for StackOverflow.</p> <p>Implementing Authentication and Authorization as it pertains to REST is even more so <em>too-broad</em> and various approaches to implementations are explained in great detail on the internet in general.</p> <blockquote> <p><strong>Comments asking for help/info on this will/should just be flagged as <em>No Longer Needed</em></strong>.</p> </blockquote>
{ "question_id": 3105296, "question_date": "2010-06-23T20:30:57.247Z", "question_score": 610, "tags": "rest|session-state", "answer_id": 3105337, "answer_date": "2010-06-23T20:35:57.983Z", "answer_score": 546 }
Please answer the following Stack Overflow question: Title: Can I add extension methods to an existing static class? <p>I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as <code>Console</code>.</p> <p>For example, if I want to add an extension to <code>Console</code>, called '<code>WriteBlueLine</code>', so that I can go:</p> <pre><code>Console.WriteBlueLine(&quot;This text is blue&quot;); </code></pre> <p>I tried this by adding a local, public static method, with <code>Console</code> as a '<code>this</code>' parameter... but no dice!</p> <pre><code>public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } </code></pre> <p>This didn't add a '<code>WriteBlueLine</code>' method to <code>Console</code>... am I doing it wrong? Or asking for the impossible?</p>
<p>No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the <code>ConfigurationManager</code> interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.</p> <pre><code> public static class ConfigurationManagerWrapper { public static ConfigurationSection GetSection( string name ) { return ConfigurationManager.GetSection( name ); } ..... public static ConfigurationSection GetWidgetSection() { return GetSection( "widgets" ); } } </code></pre>
{ "question_id": 249222, "question_date": "2008-10-30T03:54:04.407Z", "question_score": 610, "tags": "c#|static|extension-methods", "answer_id": 309414, "answer_date": "2008-11-21T16:44:56.610Z", "answer_score": 318 }
Please answer the following Stack Overflow question: Title: How do I create a folder in a GitHub repository? <p>I want to create a folder in a GitHub repository and want to add files in that folder. How do I achieve this?</p>
<p><strong>TL;DR</strong> Use <code>/</code> in the file name field to create folder(s), e.g. typing <code>folder1/file1</code> in the file name field will create a folder <code>folder1</code> and a file <code>file1</code>.</p> <p><strong>Original answer</strong><br /> You cannot create an empty folder <em>and then</em> add files to that folder, but rather creation of a folder must happen <em>together with</em> adding of at least a single file. This is because git doesn't track empty folders.</p> <p>On GitHub you can do it this way:</p> <ul> <li>Go to the folder inside which you want to create another folder</li> <li>Click on <em>New file</em></li> <li>On the text field for the file name, first write the folder name you want to create</li> <li><strong>Then type <code>/</code></strong>. This creates a folder</li> <li>You can add more folders similarly</li> <li>Finally, give the new file a name (for example, <code>.gitkeep</code> which is <a href="https://stackoverflow.com/a/7229996"><em>conventionally</em></a> used to make Git track otherwise empty folders; it is not a Git feature though)</li> <li>Finally, click <em>Commit new file</em>.</li> </ul>
{ "question_id": 12258399, "question_date": "2012-09-04T07:08:28.013Z", "question_score": 609, "tags": "github|github-services", "answer_id": 34259067, "answer_date": "2015-12-14T02:53:47.943Z", "answer_score": 519 }
Please answer the following Stack Overflow question: Title: Run R script from command line <p>I have a file, called <code>a.r</code>, it has a <code>chmod</code> of 755,</p> <pre><code>sayHello &lt;- function(){ print('hello') } sayHello() </code></pre> <p>How can I run this via command-line?</p>
<p>If you want the output to print to the terminal it is best to use Rscript</p> <pre><code>Rscript a.R </code></pre> <p>Note that when using <code>R CMD BATCH a.R</code> that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.</p> <pre><code>R CMD BATCH a.R # Check the output cat a.Rout </code></pre> <p>One other thing to note about using Rscript is that it doesn't load the <code>methods</code> package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.</p> <p>If you really want to use the <code>./a.R</code> way of calling the script you could add an appropriate <code>#!</code> to the top of the script</p> <pre><code>#!/usr/bin/env Rscript sayHello &lt;- function(){ print('hello') } sayHello() </code></pre> <p>I will also note that if you're running on a *unix system there is the useful <a href="https://cran.r-project.org/package=littler" rel="noreferrer">littler</a> package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found <a href="https://stackoverflow.com/q/31526013/1169233">in this question</a>.</p>
{ "question_id": 18306362, "question_date": "2013-08-19T04:23:21.660Z", "question_score": 609, "tags": "r|command-line", "answer_id": 18306656, "answer_date": "2013-08-19T05:01:06.970Z", "answer_score": 806 }
Please answer the following Stack Overflow question: Title: Test if a vector contains a given element <p>How to check if a vector contains a given value?</p>
<p>Both the <code>match()</code> (returns the first appearance) and <code>%in%</code> (returns a Boolean) functions are designed for this.</p> <pre><code>v &lt;- c('a','b','c','e') 'b' %in% v ## returns TRUE match('b',v) ## returns the first location of 'b', in this case: 2 </code></pre>
{ "question_id": 1169248, "question_date": "2009-07-23T02:20:53.340Z", "question_score": 609, "tags": "r|vector|r-faq", "answer_id": 1169262, "answer_date": "2009-07-23T02:25:24.957Z", "answer_score": 576 }
Please answer the following Stack Overflow question: Title: How to check for an undefined or null variable in JavaScript? <p>We are frequently using the following code pattern in our JavaScript code</p> <pre><code>if (typeof(some_variable) != 'undefined' &amp;&amp; some_variable != null) { // Do something with some_variable } </code></pre> <p>Is there a less verbose way of checking that has the same effect?</p> <p>According to some forums and literature saying simply the following should have the same effect.</p> <pre><code>if (some_variable) { // Do something with some_variable } </code></pre> <p>Unfortunately, <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> evaluates such a statement as error on runtime when <code>some_variable</code> is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?</p>
<p>You have to differentiate between cases:</p> <ol> <li>Variables can be <code>undefined</code> or <em>undeclared</em>. You'll get an error if you access an undeclared variable in any context other than <code>typeof</code>.</li> </ol> <pre><code>if(typeof someUndeclaredVar == whatever) // works if(someUndeclaredVar) // throws error </code></pre> <p>A variable that has been declared but not initialized is <code>undefined</code>.</p> <pre><code>let foo; if (foo) //evaluates to false because foo === undefined </code></pre> <ol start="2"> <li><p>Undefined <em>properties</em> , like <code>someExistingObj.someUndefProperty</code>. An undefined property doesn't yield an error and simply returns <code>undefined</code>, which, when converted to a boolean, evaluates to <code>false</code>. So, if you don't care about <code>0</code> and <code>false</code>, using <code>if(obj.undefProp)</code> is ok. There's a common idiom based on this fact:</p> <pre><code>value = obj.prop || defaultValue </code></pre> <p>which means "if <code>obj</code> has the property <code>prop</code>, assign it to <code>value</code>, otherwise assign the default value <code>defautValue</code>".</p> <p>Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator" rel="noreferrer"><code>in</code></a> operator instead</p> <pre><code>value = ('prop' in obj) ? obj.prop : defaultValue </code></pre></li> </ol>
{ "question_id": 2559318, "question_date": "2010-04-01T09:17:18.953Z", "question_score": 609, "tags": "javascript|null|undefined", "answer_id": 2559513, "answer_date": "2010-04-01T09:54:29.213Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: How to check if a file exists in Go? <p>Go's standard library does not have a function solely intended to check if a file exists or not (like Python's <a href="http://docs.python.org/library/os.path.html#os.path.exists" rel="noreferrer"><code>os.path.exists</code></a>). What is the <strong>idiomatic</strong> way to do it?</p>
<p>To check if a file doesn't exist, equivalent to Python's <code>if not os.path.exists(filename)</code>:</p> <pre><code>if _, err := os.Stat(&quot;/path/to/whatever&quot;); errors.Is(err, os.ErrNotExist) { // path/to/whatever does not exist } </code></pre> <p>To check if a file exists, equivalent to Python's <code>if os.path.exists(filename)</code>:</p> <p>Edited: per recent comments</p> <pre><code>if _, err := os.Stat(&quot;/path/to/whatever&quot;); err == nil { // path/to/whatever exists } else if errors.Is(err, os.ErrNotExist) { // path/to/whatever does *not* exist } else { // Schrodinger: file may or may not exist. See err for details. // Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence } </code></pre>
{ "question_id": 12518876, "question_date": "2012-09-20T18:42:02.137Z", "question_score": 609, "tags": "file|go|standard-library", "answer_id": 12518877, "answer_date": "2012-09-20T18:42:02.137Z", "answer_score": 940 }
Please answer the following Stack Overflow question: Title: Is it possible to have placeholders in strings.xml for runtime values? <p>Is it possible to have placeholders in string values in <code>string.xml</code> that can be assigned values at run time?</p> <p>Example:</p> <blockquote> <p>some string <strong>PLACEHOLDER1</strong> some more string</p> </blockquote>
<h3>Formatting and Styling</h3> <p>Yes, see the following from <a href="http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling" rel="noreferrer">String Resources: Formatting and Styling</a></p> <blockquote> <p>If you need to format your strings using <code>String.format(String, Object...)</code>, then you can do so by putting your format arguments in the string resource. For example, with the following resource:</p> <pre><code>&lt;string name="welcome_messages"&gt;Hello, %1$s! You have %2$d new messages.&lt;/string&gt; </code></pre> <p>In this example, the format string has two arguments: <code>%1$s</code> is a string and <code>%2$d</code> is a decimal number. You can format the string with arguments from your application like this:</p> <pre><code>Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); </code></pre> </blockquote> <h3>Basic Usage</h3> <p>Note that <code>getString</code> has an overload that uses the string as a format string:</p> <pre><code>String text = res.getString(R.string.welcome_messages, username, mailCount); </code></pre> <h3>Plurals</h3> <p>If you need to handle plurals, use this:</p> <pre><code>&lt;plurals name="welcome_messages"&gt; &lt;item quantity="one"&gt;Hello, %1$s! You have a new message.&lt;/item&gt; &lt;item quantity="other"&gt;Hello, %1$s! You have %2$d new messages.&lt;/item&gt; &lt;/plurals&gt; </code></pre> <p>The first <code>mailCount</code> param is used to decide which format to use (single or plural), the other params are your substitutions:</p> <pre><code>Resources res = getResources(); String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount); </code></pre> <p>See <a href="http://developer.android.com/guide/topics/resources/string-resource.html#Plurals" rel="noreferrer">String Resources: Plurals</a> for more details.</p>
{ "question_id": 3656371, "question_date": "2010-09-07T06:55:03.310Z", "question_score": 609, "tags": "android|string|string-formatting|android-resources", "answer_id": 3656409, "answer_date": "2010-09-07T07:01:34.260Z", "answer_score": 1211 }
Please answer the following Stack Overflow question: Title: Express.js - app.listen vs server.listen <p>This may be a very basic question but I simply don't get it. What is the difference between creating an app using <em>Express.js</em> and starting the app listening on port 1234, for example:</p> <pre><code>var express = require('express'); var app = express(); //app.configure, app.use etc app.listen(1234); </code></pre> <p>and adding an http server:</p> <pre><code>var express = require('express'); var http = require('http'); var app = express(); var server = http.createServer(app); //app.configure, app.use etc server.listen(1234); </code></pre> <p>What's the difference?<br> If I navigate to <code>http://localhost:1234</code>, thus I get the same output.</p>
<p>The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run <code>socket.io</code> within the same HTTP server instance:</p> <pre><code>var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); ... server.listen(1234); </code></pre> <p>However, <code>app.listen()</code> also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:</p> <pre><code>var express = require('express'); var app = express(); // app.use/routes/etc... var server = app.listen(3033); var io = require('socket.io').listen(server); io.sockets.on('connection', function (socket) { ... }); </code></pre>
{ "question_id": 17696801, "question_date": "2013-07-17T10:01:51.163Z", "question_score": 609, "tags": "node.js|express|server", "answer_id": 17697134, "answer_date": "2013-07-17T10:18:49.460Z", "answer_score": 714 }
Please answer the following Stack Overflow question: Title: What are some resources for getting started in operating system development? <p>One thing I've always wanted to do is develop my very own operating system (not necessarily fancy like Linux or Windows, but better than a simple boot loader which I've already done).</p> <p>I'm having a hard time finding resources/guides that take you past writing a simple &quot;Hello World&quot; OS.</p> <p>I know lots of people will probably recommend I look at Linux or BSD; but the code base for systems like that is (presumably) so big that I wouldn't know where to start.</p> <p>Any suggestions?</p> <p>Update: To make it easier for people who land on this post through Google here are some OS development resources:</p> <ul> <li><p><a href="https://web.archive.org/web/20120506110242/http://osix.net/modules/article/?id=359" rel="noreferrer">Writing Your Own Operating System</a> (Thanks Adam)</p> </li> <li><p><a href="http://www.linuxfromscratch.org/" rel="noreferrer">Linux From Scratch</a> (Thanks John)</p> </li> <li><p><a href="http://en.wikipedia.org/wiki/SharpOS_(operating_system)" rel="noreferrer">SharpOS (C# Operating System)</a> (Thanks lomaxx)</p> </li> <li><p><a href="http://www.minix3.org/" rel="noreferrer">Minix3</a> and <a href="http://minix1.woodhull.com/mxdownld.html" rel="noreferrer">Minix2</a> (Thanks Mike)</p> </li> <li><p><a href="http://wiki.osdev.org/Main_Page" rel="noreferrer">OS Dev Wiki</a> and <a href="http://forum.osdev.org/" rel="noreferrer">Forums</a> (Thanks Steve)</p> </li> <li><p><a href="http://www.osdever.net/" rel="noreferrer">BonaFide</a> (Thanks Steve)</p> </li> <li><p><a href="http://osdever.net/bkerndev/Docs/intro.htm" rel="noreferrer">Bran</a> (Thanks Steve)</p> </li> <li><p><a href="http://www.jamesmolloy.co.uk/tutorial_html/index.html" rel="noreferrer">Roll your own toy UNIX-clone OS</a> (Thanks Steve)</p> </li> <li><p><a href="http://www.brokenthorn.com/Resources/OSDevIndex.html" rel="noreferrer">Broken Thorn OS Development Series</a></p> </li> </ul> <p>Other resources:</p> <p>I found a nice resource named <a href="http://mikeos.berlios.de/" rel="noreferrer">MikeOS</a>, &quot;MikeOS is a learning tool to demonstrate how simple OSes work. It uses 16-bit real mode for BIOS access, so that it doesn't need complex drivers&quot;</p> <p><em>Updated 11/14/08</em></p> <p>I found some resources at <a href="http://www.freebyte.com/operatingsystems/#osprojects" rel="noreferrer">Freebyte's Guide to...Free and non-free Operating Systems</a> that links to kits such as OSKit and ExOS library. These seem super useful in getting started in OS development.</p> <p><em>Updated 2/23/09</em></p> <p><a href="https://stackoverflow.com/users/42019/ric-tokyo">Ric Tokyo</a> recommended <a href="http://code.google.com/p/nanoos/" rel="noreferrer">nanoos</a> in this <a href="https://stackoverflow.com/questions/580308/making-an-os-in-c/580362#580362">question</a>. Nanoos is an OS written in C++.</p> <p><em>Updated 3/9/09</em></p> <p>Dinah provided some useful Stack Overflow discussion of aspiring OS developers: <a href="https://stackoverflow.com/questions/340674/roadblocks-in-creating-a-custom-operating-system">Roadblocks in creating a custom operating system</a> discusses what pitfalls you might encounter while developing an OS and <a href="https://stackoverflow.com/questions/130065/os-development">OS Development</a> is a more general discussion.</p> <p><em>Updated 7/9/09</em></p> <p>LB provided a link to the <a href="http://www.scs.stanford.edu/07au-cs140/pintos/pintos.html" rel="noreferrer">Pintos Project</a>, an education OS designed for students learning OS development.</p> <p><em>Updated 7/27/09 (Still going strong!)</em></p> <p>I stumbled upon an <a href="http://academicearth.org/courses/operating-systems-and-system-programming" rel="noreferrer">online OS course</a> from Berkley featuring 23 lectures.</p> <p><a href="http://tomos.sourceforge.net/" rel="noreferrer">TomOS</a> is a fork of <a href="http://mikeos.berlios.de/" rel="noreferrer">MikeOS</a> that includes a little memory manager and mouse support. As MikeOS, it is designed to be an educational project. It is written in NASM assembler.</p> <p><em>Updated 8/4/09</em></p> <p>I found the <a href="http://www.cs.berkeley.edu/%7Ekubitron/courses/cs162-F08/" rel="noreferrer">slides and other materials</a> to go along with the online Berkeley lectures listed above.</p> <p><em>Updated 8/23/09</em></p> <p>All <a href="https://stackoverflow.com/questions/tagged/osdev">questions tagged osdev</a> on stackoverflow</p> <p><a href="http://www.eecs.harvard.edu/syrah/os161/" rel="noreferrer">OS/161</a> is an academic OS written in c that runs on a simulated hardware. This OS is similar in Nachos. Thanks Novelocrat!</p> <p>tangurena recommends <a href="http://en.wikipedia.org/wiki/MicroC/OS-II" rel="noreferrer">http://en.wikipedia.org/wiki/MicroC/OS-II</a>, an OS designed for embedded systems. There is a <a href="https://rads.stackoverflow.com/amzn/click/com/1578201039" rel="noreferrer" rel="nofollow noreferrer">companion book</a> as well.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0672327201" rel="noreferrer" rel="nofollow noreferrer">Linux Kernel Development</a> by Robert Love is suggested by Anders. It is a &quot;widely acclaimed insider's look at the Linux kernel.&quot;</p> <p><em>Updated 9/18/2009</em></p> <p>Thanks Tim S. Van Haren for telling us about <a href="http://www.gocosmos.org/index.en.aspx" rel="noreferrer">Cosmos</a>, an OS written entirely in c#.</p> <p>tgiphil tells us about <a href="http://www.mosa-project.org/" rel="noreferrer">Managed Operating System Alliance (MOSA) Framework</a>, &quot;a set of tools, specifications and source code to foster development of managed operating systems based on the Common Intermediate Language.&quot;</p> <p><em>Update 9/24/2009</em></p> <p>Steve found a couple resources for development on windows using Visual Studio, check out <a href="http://www.brokenthorn.com/Resources/OSDevMSVC.html" rel="noreferrer">BrokenThorn's guide setup with VS 2005</a> or <a href="http://wiki.osdev.org/Visual%5FStudio" rel="noreferrer">OSDev's VS Section</a>.</p> <p><em>Updated 9/5/2012</em></p> <p>kerneltrap.org is no longer available. The linux kernel v0.01 is available from <a href="http://www.kernel.org/pub/linux/kernel/Historic/linux-0.01.tar.gz" rel="noreferrer">kernel.org</a></p> <p><em>Updated 12/21/2012</em> A basic OS development <a href="http://nw08.american.edu/%7Emblack/teaching.html#OSPROJECT" rel="noreferrer">tutorial</a> designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related <a href="http://nw08.american.edu/%7Emblack/papers/sigcse09.pdf" rel="noreferrer">paper</a>. Thanks Srujan!</p> <p><em>Updated 11/15/2013</em></p> <p><a href="http://www.cs.bham.ac.uk/%7Eexr/lectures/opsys/10_11/lectures/os-dev.pdf" rel="noreferrer">Writing a Simple Operating System From Scratch</a>. Thanks James Moore!</p> <p><em>Updated 12/8/2013</em></p> <p><a href="https://github.com/SamyPesse/How-to-Make-a-Computer-Operating-System" rel="noreferrer">How to make a computer operating system</a> Thanks ddtoni!</p> <p><em>Updated 3/18/2014</em></p> <p><a href="https://github.com/klange/toaruos" rel="noreferrer">ToAruOS an OS built mostly from scratch, including GUI</a></p> <p><em>Updated Sept 12 2016</em></p> <p><a href="http://www.independent-software.com/writing-your-own-toy-operating-system/" rel="noreferrer">Writing your own Toy Operating System</a></p> <p><em>Updated Dec 10 2016</em></p> <p><a href="https://www.cs.bham.ac.uk/%7Eexr/lectures/opsys/10_11/lectures/os-dev.pdf" rel="noreferrer">Writing a Simple Operating System —from Scratch</a> (thank you @Tyler C)</p>
<p>There are a lot of links after this <a href="http://www.osix.net/modules/article/?id=359" rel="noreferrer">brief overview</a> of what is involved in writing an OS for the X86 platform.</p> <p>The link that appears to be most promising (www.nondot.org/sabre/os/articles) is no longer available, so you'll need to poke through the <a href="http://web.archive.org/web/20021207220335/http://www.nondot.org/sabre/os/articles" rel="noreferrer">Archive.org version</a> to read it.</p> <p>At the end of the day the bootloader takes the machine code of the kernel, puts it in memory, and jumps to it. You can put any machine code in the kernel that you want, but most C programs expect an OS so you'll need to tell your compiler that it won't have all that, or the bootloader has to create some of it.</p> <p>The kernel then does all the heavy lifting, and I suspect it's the example kernel you want. But there's a long way to go between having a kernel that says, "Hello world" to having a kernel that loads a command interpretor, provides disk services, and loads and manages programs.</p> <p>You might want to consider subscribing to ACM to get access to their older literature - there are lots of articles in the late 80's and early 90's in early computing magazines about how to <a href="http://portal.acm.org/citation.cfm?id=87073.87079" rel="noreferrer">create alternative OSs</a>. There are likely books that are out of print from this era as well. You might be able to get the same information for free by looking up the indexes of those magazines (which are available on that site - click "index" near the magazine name) and then asking around for people with a copy.</p> <p>Lastly, I know that usenet is dead (for so sayeth the prophets of internet doom) but you'll find that many of the craggy old experts from that era still live there. You should search google groups (they have dejanews's old repository) and I expect you'll find many people asking the same questions a decade or 1.5 ago that you're asking now. You may even run across Linus Torvalds' many queries for help as he was developing linux originally. If searches don't bring anything up, ask in the appropriate newsgroup (probably starts with comp.arch, but search for ones with OS in the name).</p>
{ "question_id": 43180, "question_date": "2008-09-04T04:28:09.230Z", "question_score": 609, "tags": "operating-system|kernel|osdev", "answer_id": 45684, "answer_date": "2008-09-05T12:38:38.060Z", "answer_score": 97 }