input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Simulate limited bandwidth from within Chrome? <p>Is there a way I can simulate various connection speeds from within Chrome?</p> <p>I need to be able to check <a href="http://localhost" rel="noreferrer">http://localhost</a> with varying speeds.</p> <p>I know there are standalone applications that can do this, but I'd rather do this inside Chrome.</p>
<p>I'd recommend <a href="http://charlesproxy.com" rel="noreferrer">Charles Proxy</a> - you can choose to slowdown individual sites, also has a whole bunch of HTTP inspection tools.</p> <p><strong>Edit:</strong></p> <p>As of June 2014, Chrome now has the ability to do this natively in DevTools - you'll need Chrome 38 though.</p> <p>The option is accessible from the Network tab via a drop down at the end of the toolbar. </p>
{ "question_id": 10328568, "question_date": "2012-04-26T06:55:21.267Z", "question_score": 213, "tags": "google-chrome|google-chrome-extension|bandwidth-throttling", "answer_id": 10329600, "answer_date": "2012-04-26T08:17:34.507Z", "answer_score": 120 }
Please answer the following Stack Overflow question: Title: How to use UIVisualEffectView to Blur Image? <p>Could someone give a small example of applying the blur to an image? I've been trying to figure out the code for a while now :( still new at obj c!</p> <blockquote> <p>The <code>UIVisualEffectView</code> provides a simple abstraction over complex visual effects. Depending on the desired effect, the results may affect content layered behind the view or content added to the view’s contentView.</p> <p>Apply a <code>UIVisualEffectView</code> to an existing view to apply a blur or vibrancy effect to the exiting view. After you add the UIVisualEffectView to the view hierarchy, add any subviews to the contentView of the <code>UIVisualEffectView</code>. Do not add subviews directly to the <code>UIVisualEffectView</code> itself.</p> </blockquote> <p><a href="https://developer.apple.com/documentation/uikit/uivisualeffectview#//apple_ref/occ/instp/UIVisualEffectView/contentView" rel="noreferrer">https://developer.apple.com/documentation/uikit/uivisualeffectview#//apple_ref/occ/instp/UIVisualEffectView/contentView</a></p>
<p>Just put this blur view on the imageView. Here is an example in Objective-C:</p> <pre><code>UIVisualEffect *blurEffect; blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView *visualEffectView; visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; visualEffectView.frame = imageView.bounds; [imageView addSubview:visualEffectView]; </code></pre> <p>and Swift:</p> <pre><code>var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) visualEffectView.frame = imageView.bounds imageView.addSubview(visualEffectView) </code></pre>
{ "question_id": 24067719, "question_date": "2014-06-05T18:35:37.547Z", "question_score": 213, "tags": "ios|objective-c|uiview|uikit|uivisualeffectview", "answer_id": 24083728, "answer_date": "2014-06-06T14:02:54.093Z", "answer_score": 422 }
Please answer the following Stack Overflow question: Title: Rails get index of "each" loop <p>So I have this loop:</p> <pre><code>&lt;% @images.each do |page| %&gt; &lt;% end %&gt; </code></pre> <p>How would I get the index of "page" inside of the loop?</p>
<pre><code>&lt;% @images.each_with_index do |page, index| %&gt; &lt;% end %&gt; </code></pre>
{ "question_id": 4811668, "question_date": "2011-01-27T00:11:12.080Z", "question_score": 213, "tags": "ruby-on-rails|ruby", "answer_id": 4811680, "answer_date": "2011-01-27T00:12:07.433Z", "answer_score": 399 }
Please answer the following Stack Overflow question: Title: Presenting a UIAlertController properly on an iPad using iOS 8 <p>With iOS 8.0, Apple introduced <a href="https://developer.apple.com/library/prerelease/iOS/documentation/UIKit/Reference/UIAlertController_class/index.html" rel="noreferrer">UIAlertController</a> to replace <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/uiactionsheet_class/Reference/Reference.html" rel="noreferrer">UIActionSheet</a>. Unfortunately, Apple didn't add any information on how to present it. I found an <a href="http://hayageek.com/uialertcontroller-example-ios/" rel="noreferrer">entry</a> about it on hayaGeek's blog, however, it doesn't seem to work on iPad. The view is totally misplaced:</p> <p>Misplaced: <img src="https://i.stack.imgur.com/KhAaj.png" alt="Misplaced image"></p> <p>Correct: <img src="https://i.stack.imgur.com/lFd3S.png" alt="enter image description here"></p> <p>I use the following code to show it on the interface:</p> <pre><code> let alert = UIAlertController() // setting buttons self.presentModalViewController(alert, animated: true) </code></pre> <p>Is there another way to add it for iPad? Or did Apple just forget the iPad, or not implemented, yet?</p>
<p>You can present a <code>UIAlertController</code> from a popover by using <code>UIPopoverPresentationController</code>.</p> <h2>In Obj-C:</h2> <pre><code>UIViewController *self; // code assumes you're in a view controller UIButton *button; // the button you want to show the popup sheet from UIAlertController *alertController; UIAlertAction *destroyAction; UIAlertAction *otherAction; alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; destroyAction = [UIAlertAction actionWithTitle:@&quot;Remove All Data&quot; style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { // do destructive stuff here }]; otherAction = [UIAlertAction actionWithTitle:@&quot;Blah&quot; style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { // do something here }]; // note: you can control the order buttons are shown, unlike UIActionSheet [alertController addAction:destroyAction]; [alertController addAction:otherAction]; [alertController setModalPresentationStyle:UIModalPresentationPopover]; UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController]; popPresenter.sourceView = button; popPresenter.sourceRect = button.bounds; [self presentViewController:alertController animated:YES completion:nil]; </code></pre> <p>Editing for Swift 4.2, though there are many blogs available for the same but it may save your time to go and search for them.</p> <pre><code>if let popoverController = yourAlert.popoverPresentationController { popoverController.sourceView = self.view //to set the source of your alert popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement. popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction } </code></pre>
{ "question_id": 24224916, "question_date": "2014-06-14T22:38:37.087Z", "question_score": 213, "tags": "ios|ipad|user-interface|uialertcontroller", "answer_id": 24233937, "answer_date": "2014-06-15T20:42:31.513Z", "answer_score": 306 }
Please answer the following Stack Overflow question: Title: How change List<T> data to IQueryable<T> data <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/73542/ilistt-to-iqueryablet">IList&lt;T&gt; to IQueryable&lt;T&gt;</a> </p> </blockquote> <p>I have a List data, but I want a IQueryable data , is it possible from List data to IQueryable data? Show me code</p>
<pre><code>var list = new List&lt;string&gt;(); var queryable = list.AsQueryable(); </code></pre> <p>Add a reference to: <code>System.Linq</code></p>
{ "question_id": 676500, "question_date": "2009-03-24T08:10:25.757Z", "question_score": 213, "tags": ".net|linq", "answer_id": 676504, "answer_date": "2009-03-24T08:12:37.013Z", "answer_score": 471 }
Please answer the following Stack Overflow question: Title: How can I tell when UITableView has completed ReloadData? <p>I am trying to scroll to the bottom of a UITableView after it is done performing <code>[self.tableView reloadData]</code>.</p> <p>I originally had</p> <pre><code> [self.tableView reloadData] NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; </code></pre> <p>But then I read that reloadData is asynchronous, so the scrolling doesn't happen since the <code>self.tableView</code>, <code>[self.tableView numberOfSections]</code> and <code>[self.tableView numberOfRowsinSection</code> are all 0.</p> <p>It's weird that I am using:</p> <pre><code>[self.tableView reloadData]; NSLog(@&quot;Number of Sections %d&quot;, [self.tableView numberOfSections]); NSLog(@&quot;Number of Rows %d&quot;, [self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1); </code></pre> <p>In the console it returns Sections = 1, Row = -1;</p> <p>When I do the exact same NSLogs in <code>cellForRowAtIndexPath</code> I get Sections = 1 and Row = 8; (8 is right)</p>
<p>The reload happens during the next layout pass, which normally happens when you return control to the run loop (after, say, your button action or whatever returns).</p> <p>So one way to run something after the table view reloads is simply to force the table view to perform layout immediately:</p> <pre><code>[self.tableView reloadData]; [self.tableView layoutIfNeeded]; NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; </code></pre> <p>Another way is to schedule your after-layout code to run later using <code>dispatch_async</code>:</p> <pre><code>[self.tableView reloadData]; dispatch_async(dispatch_get_main_queue(), ^{ NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection:([self.tableView numberOfSections]-1)]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; }); </code></pre> <h3>UPDATE</h3> <p>Upon further investigation, I find that the table view sends <code>tableView:numberOfSections:</code> and <code>tableView:numberOfRowsInSection:</code> to its data source before returning from <code>reloadData</code>. If the delegate implements <code>tableView:heightForRowAtIndexPath:</code>, the table view also sends that (for each row) before returning from <code>reloadData</code>.</p> <p>However, the table view does not send <code>tableView:cellForRowAtIndexPath:</code> or <code>tableView:headerViewForSection</code> until the layout phase, which happens by default when you return control to the run loop.</p> <p>I also find that in a tiny test program, the code in your question properly scrolls to the bottom of the table view, <strong>without</strong> me doing anything special (like sending <code>layoutIfNeeded</code> or using <code>dispatch_async</code>).</p>
{ "question_id": 16071503, "question_date": "2013-04-17T22:41:34.417Z", "question_score": 213, "tags": "objective-c|uitableview|reloaddata", "answer_id": 16071589, "answer_date": "2013-04-17T22:49:48.343Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: Implementing Singleton with an Enum (in Java) <p>I have read that it is possible to implement <code>Singleton</code> in Java using an <code>Enum</code> such as:</p> <pre><code>public enum MySingleton { INSTANCE; } </code></pre> <p>But, how does the above work? Specifically, an <code>Object</code> has to be instantiated. Here, how is <code>MySingleton</code> being instantiated? Who is doing <code>new MySingleton()</code>?</p>
<p>This,</p> <pre><code>public enum MySingleton { INSTANCE; } </code></pre> <p>has an implicit empty constructor. Make it explicit instead,</p> <pre><code>public enum MySingleton { INSTANCE; private MySingleton() { System.out.println("Here"); } } </code></pre> <p>If you then added another class with a <code>main()</code> method like</p> <pre><code>public static void main(String[] args) { System.out.println(MySingleton.INSTANCE); } </code></pre> <p>You would see</p> <pre><code>Here INSTANCE </code></pre> <p><code>enum</code> fields are compile time constants, but they are instances of their <code>enum</code> type. And, they're constructed when the enum type is referenced for <strong>the first time</strong>.</p>
{ "question_id": 26285520, "question_date": "2014-10-09T18:27:19.733Z", "question_score": 213, "tags": "java|design-patterns|enums|singleton", "answer_id": 26285591, "answer_date": "2014-10-09T18:31:35.680Z", "answer_score": 236 }
Please answer the following Stack Overflow question: Title: Clicking URLs opens default browser <p>I have loaded an external URL in my <code>WebView</code>. Now what I need is that when the user clicks on the links on the page loaded, it has to work like a normal browser and open the link in the same <code>WebView</code>. But it's opening the default browser and loading the page there?</p> <p>I have enabled JavaScript. But still it's not working. Have I forgotten something?</p>
<p>If you're using a <code>WebView</code> you'll have to intercept the clicks yourself if you don't want the default Android behaviour.</p> <p>You can monitor events in a <code>WebView</code> using a <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html" rel="noreferrer"><code>WebViewClient</code></a>. The method you want is <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String)" rel="noreferrer"><code>shouldOverrideUrlLoading()</code></a>. This allows you to perform your own action when a particular URL is selected.</p> <p>You set the <code>WebViewClient</code> of your <code>WebView</code> using the <a href="http://developer.android.com/reference/android/webkit/WebView.html#setWebViewClient(android.webkit.WebViewClient)" rel="noreferrer"><code>setWebViewClient()</code> method</a>.</p> <p>If you look at the <a href="https://developer.android.com/guide/webapps/webview.html" rel="noreferrer"><code>WebView</code> sample in the SDK</a> there's an example which does just what you want. It's as simple as:</p> <pre><code>private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } </code></pre>
{ "question_id": 2378800, "question_date": "2010-03-04T11:22:15.770Z", "question_score": 213, "tags": "android|url|android-webview|android-websettings", "answer_id": 2379054, "answer_date": "2010-03-04T12:03:51.193Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: How do you detect the clearing of a "search" HTML5 input? <p>In HTML5, the <code>search</code> input type appears with a little X on the right that will clear the textbox (at least in Chrome, maybe others). Is there a way to detect when this X is clicked in Javascript or jQuery other than, say, detecting when the box is clicked at all or doing some sort of location click-detecting (x-position/y-position)?</p>
<p>Actually, there is a &quot;search&quot; event that is fired whenever the user searches, or when the user clicks the &quot;x&quot;. This is especially useful because it understands the &quot;incremental&quot; attribute.</p> <p>Now, having said that, I'm not sure if you can tell the difference between clicking the &quot;x&quot; and searching, unless you use an &quot;onclick&quot; hack. Either way, hopefully this helps.</p> <p><a href="http://help.dottoro.com/ljdvxmhr.php" rel="noreferrer">Dottoro web reference</a></p>
{ "question_id": 2977023, "question_date": "2010-06-04T19:10:55.047Z", "question_score": 213, "tags": "javascript|jquery|html|events|dom-events", "answer_id": 3726743, "answer_date": "2010-09-16T12:41:54.847Z", "answer_score": 133 }
Please answer the following Stack Overflow question: Title: What is an opaque response, and what purpose does it serve? <p>I tried to <code>fetch</code> the URL of an old website, and an error happened:</p> <pre><code>Fetch API cannot load http://xyz. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://abc' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. </code></pre> <p>I understood the message, and tried to do a request that returns an opaque response:</p> <pre><code>fetch("http://xyz", {'mode': 'no-cors'}) </code></pre> <p>Ok, it now works... but I can't read it. =\</p> <p>What's the purpose then, of an opaque response?</p>
<p>Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.</p> <p>This is what <code>{ mode: 'no-cors' }</code> was made for.</p>
{ "question_id": 36292537, "question_date": "2016-03-29T18:41:21.997Z", "question_score": 213, "tags": "cors|fetch-api", "answer_id": 36303436, "answer_date": "2016-03-30T08:26:33.430Z", "answer_score": 173 }
Please answer the following Stack Overflow question: Title: Multiple left-hand assignment with JavaScript <pre><code>var var1 = 1, var2 = 1, var3 = 1; </code></pre> <p>This is equivalent to this:</p> <pre><code>var var1 = var2 = var3 = 1; </code></pre> <p>I'm fairly certain this is the order the variables are defined: var3, var2, var1, which would be equivalent to this:</p> <pre><code>var var3 = 1, var2 = var3, var1 = var2; </code></pre> <p>Is there any way to confirm this in JavaScript? Using some profiler possibly?</p>
<p>Actually,</p> <pre><code>var var1 = 1, var2 = 1, var3 = 1; </code></pre> <p>is <em>not</em> equivalent to:</p> <pre><code>var var1 = var2 = var3 = 1; </code></pre> <p>The difference is in scoping:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function good() { var var1 = 1, var2 = 1, var3 = 1; } function bad() { var var1 = var2 = var3 = 1; } good(); console.log(window.var2); // undefined bad(); console.log(window.var2); // 1. Aggh!</code></pre> </div> </div> </p> <p>Actually this shows that assignment are right associative. The <code>bad</code> example is equivalent to:</p> <pre><code>var var1 = (window.var2 = (window.var3 = 1)); </code></pre>
{ "question_id": 1758576, "question_date": "2009-11-18T19:48:37.857Z", "question_score": 213, "tags": "javascript|variables|variable-assignment", "answer_id": 1758912, "answer_date": "2009-11-18T20:39:11.057Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: Difference between defining typing.Dict and dict? <p>I am practicing using type hints in Python 3.5. One of my colleague uses <code>typing.Dict</code>:</p> <pre><code>import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -&gt; bool: print(new_bandwidths, user_id, user_name) return False def my_change_bandwidths(new_bandwidths: dict, user_id: int, user_name: str) -&gt;bool: print(new_bandwidths, user_id, user_name) return True def main(): my_id, my_name = 23, "Tiras" simple_dict = {"Hello": "Moon"} change_bandwidths(simple_dict, my_id, my_name) new_dict = {"new": "energy source"} my_change_bandwidths(new_dict, my_id, my_name) if __name__ == "__main__": main() </code></pre> <p>Both of them work just fine, there doesn't appear to be a difference. </p> <p>I have read the <a href="https://docs.python.org/3/library/typing.html"><code>typing</code> module documentation</a>.</p> <p>Between <code>typing.Dict</code> or <code>dict</code> which one should I use in the program?</p>
<p>There is no real difference between using a plain <code>typing.Dict</code> and <code>dict</code>, no.</p> <p>However, <code>typing.Dict</code> is a <a href="https://docs.python.org/3/library/typing.html#generics" rel="noreferrer"><em>Generic type</em></a> <sup>*</sup> that lets you specify the type of the keys and values <em>too</em>, making it more flexible:</p> <pre><code>def change_bandwidths(new_bandwidths: typing.Dict[str, str], user_id: int, user_name: str) -&gt; bool: </code></pre> <p>As such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding <code>typing.Dict</code> to <code>typing.Dict[key_type, value_type]</code> is a 'smaller' change than replacing <code>dict</code>.</p> <p>You can make this even more generic by using <a href="https://docs.python.org/3/library/typing.html#typing.Mapping" rel="noreferrer"><code>Mapping</code></a> or <a href="https://docs.python.org/3/library/typing.html#typing.MutableMapping" rel="noreferrer"><code>MutableMapping</code></a> types here; since your function doesn't need to <em>alter</em> the mapping, I'd stick with <code>Mapping</code>. A <code>dict</code> is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those:</p> <pre><code>def change_bandwidths(new_bandwidths: typing.Mapping[str, str], user_id: int, user_name: str) -&gt; bool: </code></pre> <p>Now you are clearly telling other users of this function that your code won't actually <em>alter</em> the <code>new_bandwidths</code> mapping passed in.</p> <p>Your actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used <code>new_bandwidths: typing.Any</code>, because any object in Python is printable.</p> <hr /> <p><sup>*</sup>: Note: If you are using Python 3.7 or newer, you can use <code>dict</code> as a generic type if you start your module with <a href="https://www.python.org/dev/peps/pep-0563/" rel="noreferrer"><code>from __future__ import annotations</code></a>, and as of Python 3.9, <code>dict</code> (as well as other standard containers) <a href="https://www.python.org/dev/peps/pep-0585/" rel="noreferrer">supports being used as generic type even without that directive</a>.</p>
{ "question_id": 37087457, "question_date": "2016-05-07T10:36:37.577Z", "question_score": 213, "tags": "python|dictionary|type-hinting|python-typing", "answer_id": 37087556, "answer_date": "2016-05-07T10:45:42.147Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Delay/Wait in a test case of Xcode UI testing <p>I am trying to write a test case using the new UI Testing available in Xcode 7 beta 2. The App has a login screen where it makes a call to the server to login. There is a delay associated with this as it is an asynchronous operation.</p> <p>Is there a way to cause a delay or wait mechanism in the XCTestCase before proceeding to further steps?</p> <p>There is no proper documentation available and I went through the Header files of the classes. Was not able to find anything related to this.</p> <p>Any ideas/suggestions?</p>
<p>Asynchronous UI Testing was introduced in Xcode 7 Beta 4. To wait for a label with the text "Hello, world!" to appear you can do the following:</p> <pre><code>let app = XCUIApplication() app.launch() let label = app.staticTexts["Hello, world!"] let exists = NSPredicate(format: "exists == 1") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) </code></pre> <p>More <a href="http://masilotti.com/ui-testing-xcode-7/">details about UI Testing</a> can be found on my blog.</p>
{ "question_id": 31182637, "question_date": "2015-07-02T10:55:49.910Z", "question_score": 213, "tags": "ios|ios9|xcode-ui-testing|xcode7-beta2|xctwaiter", "answer_id": 32228104, "answer_date": "2015-08-26T13:32:48.070Z", "answer_score": 188 }
Please answer the following Stack Overflow question: Title: Which is faster: multiple single INSERTs or one multiple-row INSERT? <p>I am trying to optimize one part of my code that inserts data into MySQL. Should I chain INSERTs to make one huge multiple-row INSERT or are multiple separate INSERTs faster?</p>
<p><a href="https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html" rel="noreferrer">https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html</a></p> <blockquote> <p>The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:</p> <ul> <li>Connecting: (3)</li> <li>Sending query to server: (2)</li> <li>Parsing query: (2)</li> <li>Inserting row: (1 × size of row)</li> <li>Inserting indexes: (1 × number of indexes)</li> <li>Closing: (1)</li> </ul> </blockquote> <p>From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:</p> <blockquote> <p>If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.</p> </blockquote>
{ "question_id": 1793169, "question_date": "2009-11-24T21:51:33.217Z", "question_score": 213, "tags": "mysql|insert|mariadb|benchmarking", "answer_id": 1793209, "answer_date": "2009-11-24T21:57:16.917Z", "answer_score": 322 }
Please answer the following Stack Overflow question: Title: S3 Bucket action doesn't apply to any resources <p>I'm following the instructions from <a href="https://stackoverflow.com/a/23102551/773263">this answer</a> to generate the follow S3 bucket policy:</p> <pre><code>{ "Id": "Policy1495981680273", "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1495981517155", "Action": [ "s3:GetObject" ], "Effect": "Allow", "Resource": "arn:aws:s3:::surplace-audio", "Principal": "*" } ] } </code></pre> <p>I get back the following error:</p> <blockquote> <p>Action does not apply to any resource(s) in statement</p> </blockquote> <p>What am I missing from my policy?</p>
<p>From IAM docs, <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Action" rel="noreferrer">http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Action</a></p> <p>Some services do not let you specify actions for individual resources; instead, any actions that you list in the Action or NotAction element apply to all resources in that service. In these cases, you use the wildcard * in the Resource element.</p> <p>With this information, resource should have a value like below:</p> <pre><code>"Resource": "arn:aws:s3:::surplace-audio/*" </code></pre>
{ "question_id": 44228422, "question_date": "2017-05-28T14:30:51.937Z", "question_score": 213, "tags": "amazon-web-services|amazon-s3", "answer_id": 44228514, "answer_date": "2017-05-28T14:41:27.330Z", "answer_score": 373 }
Please answer the following Stack Overflow question: Title: Change highlight text color in Visual Studio Code <p>Right now, it is a faint gray overlay, which is hard to see. Any way to change the default color?</p> <p><a href="https://i.stack.imgur.com/qmrOL.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qmrOL.jpg" alt="enter image description here"></a></p>
<p><strong>Update</strong> <a href="https://stackoverflow.com/a/43605752/285212">See @Jakub Zawiślak's answer for VScode 1.12+</a></p> <hr> <p><strong>Old answer</strong></p> <p>Visual Studio Code calls this selection highlighting and unfortunately, I don't think the color is customizable currently. Themes can control the 'selection' color, but the 'selection highlight' color is hardcoded.</p> <p>See this issue tracking a possible solution: <a href="https://github.com/Microsoft/vscode/issues/1636" rel="noreferrer">https://github.com/Microsoft/vscode/issues/1636</a></p> <p>(As a side note, you can toggle this feature or/off with the <code>editor.selectionHighlight</code> setting.)</p>
{ "question_id": 35926381, "question_date": "2016-03-10T20:17:05.990Z", "question_score": 213, "tags": "visual-studio-code", "answer_id": 35929462, "answer_date": "2016-03-10T23:33:39.943Z", "answer_score": 16 }
Please answer the following Stack Overflow question: Title: Could not load file or assembly ... The parameter is incorrect <p>Recently I met the following exception at C# solution:</p> <blockquote> <p>Error 2 Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))</p> </blockquote> <p>This does not depend either on my code or on the name of assembly (like <code>Newtonsoft.Json</code> in this case).</p> <p>When I delete this dll from the solution the compiler tells about another in the same exception. So I suppose something shoud be turned off/on at my PC :)</p>
<p>Looks like a corrupted assembly being referenced.</p> <p>Clear both:</p> <ol> <li><p>the \bin folder of your project</p></li> <li><p>the temp folder (should be <code>C:\Users\your_username\AppData\Local\Temp\Temporary ASP.NET Files</code> in windows 7)</p></li> </ol> <p>and see if the error still happens</p>
{ "question_id": 8269386, "question_date": "2011-11-25T12:49:25.810Z", "question_score": 213, "tags": "c#|exception|compiler-construction|compiler-errors", "answer_id": 8269493, "answer_date": "2011-11-25T12:59:09.503Z", "answer_score": 350 }
Please answer the following Stack Overflow question: Title: Undefined reference to static class member <p>Can anyone explain why following code won't compile? At least on g++ 4.2.4.</p> <p>And more interesting, why it will compile when I cast MEMBER to int?</p> <pre><code>#include &lt;vector&gt; class Foo { public: static const int MEMBER = 1; }; int main(){ vector&lt;int&gt; v; v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER' v.push_back( (int) Foo::MEMBER ); // OK return 0; } </code></pre>
<p>You need to actually define the static member somewhere (after the class definition). Try this:</p> <pre><code>class Foo { /* ... */ }; const int Foo::MEMBER; int main() { /* ... */ } </code></pre> <p>That should get rid of the undefined reference.</p>
{ "question_id": 272900, "question_date": "2008-11-07T17:39:56.217Z", "question_score": 213, "tags": "c++|g++", "answer_id": 272965, "answer_date": "2008-11-07T17:57:35.213Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: Difference between _JAVA_OPTIONS, JAVA_TOOL_OPTIONS and JAVA_OPTS <p>I thought it would be great to have a comparison between <code>_JAVA_OPTIONS</code> and <code>JAVA_TOOL_OPTIONS</code>. I have been searching a bit for one, but I cannot find anything, so I hope we can find the knowledge here on Stackoverflow.</p> <p><code>JAVA_OPTS</code> is included for completeness. It is not part of the JVM, but there is a lot of questions about it out in the wild.</p> <h2>What I know:</h2> <p>So far I have found out that:</p> <ul> <li><strong><code>JAVA_OPTS</code></strong> is not used by the JDK, but by a bunch of other apps (see <a href="https://stackoverflow.com/questions/3933300/">this post</a>).</li> <li><strong><code>JAVA_TOOL_OPTIONS</code></strong> and <strong><code>_JAVA_OPTIONS</code></strong> are ways to specify JVM arguments as an environment variable instead of command line parameters. <ul> <li>The are picked up by at least <code>java</code> and <code>javac</code></li> <li>They have this precedence: <ol> <li><code>_JAVA_OPTIONS</code> (overwrites the others)</li> <li>Command line parameters</li> <li><code>JAVA_TOOL_OPTIONS</code> (is overwritten by the others)</li> </ol></li> </ul></li> </ul> <h2>What I would like to know</h2> <ul> <li>Are there any official documentation comparing <code>JAVA_TOOL_OPTIONS</code> and <code>_JAVA_OPTIONS</code></li> <li>Are there any other differences between <code>JAVA_TOOL_OPTIONS</code> and <code>_JAVA_OPTIONS</code> (except from precedence).</li> <li>Which executables pick up <code>JAVA_TOOL_OPTIONS</code> and <code>_JAVA_OPTIONS</code> (in addition to <code>java</code> and <code>javac</code>)</li> <li>Any limitation on what can be included on <code>JAVA_TOOL_OPTIONS</code> and <code>_JAVA_OPTIONS</code></li> </ul> <h2>Official Documentation</h2> <p>I have not been able to find any documentation about <code>_JAVA_OPTIONS</code>. <a href="http://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#tooloptions" rel="noreferrer">The documentation for <code>JAVA_TOOL_OPTIONS</code></a> does not shed much light on the difference:</p> <blockquote> <p>Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a JAVA_TOOL_OPTIONS variable is provided so that agents may be launched in these cases. <br>...</p> </blockquote> <h1>Example script</h1> <p>This is the code I used to figure this out. Console output is included as comments:</p> <pre><code>export JAVA_OPTS=foobar export JAVA_TOOL_OPTIONS= export _JAVA_OPTIONS="-Xmx512m -Xms64m" java -version # Picked up JAVA_TOOL_OPTIONS: # Picked up _JAVA_OPTIONS: -Xmx512m -Xms64m # java version "1.7.0_40" OpenJDK Runtime Environment (IcedTea 2.4.1) (suse-3.41.1-x86_64) OpenJDK 64-Bit Server VM (build 24.0-b50, mixed mode) javac -version # Picked up JAVA_TOOL_OPTIONS: # Picked up _JAVA_OPTIONS: -Xmx512m -Xms64m # javac 1.7.0_40 export JAVA_TOOL_OPTIONS="-Xmx1 -Xms1" export _JAVA_OPTIONS="-Xmx512m -Xms64m" javac -version # Picked up JAVA_TOOL_OPTIONS: -Xmx1 -Xms1 # Picked up _JAVA_OPTIONS: -Xmx512m -Xms64m # javac 1.7.0_40 export JAVA_TOOL_OPTIONS="-Xmx512m -Xms64m" export _JAVA_OPTIONS="-Xmx1 -Xms1" javac -version # Picked up JAVA_TOOL_OPTIONS: -Xmx512m -Xms64m # Picked up _JAVA_OPTIONS: -Xmx1 -Xms1 # Error occurred during initialization of VM # Too small initial heap export JAVA_TOOL_OPTIONS="-Xmx1 -Xms1" export _JAVA_OPTIONS= java -Xmx512m -Xms64m -version # Picked up JAVA_TOOL_OPTIONS: -Xmx1 -Xms1 # Picked up _JAVA_OPTIONS: # java version "1.7.0_40" # OpenJDK Runtime Environment (IcedTea 2.4.1) (suse-3.41.1-x86_64) # OpenJDK 64-Bit Server VM (build 24.0-b50, mixed mode) export JAVA_TOOL_OPTIONS= export _JAVA_OPTIONS="-Xmx1 -Xms1" java -Xmx512m -Xms64m -version # Picked up JAVA_TOOL_OPTIONS: # Picked up _JAVA_OPTIONS: -Xmx1 -Xms1 # Error occurred during initialization of VM # Too small initial heap </code></pre>
<p>You have pretty much nailed it except that these options are picked up even if you start JVM in-process via a library call.</p> <p>The fact that <code>_JAVA_OPTIONS</code> is not documented suggests that it is not recommended to use this variable, and I've actually seen people abuse it by setting it in their <code>~/.bashrc</code>. However, if you want to get to the bottom of this problem, you can check the source of Oracle HotSpot VM (e.g. <a href="http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/9b0ca45cd756/src/share/vm/runtime/arguments.cpp" rel="noreferrer">in OpenJDK7</a>).</p> <p>You should also remember that there is no guarantee other VMs have or will continue to have support for undocumented variables.</p> <p><strong>UPDATE 2015-08-04:</strong> To save five minutes for folks coming from search engines, <code>_JAVA_OPTIONS</code> trumps command-line arguments, which in turn trump <code>JAVA_TOOL_OPTIONS</code>.</p>
{ "question_id": 28327620, "question_date": "2015-02-04T17:26:53.963Z", "question_score": 213, "tags": "java|jvm|jvm-arguments", "answer_id": 30305597, "answer_date": "2015-05-18T14:15:26.073Z", "answer_score": 90 }
Please answer the following Stack Overflow question: Title: Passport.js - Error: failed to serialize user into session <p>I got a problem with the Passport.js module and Express.js.</p> <p>This is my code and I just want to use a hardcoded login for the first try.</p> <p>I always get the message:</p> <p>I searched a lot and found some posts in stackoverflow but I didnt get the failure.</p> <pre><code>Error: failed to serialize user into session at pass (c:\Development\private\aortmann\bootstrap_blog\node_modules\passport\lib\passport\index.js:275:19) </code></pre> <p>My code looks like this.</p> <pre><code>'use strict'; var express = require('express'); var path = require('path'); var fs = require('fs'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var nodemailer = require('nodemailer'); var app = express(); module.exports = function setupBlog(mailTransport, database){ var config = JSON.parse(fs.readFileSync('./blog.config')); app.set('view options', {layout: false}); app.use(express.static(path.join(__dirname, '../', 'resources', 'html'))); app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'secret' })); app.use(passport.initialize()); app.use(passport.session()); app.get('/blog/:blogTitle', function(req, res) { var blogTitle = req.params.blogTitle; if(blogTitle === 'newest'){ database.getLatestBlogPost(function(post) { res.send(post); }); } else { database.getBlogPostByTitle(blogTitle, function(blogPost) { res.send(blogPost); }); } }); passport.use(new LocalStrategy(function(username, password, done) { // database.login(username, password, done); if (username === 'admin' &amp;&amp; password === 'admin') { console.log('in'); done(null, { username: username }); } else { done(null, false); } })); app.post('/login', passport.authenticate('local', { successRedirect: '/accessed', failureRedirect: '/access' })); app.listen(8080); console.log('Blog is running on port 8080'); }(); </code></pre> <p>Thanks.</p>
<p>It looks like you didn't implement <code>passport.serializeUser</code> and <code>passport.deserializeUser</code>. Try adding this:</p> <pre><code>passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); </code></pre>
{ "question_id": 19948816, "question_date": "2013-11-13T08:26:56.070Z", "question_score": 213, "tags": "node.js|express|authentication|passport.js|passport-local", "answer_id": 19949584, "answer_date": "2013-11-13T09:07:38.357Z", "answer_score": 422 }
Please answer the following Stack Overflow question: Title: Custom Cell Row Height setting in storyboard is not responding <p>I am trying to adjust the cell height for one of the cells on my table view. I am adjusting the size from the "row height" setting inside the "size inspector" of the cell in question. When I run the app on my iPhone the cell has the default size set from the "row size" in the table view.</p> <p>If I change the "row size" of the table view then the size of all cells changes. I do not want to do that as I want a custom size only for one cell. I have seen a lot of posts that have a programmatic solution to the problem, but I would prefer to do it through storyboard, if that is possible.</p>
<p>On <strong>dynamic</strong> cells, <code>rowHeight</code> set on the UITableView always overrides the individual cells' rowHeight.</p> <p>But on <strong>static</strong> cells, <code>rowHeight</code> set on individual cells can override UITableView's.</p> <p>Not sure if it's a bug, Apple might be intentionally doing this?</p>
{ "question_id": 8615862, "question_date": "2011-12-23T12:05:18.273Z", "question_score": 213, "tags": "ios|uitableview|ios5|storyboard|xcode4.2", "answer_id": 9898238, "answer_date": "2012-03-27T21:49:50.137Z", "answer_score": 296 }
Please answer the following Stack Overflow question: Title: .NET Global exception handler in console application <p>Question: I want to define a global exception handler for unhandled exceptions in my console application. In asp.net, one can define one in global.asax, and in windows applications /services, one can define as below</p> <pre><code>AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler); </code></pre> <p>But how can I define a global exception handler for a console application ?<br /> currentDomain seems not to work (.NET 2.0) ?</p> <p><strong>Edit:</strong><br /></p> <p>Argh, stupid mistake.<br /> In VB.NET, one needs to add the "AddHandler" keyword in front of currentDomain, or else one doesn't see the UnhandledException event in IntelliSense... <br /> That's because the VB.NET and C# compilers treat event handling differently.</p>
<p>No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:</p> <pre><code>using System; class Program { static void Main(string[] args) { System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; throw new Exception("Kaboom"); } static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject.ToString()); Console.WriteLine("Press Enter to continue"); Console.ReadLine(); Environment.Exit(1); } } </code></pre> <p>Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.</p>
{ "question_id": 3133199, "question_date": "2010-06-28T14:25:58.977Z", "question_score": 213, "tags": "c#|.net|vb.net|exception-handling|console-application", "answer_id": 3133249, "answer_date": "2010-06-28T14:32:05.953Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: Custom numeric format string to always display the sign <p>Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)</p>
<p>Yes, you can. There is conditional formatting. See <a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx" rel="noreferrer">Conditional formatting in MSDN</a></p> <p>eg: </p> <pre><code>string MyString = number.ToString("+0;-#"); </code></pre> <p>Where each section separated by a semicolon represents positive and negative numbers</p> <p>or:</p> <pre><code>string MyString = number.ToString("+#;-#;0"); </code></pre> <p>if you don't want the zero to have a plus sign.</p>
{ "question_id": 348201, "question_date": "2008-12-07T22:17:56.917Z", "question_score": 213, "tags": "c#|.net|formatting|string-formatting", "answer_id": 348242, "answer_date": "2008-12-07T22:40:09.210Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: How can I explode and trim whitespace? <p>For example, I would like to create an array from the elements in this string:</p> <pre><code>$str = 'red, green, blue ,orange'; </code></pre> <p>I know you can explode and loop through them and trim:</p> <pre><code>$arr = explode(',', $str); foreach ($arr as $value) { $new_arr[] = trim($value); } </code></pre> <p>But I feel like there's a one line approach that can handle this. Any ideas?</p>
<p>You can do the following using <a href="http://php.net/manual/en/function.array-map.php"><strong>array_map</strong></a>:</p> <pre><code>$new_arr = array_map('trim', explode(',', $str)); </code></pre>
{ "question_id": 19347005, "question_date": "2013-10-13T15:42:19.240Z", "question_score": 213, "tags": "php|explode|trim|higher-order-functions", "answer_id": 19347006, "answer_date": "2013-10-13T15:42:19.240Z", "answer_score": 552 }
Please answer the following Stack Overflow question: Title: How to fix UITableView separator on iOS 7? <p>UITableView draws with ragged lines on iOS 7:</p> <p><img src="https://i.stack.imgur.com/OE69H.png" alt="enter image description here"></p> <p>How to fix it? The line between cells should be on the full width of the screen.</p>
<p><code>UITableView</code> has a property <code>separatorInset</code>. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen. </p> <pre><code>[tableView setSeparatorInset:UIEdgeInsetsZero]; </code></pre> <p><strong>Note:</strong> If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:</p> <pre><code>if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) { [tableView setSeparatorInset:UIEdgeInsetsZero]; } </code></pre>
{ "question_id": 18773239, "question_date": "2013-09-12T19:55:41.440Z", "question_score": 213, "tags": "iphone|ios|ipad|uitableview|ios7", "answer_id": 18773281, "answer_date": "2013-09-12T19:58:50.203Z", "answer_score": 488 }
Please answer the following Stack Overflow question: Title: Should I Dispose() DataSet and DataTable? <p>DataSet and DataTable both implement IDisposable, so, by conventional best practices, I should call their Dispose() methods.</p> <p>However, from what I've read so far, DataSet and DataTable don't actually have any unmanaged resources, so Dispose() doesn't actually do much.</p> <p>Plus, I can't just use <code>using(DataSet myDataSet...)</code> because DataSet has a collection of DataTables.</p> <p>So, to be safe, I'd need to iterate through myDataSet.Tables, dispose of each of the DataTables, then dispose of the DataSet.</p> <p>So, is it worth the hassle to call Dispose() on all of my DataSets and DataTables?</p> <p><strong>Addendum:</strong></p> <p>For those of you who think that DataSet should be disposed: In general, the pattern for disposing is to use <code>using</code> or <code>try..finally</code>, because you want to guarantee that Dispose() will be called.</p> <p>However, this gets ugly real fast for a collection. For example, what do you do if one of the calls to Dispose() thrown an exception? Do you swallow it (which is "bad") so that you can continue on to dispose the next element?</p> <p>Or, do you suggest that I just call myDataSet.Dispose(), and forget about disposing the DataTables in myDataSet.Tables? </p>
<p>Here are a couple of discussions explaining why Dispose is not necessary for a DataSet.</p> <p><a href="http://web.archive.org/web/20100724023926/http://www.developerdotstar.com/community/node/247" rel="noreferrer">To Dispose or Not to Dispose ?</a>:</p> <blockquote> <p>The Dispose method in DataSet exists ONLY because of side effect of inheritance-- in other words, it doesn't actually do anything useful in the finalization.</p> </blockquote> <p><a href="http://web.archive.org/web/20081203232123/http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic42917.aspx" rel="noreferrer">Should Dispose be called on DataTable and DataSet objects?</a> includes some explanation from an MVP: </p> <blockquote> <p>The system.data namespace (ADONET) does not contain unmanaged resources. Therefore there is no need to dispose any of those as long as you have not added yourself something special to it.</p> </blockquote> <p><a href="http://www.velocityreviews.com/forums/t90672-understanding-the-dispose-method-and-datasets.html" rel="noreferrer">Understanding the Dispose method and datasets?</a> has a with comment from authority Scott Allen: </p> <blockquote> <p>In pratice we rarely Dispose a DataSet because it offers little benefit"</p> </blockquote> <p>So, the consensus there is that <strong>there is currently no good reason to call Dispose on a DataSet.</strong></p>
{ "question_id": 913228, "question_date": "2009-05-26T23:08:09Z", "question_score": 213, "tags": "datatable|dataset|dispose|idisposable|using", "answer_id": 913286, "answer_date": "2009-05-26T23:29:07.663Z", "answer_score": 162 }
Please answer the following Stack Overflow question: Title: Unable to execute dex: GC overhead limit exceeded in Eclipse <p>When I downloaded the Git project <a href="http://osmand.net" rel="noreferrer">OsmAnd</a> and went to compile it, Eclipse returned these errors:</p> <pre class="lang-none prettyprint-override"><code>[Dex Loader] Unable to execute dex: GC overhead limit exceeded [OsmAnd] Conversion to Dalvik format failed: Unable to execute dex: GC overhead limit exceeded </code></pre> <p>Google and Stackoverflow said that I must change <code>-Xms40m</code> <code>-Xmx384m</code> in <code>eclipse.ini</code>. <a href="https://stackoverflow.com/questions/5943712/conversion-to-dalvik-format-failed-unable-to-execute-dex-java-heap-space">Conversion to Dalvik format failed: Unable to execute dex: Java heap space</a>.<br> I cleaned project and restarted Eclipse, but it did not help.</p> <p>I found this link: <a href="http://www.cuteandroid.com/tips-for-android-developer-conversion-to-dalvik-format-failed-unable-to-execute-dex-null" rel="noreferrer">Tips for Android developer: “Conversion to Dalvik format failed: Unable to execute dex: null”</a> But I do not know which <code>.jar</code> from my project to change the input in. If anyone can help, I can send the project to them.</p>
<p>It can be fixed by changing the VM values in Eclipse.ini. Set the values to 512 and 1024 as below:</p> <pre><code>openFile --launcher.XXMaxPermSize 512M -showsplash org.eclipse.platform --launcher.defaultAction openFile -vmargs -Dosgi.requiredJavaVersion=1.5 -Xms512m -Xmx1024m </code></pre> <p>The changed area in image <img src="https://i.stack.imgur.com/caO9K.png" alt="enter image description here"></p>
{ "question_id": 9471194, "question_date": "2012-02-27T19:44:02.733Z", "question_score": 213, "tags": "java|android|out-of-memory|dalvik", "answer_id": 11093228, "answer_date": "2012-06-19T01:23:53.717Z", "answer_score": 437 }
Please answer the following Stack Overflow question: Title: How do I know if a generator is empty from the start? <p>Is there a simple way of testing if the generator has no items, like <code>peek</code>, <code>hasNext</code>, <code>isEmpty</code>, something along those lines?</p>
<p>The simple answer to your question: no, there is no simple way. There are a whole lot of work-arounds.</p> <p>There really shouldn't be a simple way, because of what generators are: a way to output a sequence of values <em>without holding the sequence in memory</em>. So there's no backward traversal.</p> <p>You could write a has_next function or maybe even slap it on to a generator as a method with a fancy decorator if you wanted to.</p>
{ "question_id": 661603, "question_date": "2009-03-19T09:51:24.130Z", "question_score": 213, "tags": "python|generator", "answer_id": 662925, "answer_date": "2009-03-19T16:25:12.830Z", "answer_score": 72 }
Please answer the following Stack Overflow question: Title: How to create an exit message <p>Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as:</p> <pre><code>die("Message goes here") </code></pre> <p>I'm tired of typing this:</p> <pre><code>puts "Message goes here" exit </code></pre>
<p>The <code>abort</code> function does this. For example:</p> <pre><code>abort("Message goes here") </code></pre> <p>Note: the <code>abort</code> message will be written to <code>STDERR</code> as opposed to <code>puts</code> which will write to <code>STDOUT</code>.</p>
{ "question_id": 29539, "question_date": "2008-08-27T04:48:50.417Z", "question_score": 213, "tags": "ruby", "answer_id": 86325, "answer_date": "2008-09-17T18:50:05.210Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: Source code highlighting in LaTeX <p>I need to highlight source code in LaTeX. The package <code>listings</code> seems to be the best choice for most use-cases and for me it was, until now.</p> <p>However, now I need more flexibility. Generally, what I’m looking for is a <em>real</em> lexer. In particular, I need (for an own language definition) to define (and highlight!) own number styles. <code>listings</code> does not allow highlighting numbers in code. However, I need to produce something like this:</p> <p><img src="https://i.stack.imgur.com/Hh4W1.png" alt="Required result"></p> <p><code>listings</code> also cannot cope with arbitrary delimiters for strings. Consider the following valid Ruby code:</p> <pre><code>s = %q!this is a string.! </code></pre> <p>Here, <code>!</code> can be replaced by almost <em>any</em> delimiter.</p> <p>(That <code>listings</code> cannot handle Unicode is also quite vexing, but that’s another issue.)</p> <p><strong>Ideally, I am looking for an extension of <code>listings</code> that allows me to provide more complex lexing rules. But barring that, I am also searching for viable alternatives.</strong></p> <p><a href="https://stackoverflow.com/questions/300521/latex-package-to-do-syntax-highlighting-of-code-in-various-languages/1452086#1452086">Other threads</a> have suggested using <a href="http://pygments.org/" rel="noreferrer">Pygments</a> which can produce LaTeX output. There’s even a package – <a href="http://www.ctan.org/tex-archive/macros/latex/contrib/texments/" rel="noreferrer"><code>texments</code></a> – to ease the transition.</p> <p>However, this sorely lacks features. In particular, I am interested in <code>listings</code>-style line numbering, source code line references, and the possibility of embedding LaTeX in source code (options <code>texcl</code> and <code>mathescape</code> in <code>listings</code>).</p> <p>As an example, here’s a source code typeset with <code>listings</code> which shows some of the things that a replacement should also provide:</p> <p><img src="https://i.stack.imgur.com/9Guwv.png" alt="LaTeX listings example: Sideways addition"> <sup><sub>[“Sideways addition” modified from Bit Twiddling Hacks]</sub></sup></p>
<p>Taking Norman’s advice to heart, I’ve hacked together a solution that used (a <a href="https://bitbucket.org/birkenfeld/pygments-main/changeset/0f61d8e9d1ce" rel="noreferrer">patched</a>) Pygments for highlighting and pushed in as many features as possible without bursting ;-)</p> <p>I’ve also created a LateX package, once my Pygments patch was released in <a href="http://pygments.org/download/" rel="noreferrer">version 1.2</a> …</p> <h1>Presenting <em>minted</em></h1> <p><strong><a href="http://tug.ctan.org/tex-archive/macros/latex/contrib/minted/" rel="noreferrer"><em>minted</em></a></strong> is a package that uses Pygments to provide top-notch syntax highlighting in LaTeX. For example, it allows the following output.</p> <p><img src="https://i.stack.imgur.com/OLUjl.png" alt="fancy LaTeX example"></p> <p>Here’s a minimal file to reproduce the above code (notice that including Unicode characters might require XeTeX)!</p> <pre><code>\documentclass[a4paper]{article} \usepackage{fontspec} \usepackage{minted} \setsansfont{Calibri} \setmonofont{Consolas} \begin{document} \renewcommand{\theFancyVerbLine}{ \sffamily\textcolor[rgb]{0.5,0.5,0.5}{\scriptsize\arabic{FancyVerbLine}}} \begin{minted}[mathescape, linenos, numbersep=5pt, gobble=2, frame=lines, framesep=2mm]{csharp} string title = "This is a Unicode π in the sky" /* Defined as $\pi=\lim_{n\to\infty}\frac{P_n}{d}$ where $P$ is the perimeter of an $n$-sided regular polygon circumscribing a circle of diameter $d$. */ const double pi = 3.1415926535 \end{minted} \end{document} </code></pre> <p>This can be typeset using the following command:</p> <pre><code>xelatex -shell-escape test.tex </code></pre> <p>(But <em>minted</em> also works with <code>latex</code> and <code>pdflatex</code> …)</p> <p><code>minted.sty</code> works similar to <code>texments.sty</code> but allows additional features.</p> <h2>How to get it</h2> <ul> <li><p><em>minted</em> is <a href="http://tug.ctan.org/tex-archive/macros/latex/contrib/minted/" rel="noreferrer">listed on CTAN</a> (<a href="http://tug.ctan.org/pkg/minted" rel="noreferrer">package info</a>)</p></li> <li><p><strong>documentation</strong> is of course included.</p></li> <li><p><em>minted</em> is now maintained by Geoffrey Poore. The development version, including the latest <a href="https://github.com/gpoore/minted/blob/master/source/minted.sty" rel="noreferrer"><code>.sty</code> file</a>, is available at <a href="https://github.com/gpoore/minted" rel="noreferrer">github.com/gpoore/minted</a>, and can be cloned from there.</p></li> </ul> <p>Once again, thanks to Norman for motivating me to produce this package.</p>
{ "question_id": 1966425, "question_date": "2009-12-27T17:07:54.793Z", "question_score": 213, "tags": "latex|syntax-highlighting|pygments", "answer_id": 1985330, "answer_date": "2009-12-31T13:02:32.530Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: How do I use Notepad++ (or other) with msysgit? <p>How do I use Notepad++ (or any other editor besides vim) with msysgit?</p> <p>I tried all of the following to no avail:</p> <pre><code>git config --global core.editor C:\Program Files\Notepad++\notepad++.exe git config --global core.editor "C:\Program Files\Notepad++\notepad++.exe" git config --global core.editor C:/Program Files/Notepad++/notepad++.exe git config --global core.editor C:\\Program Files\\Notepad++\\notepad++.exe </code></pre>
<p>Update 2010-2011:</p> <p><a href="https://stackoverflow.com/users/75129/zumalifeguard">zumalifeguard</a>'s <a href="https://stackoverflow.com/questions/1634161/how-do-i-use-notepad-or-other-with-msysgit/2486342#2486342">solution</a> (upvoted) is simpler than the original one, as it no longer needs a shell wrapper script.</p> <p>As I explain in &quot;<a href="https://stackoverflow.com/a/773973/6309">How can I set up an editor to work with Git on Windows?</a>&quot;, <strong>I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a <code>git config</code> again</strong>.<br /> But that is just me.</p> <hr /> <p><em>Additional information</em>: the following solution works with <strong>Cygwin</strong>, while the zuamlifeguard's solution does not.</p> <hr /> <p>Original answer.</p> <p>The following:</p> <pre class="lang-sh prettyprint-override"><code>C:\prog\git&gt;git config --global core.editor C:/prog/git/npp.sh C:/prog/git/npp.sh: #!/bin/sh &quot;c:/Program Files/Notepad++/notepad++.exe&quot; -multiInst &quot;$*&quot; </code></pre> <p>does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a <code>sh</code> script.<br /> (As <a href="https://stackoverflow.com/users/412549/franky">Franky</a> <a href="https://stackoverflow.com/questions/1634161/how-do-i-use-notepad-or-other-with-msysgit/1635493#comment51287812_1635493">comments</a>: &quot;Remember to save your <code>.sh</code> file with Unix style line endings or receive mysterious error messages!&quot;)</p> <p>More details on the SO question <a href="https://stackoverflow.com/q/10564/6309">How can I set up an editor to work with Git on Windows?</a></p> <p>Note the '<code>-multiInst</code>' option, for ensuring a new instance of notepad++ for each call from Git.</p> <p>Note also that, if you are using Git on <strong>Cygwin</strong> (and want to <a href="https://superuser.com/questions/168971/use-notepad-from-cygwin-without-having-the-shell-wait-for-an-exit-code">use Notepad++ from Cygwin</a>), then <a href="https://stackoverflow.com/users/425715/scphantm">scphantm</a> explains in &quot;<a href="https://stackoverflow.com/q/10209660/6309">using Notepad++ for Git inside Cygwin</a>&quot; that you must be aware that:</p> <blockquote> <p><code>git</code> is passing it a <code>cygwin</code> path and <code>npp</code> doesn't know what to do with it</p> </blockquote> <p>So the script in that case would be:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh &quot;C:/Program Files (x86)/Notepad++/notepad++.exe&quot; -multiInst -notabbar -nosession -noPlugin &quot;$(cygpath -w &quot;$*&quot;)&quot; </code></pre> <p>Multiple lines for readability:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh &quot;C:/Program Files (x86)/Notepad++/notepad++.exe&quot; -multiInst -notabbar \ -nosession -noPlugin &quot;$(cygpath -w &quot;$*&quot;)&quot; </code></pre> <p>With <strong><code>&quot;$(cygpath -w &quot;$*&quot;)&quot;</code></strong> being the important part here.</p> <p><a href="https://stackoverflow.com/users/1083704/val">Val</a> <a href="https://stackoverflow.com/questions/1634161/how-do-i-use-notepad-or-other-with-msysgit/1635493?noredirect=1#comment29027434_1635493">commented</a> (and then deleted) that you should not use <code>-notabbar</code> option:</p> <blockquote> <p>It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since <code>-notab</code> becomes the default setting and you must <code>Settings&gt;Preferences&gt;General&gt;TabBar&gt; Hide&gt;uncheck</code> every time you start notepad after rebase. This is hell. You recommended the hell.</p> </blockquote> <p>So use rather:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh &quot;C:/Program Files (x86)/Notepad++/notepad++.exe&quot; -multiInst -nosession -noPlugin &quot;$(cygpath -w &quot;$*&quot;)&quot; </code></pre> <p>That is:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh &quot;C:/Program Files (x86)/Notepad++/notepad++.exe&quot; -multiInst -nosession \ -noPlugin &quot;$(cygpath -w &quot;$*&quot;)&quot; </code></pre> <hr /> <p>If you want to place the script '<code>npp.sh</code>' in a path with spaces (as in '<code>c:\program files\...</code>',), you have three options:</p> <ul> <li><p>Either try to quote the path (single or double quotes), as in:</p> <pre class="lang-sh prettyprint-override"><code> git config --global core.editor 'C:/program files/git/npp.sh' </code></pre> </li> <li><p>or try the <a href="https://stackoverflow.com/a/892568/6309">shortname notation</a> (not fool-proofed):</p> <pre class="lang-sh prettyprint-override"><code> git config --global core.editor C:/progra~1/git/npp.sh </code></pre> </li> <li><p>or (my favorite) place '<code>npp.sh</code>' in a directory part of your <code>%PATH%</code> environment variable. You would not have then to specify any path for the script.</p> <pre class="lang-sh prettyprint-override"><code> git config --global core.editor npp.sh </code></pre> </li> <li><p><a href="https://stackoverflow.com/users/367796/steiny">Steiny</a> reports <a href="https://stackoverflow.com/questions/1634161/how-do-i-use-notepad-or-other-with-msysgit/1635493#comment48770355_1635493">in the comments</a> having to do:</p> <pre class="lang-sh prettyprint-override"><code> git config --global core.editor '&quot;C:/Program Files (x86)/Git/scripts/npp.sh&quot;' </code></pre> </li> </ul>
{ "question_id": 1634161, "question_date": "2009-10-27T22:59:28.703Z", "question_score": 213, "tags": "git|configuration|text-editor|notepad++|msysgit", "answer_id": 1635493, "answer_date": "2009-10-28T06:28:28.127Z", "answer_score": 78 }
Please answer the following Stack Overflow question: Title: Xcode: Build Failed, but no error messages <p>Using Xcode 4.5.1. Our project has been building fine for the last three months, but suddenly, when I try to build, it says "Build failed", but does not show any errors on the triangle exclamation mark tab, nor does it give a reason when it pops up build failed.</p> <p>We have not changed the bundle identifier, or any other project properties. I tried a clean, then build, but no luck.</p> <p>What may be causing the problem?</p> <p>Similar to <a href="https://stackoverflow.com/questions/5363564/xcode-4-build-failed-no-issues">this question</a>, but none of the solutions apply.</p>
<p>Figured it out. On the tab with three lines in a speech bubble, it shows a build log. I guess my storyboard file had become corrupt during the last git pull.</p> <img src="https://i.stack.imgur.com/R5boL.png"/> <p><strong>For Xcode 12+</strong> <a href="https://i.stack.imgur.com/0cbvw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0cbvw.png" alt="screenshot of Xcode 12 toolbar" /></a></p>
{ "question_id": 14625389, "question_date": "2013-01-31T12:05:15.117Z", "question_score": 213, "tags": "xcode|build", "answer_id": 14625517, "answer_date": "2013-01-31T12:11:49.020Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: How to use RSpec's should_raise with any kind of exception? <p>I'd like to do something like this:</p> <pre><code>some_method.should_raise &lt;any kind of exception, I don't care&gt; </code></pre> <p>How should I do this?</p> <pre><code>some_method.should_raise exception </code></pre> <p>... doesn't work.</p>
<pre><code>expect { some_method }.to raise_error </code></pre> <p><strong>RSpec 1 Syntax:</strong></p> <pre><code>lambda { some_method }.should raise_error </code></pre> <p>See <a href="http://rspec.rubyforge.org/rspec/1.2.9/classes/Spec/Matchers.html#M000176" rel="noreferrer">the documentation</a> (for RSpec 1 syntax) and <a href="http://rubydoc.info/gems/rspec-expectations/frames" rel="noreferrer">RSpec 2 documentation</a> for more.</p>
{ "question_id": 1722749, "question_date": "2009-11-12T14:53:22.077Z", "question_score": 213, "tags": "ruby-on-rails|ruby|exception-handling|rspec", "answer_id": 1722839, "answer_date": "2009-11-12T15:04:49.217Z", "answer_score": 380 }
Please answer the following Stack Overflow question: Title: Lambda capture as const reference? <p>Is it possible to capture by <code>const</code> reference in a lambda expression?</p> <p>I want the assignment marked below to fail, for example:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;string&gt; using namespace std; int main() { string strings[] = { &quot;hello&quot;, &quot;world&quot; }; static const size_t num_strings = sizeof(strings)/sizeof(strings[0]); string best_string = &quot;foo&quot;; for_each( &amp;strings[0], &amp;strings[num_strings], [&amp;best_string](const string&amp; s) { best_string = s; // this should fail } ); return 0; } </code></pre> <p><em>Update:</em> As this is an old question, it might be good to update it if there are facilities in C++14 to help with this. Do the extensions in C++14 allow us to capture a non-const object by const reference? (<em>August 2015</em>)</p>
<p><code>const</code> isn't in the grammar for captures as of n3092:</p> <pre><code>capture: identifier &amp; identifier this </code></pre> <p>The text only mention capture-by-copy and capture-by-reference and doesn't mention any sort of const-ness.</p> <p>Feels like an oversight to me, but I haven't followed the standardization process very closely.</p>
{ "question_id": 3772867, "question_date": "2010-09-22T19:23:36.567Z", "question_score": 213, "tags": "c++|c++11|lambda|c++14", "answer_id": 3772980, "answer_date": "2010-09-22T19:40:16.753Z", "answer_score": 137 }
Please answer the following Stack Overflow question: Title: Stream.Seek(0, SeekOrigin.Begin) or Position = 0 <p>When you need to reset a stream to beginning (e.g. <code>MemoryStream</code>) is it best practice to use</p> <pre><code>stream.Seek(0, SeekOrigin.Begin); </code></pre> <p>or </p> <pre><code>stream.Position = 0; </code></pre> <p>I've seen both work fine, but wondered if one was more correct than the other?</p>
<p>Use <code>Position</code> when setting an absolute position and <code>Seek</code> when setting a relative position. Both are provided for convenience so you can choose one that fits the style and readability of your code. Accessing <code>Position</code> requires the stream be seekable so they're safely interchangeable.</p>
{ "question_id": 7238929, "question_date": "2011-08-30T05:07:52.430Z", "question_score": 213, "tags": "c#|.net|stream", "answer_id": 7239011, "answer_date": "2011-08-30T05:22:26.590Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: What is q=0.5 in Accept* HTTP headers? <pre><code>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 </code></pre> <p>What do these 'q=%f' mean?</p>
<p>This is called a <strong>relative quality factor</strong>. It specifies what language the user would prefer, on a scale of 0 to 1, as can be seen from the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4" rel="noreferrer">HTTP/1.1 Specification, §14.4</a>:</p> <blockquote> <p>Each language-range MAY be given an associated quality value which represents an estimate of the user's preference for the languages specified by that range. The quality value defaults to &quot;q=1&quot;. For example,</p> <pre><code> Accept-Language: da, en-gb;q=0.8, en;q=0.7 </code></pre> <p>would mean: &quot;I prefer Danish, but will accept British English and other types of English.&quot;</p> </blockquote>
{ "question_id": 8552927, "question_date": "2011-12-18T16:04:15.347Z", "question_score": 213, "tags": "http|http-headers", "answer_id": 8552941, "answer_date": "2011-12-18T16:06:23.793Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: How can I specify the base for Math.log() in JavaScript? <p>I need a <code>log</code> function for JavaScript, but it needs to be base 10. I can't see any listing for this, so I'm assuming it's not possible. Are there any math wizards out there who know a solution for this?</p>
<p><strong>"Change of Base" Formula / Identity</strong></p> <blockquote> <p>The numerical value for logarithm to the base 10 can be calculated with the following identity.</p> </blockquote> <p><a href="http://en.wikipedia.org/wiki/Common_logarithm#Numeric_value" rel="noreferrer"><img src="https://upload.wikimedia.org/math/b/8/6/b865df69b449daf0523e9a19bb86603c.png" alt="Logarithm for base 10"></a></p> <hr> <p>Since <code>Math.log(x)</code> in JavaScript returns the natural logarithm of <code>x</code> (same as <em>ln(x)</em>), for base 10 you can divide by <code>Math.log(10)</code> (same as <em>ln(10)</em>):</p> <pre><code>function log10(val) { return Math.log(val) / Math.LN10; } </code></pre> <p><code>Math.LN10</code> is a built-in precomputed constant for <code>Math.log(10)</code>, so this function is essentially identical to:</p> <pre><code>function log10(val) { return Math.log(val) / Math.log(10); } </code></pre>
{ "question_id": 3019278, "question_date": "2010-06-10T23:30:55.940Z", "question_score": 213, "tags": "javascript|math|logarithm", "answer_id": 3019290, "answer_date": "2010-06-10T23:33:25.180Z", "answer_score": 342 }
Please answer the following Stack Overflow question: Title: Why charset names are not constants? <p>Charset issues are confusing and complicated by themselves, but on top of that you have to remember exact names of your charsets. Is it <code>"utf8"</code>? Or <code>"utf-8"</code>? Or maybe <code>"UTF-8"</code>? When searching internet for code samples you will see all of the above. Why not just make them named constants and use <code>Charset.UTF8</code>?</p>
<p>The simple answer to the question asked is that the available charset strings vary from platform to platform.</p> <p>However, there are six that are required to be present, so constants could have been made for those long ago. I don't know why they weren't.</p> <p>JDK 1.4 did a great thing by introducing the Charset type. At this point, they wouldn't have wanted to provide String constants anymore, since the goal is to get everyone using Charset instances. So why not provide the six standard Charset constants, then? I asked Martin Buchholz since he happens to be sitting right next to me, and he said there wasn't a really particularly great reason, except that at the time, things were still half-baked -- too few JDK APIs had been retrofitted to accept Charset, and of the ones that were, the Charset overloads usually performed slightly worse.</p> <p>It's sad that it's only in JDK 1.6 that they finally finished outfitting everything with Charset overloads. And that this backwards performance situation still exists (the reason why is incredibly weird and I can't explain it, but is related to security!).</p> <p>Long story short -- just define your own constants, or use Guava's Charsets class which Tony the Pony linked to (though that library is not really actually released yet).</p> <p><strong>Update:</strong> a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html" rel="noreferrer"><code>StandardCharsets</code></a> class is in JDK 7.</p>
{ "question_id": 1684040, "question_date": "2009-11-05T22:18:23.893Z", "question_score": 213, "tags": "java|character-encoding", "answer_id": 1684182, "answer_date": "2009-11-05T22:43:51.193Z", "answer_score": 161 }
Please answer the following Stack Overflow question: Title: How to store a git config as part of the repository? <p>I'm using filters to mangle files during checkout like described <a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Keyword-Expansion" rel="noreferrer">here</a>. Now the problem is that filter definition is only stored in my local configuration file:</p> <pre><code>$ cat .git/config .... [filter "dater"] smudge = /home/.../expand_date clean = perl -pe \"s/\\\\\\$Date[^\\\\\\$]*\\\\\\$/\\\\\\$Date\\\\\\$/\" </code></pre> <p>If my coworkers want to benefit from this <code>Date</code> expansion, they need to copy my filter definition. And if I change it, I need to notify them, etc..</p> <p>So can I store this filter definition part of <code>.git/config</code> in repository and make git use it?</p>
<p>There are 3 supported scopes of <code>.gitconfig</code> file: <code>--system, --global, --local</code>. You can also create a custom configuration file, and include it in one of the supported files.</p> <p>For your needs <strong>custom</strong> - is the right choice. Instead of writing your filter in <code>.git/config</code> you should save it in <code>.gitconfig</code> file in your repository root:</p> <pre><code>your-repo/ │ ├── .git/ │ ├── config │ ├── .gitconfig │ </code></pre> <p>Create the <code>.gitconfig</code> with your filter and commit the changes. Then your colleagues will always keep it updated -- but they will have to include it manually. <strong>It is not possible to automatically include your custom configuration file</strong> through git alone, because it creates a security vulnerability.</p> <p>To apply this configuration for a single repository, each user will need to run the following command in <code>your-repo/</code>:</p> <pre><code>git config --local include.path ../.gitconfig </code></pre> <p>Reference: <a href="https://git-scm.com/docs/git-config#_includes" rel="noreferrer">https://git-scm.com/docs/git-config#_includes</a></p> <p>Be careful not to store personal data in the custom <code>.gitconfig</code>, like <code>user.*</code>, keep those in your global <code>.gitconfig</code>.</p>
{ "question_id": 18329621, "question_date": "2013-08-20T07:48:27.093Z", "question_score": 213, "tags": "git", "answer_id": 18330114, "answer_date": "2013-08-20T08:15:20.933Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector <p>I am starting to learn Swift, and have been following the very good Stanford University video lectures on YouTube. Here is a link if you are interested or it helps (although it isn't required to understand my problem):</p> <p><a href="https://itunes.apple.com/ca/course/2.-more-xcode-and-swift-mvc/id961180099?i=333886879&amp;mt=2">Developing iOS 8 Apps with Swift - 2. More Xcode and Swift, MVC</a></p> <p>While following the lectures I got to a point where (as far as I could tell) my code was identical to the code in the video but on my system I got a compiler error. After a lot of trial and error I have managed to reduce my code to two examples, one of which generates an error, the other or which doesn't, but I have no idea what is actually causing the error or how to resolve it.</p> <p>The code which creates the error is:</p> <pre><code>import UIKit class BugViewController: UIViewController { func perform(operation: (Double) -&gt; Double) { } func perform(operation: (Double, Double) -&gt; Double) { } } </code></pre> <p>This creates the following compiler error:</p> <blockquote> <p>Method 'perform' with Objective-C selector 'perform: ' conflicts with previous declaration with the same Objective-C selector</p> </blockquote> <p>By simply removing the sub-classing of UIViewController the code compiles:</p> <pre><code>import UIKit class BugViewController { func perform(operation: (Double) -&gt; Double) { } func perform(operation: (Double, Double) -&gt; Double) { } } </code></pre> <p>Some other information which may or may not be relevant:</p> <ul> <li>I have recently upgraded to Yosemite.</li> <li>When I installed Xcode, I ended up with a Beta version (Version 6.3 (6D543q)) because (if I remember correctly) this was the version I needed to run on my version of OS X.</li> </ul> <p>I am half hoping this is a bug in the compiler because otherwise this doesn't make any sense to me. Any help very gratefully received!</p>
<p>Objective-C does not support method overloading, you have to use a different method name. When you inherited UIViewController you inherited NSObject and made the class interopable to Obj-C. Swift on the other hand does support overloading, that's why it works when you remove the inheritance.</p>
{ "question_id": 29457720, "question_date": "2015-04-05T13:19:12.333Z", "question_score": 213, "tags": "swift", "answer_id": 29457777, "answer_date": "2015-04-05T13:26:07.707Z", "answer_score": 146 }
Please answer the following Stack Overflow question: Title: Gradle buildscript dependencies <p>What is the difference between declaring repositories in the <code>buildscript</code> section of the gradle build or in the root level of the build.</p> <pre><code>buildscript { repositories { mavenCentral(); } } </code></pre> <p>versus</p> <pre><code>repositories { mavenCentral(); } </code></pre>
<p>The repositories in the <code>buildscript</code> block are used to fetch the dependencies of your <code>buildscript</code> dependencies. These are the dependencies that are put on the classpath of your build and that you can refer to from your build file. For instance extra plugins that exist on the internet.</p> <p>The repositories on the root level are used to fetch the dependencies that your project depends on. So all the dependencies you need to compile your project.</p>
{ "question_id": 13923766, "question_date": "2012-12-17T23:07:11.137Z", "question_score": 213, "tags": "build|repository|gradle", "answer_id": 13932793, "answer_date": "2012-12-18T12:15:42.753Z", "answer_score": 193 }
Please answer the following Stack Overflow question: Title: How do I get bash completion to work with aliases? <p>Case in point: </p> <p>I'm a on mac with bash v3.2.17, I'm using git installed via macports with the bash_completion variant.</p> <p>When I type <code>git checkout m&lt;tab&gt;</code>. for example, I get it completed to <code>master</code>.</p> <p>However, I've got an alias to <code>git checkout</code>, <code>gco</code>. When I type <code>gco m&lt;tab&gt;</code>, I don't get the branch name autocompleted.</p> <p>Ideally I'd like autocompletion to just magically work for all my aliases. Is it possible? Failing that, I'd like to manually customize it for each alias. So, how do I go about either?</p>
<p>As stated in the comments above,</p> <pre><code>complete -o default -o nospace -F _git_checkout gco </code></pre> <p>will no longer work. However, there's a <code>__git_complete</code> function in git-completion.bash which can be used to set up completion for aliases like so:</p> <pre><code>__git_complete gco _git_checkout </code></pre>
{ "question_id": 342969, "question_date": "2008-12-05T05:17:09.693Z", "question_score": 213, "tags": "git|bash|shell|unix|autocomplete", "answer_id": 15009611, "answer_date": "2013-02-21T18:25:48.963Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: When is -XAllowAmbiguousTypes appropriate? <p>I've recently posted a <a href="https://stackoverflow.com/questions/23448150/techniques-for-tracing-constraints">question</a> about <a href="https://github.com/emilaxelsson/syntactic" rel="noreferrer">syntactic-2.0</a> regarding the definition of <code>share</code>. I've had this working in <strong>GHC 7.6</strong>:</p> <pre><code>{-# LANGUAGE GADTs, TypeOperators, FlexibleContexts #-} import Data.Syntactic import Data.Syntactic.Sugar.BindingT data Let a where Let :: Let (a :-&gt; (a -&gt; b) :-&gt; Full b) share :: (Let :&lt;: sup, sup ~ Domain b, sup ~ Domain a, Syntactic a, Syntactic b, Syntactic (a -&gt; b), SyntacticN (a -&gt; (a -&gt; b) -&gt; b) fi) =&gt; a -&gt; (a -&gt; b) -&gt; b share = sugarSym Let </code></pre> <p>However, GHC 7.8 wants <code>-XAllowAmbiguousTypes</code> to compile with that signature. Alternatively, I can replace the <code>fi</code> with </p> <pre><code>(ASTF sup (Internal a) -&gt; AST sup ((Internal a) :-&gt; Full (Internal b)) -&gt; ASTF sup (Internal b)) </code></pre> <p>which is the type implied by the fundep on <code>SyntacticN</code>. This allows me to avoid the extension. Of course this is </p> <ul> <li>a very long type to add to an already-large signature</li> <li>tiresome to manually derive</li> <li>unnecessary due to the fundep</li> </ul> <p>My questions are:</p> <ol> <li>Is this an acceptable use of <code>-XAllowAmbiguousTypes</code>?</li> <li>In general, when should this extension be used? An answer <a href="https://stackoverflow.com/questions/23461560/how-can-i-extract-this-polymorphic-recursion-function/23462397#23462397">here</a> suggests "it is almost never a good idea".</li> <li><p>Though I've read <a href="http://www.haskell.org/ghc/docs/7.8.2/html/users_guide/other-type-extensions.html#ambiguity" rel="noreferrer">the docs</a>, I'm still having trouble deciding if a constraint is ambiguous or not. Specifically, consider this function from Data.Syntactic.Sugar:</p> <pre><code>sugarSym :: (sub :&lt;: AST sup, ApplySym sig fi sup, SyntacticN f fi) =&gt; sub sig -&gt; f sugarSym = sugarN . appSym </code></pre> <p>It appears to me that <code>fi</code> (and possibly <code>sup</code>) should be ambiguous here, but it compiles without the extension. Why is <code>sugarSym</code> unambiguous while <code>share</code> is? Since <code>share</code> is an application of <code>sugarSym</code>, the <code>share</code> constraints all come straight from <code>sugarSym</code>.</p></li> </ol>
<p>I don't see any published version of syntactic whose signature for <code>sugarSym</code> uses those exact type names, so I'll be using <a href="https://github.com/emilaxelsson/syntactic/tree/8cfd021b8560a951b169cdaf0ac69a838e77de%5E">the development branch at commit 8cfd02^</a>, the last version which still used those names.</p> <p>So, why does GHC complain about the <code>fi</code> in your type signature but not the one for <code>sugarSym</code>? The documentation you have linked to explains that a type is ambiguous if it doesn't appear to the right of the constraint, unless the constraint is using functional dependencies to infer the otherwise-ambiguous type from other non-ambiguous types. So let's compare the contexts of the two functions and look for functional dependencies.</p> <pre><code>class ApplySym sig f sym | sig sym -&gt; f, f -&gt; sig sym class SyntacticN f internal | f -&gt; internal sugarSym :: ( sub :&lt;: AST sup , ApplySym sig fi sup , SyntacticN f fi ) =&gt; sub sig -&gt; f share :: ( Let :&lt;: sup , sup ~ Domain b , sup ~ Domain a , Syntactic a , Syntactic b , Syntactic (a -&gt; b) , SyntacticN (a -&gt; (a -&gt; b) -&gt; b) fi ) =&gt; a -&gt; (a -&gt; b) -&gt; b </code></pre> <p>So for <code>sugarSym</code>, the non-ambiguous types are <code>sub</code>, <code>sig</code> and <code>f</code>, and from those we should be able to follow functional dependencies in order to disambiguate all the other types used in the context, namely <code>sup</code> and <code>fi</code>. And indeed, the <code>f -&gt; internal</code> functional dependency in <code>SyntacticN</code> uses our <code>f</code> to disambiguate our <code>fi</code>, and thereafter the <code>f -&gt; sig sym</code> functional dependency in <code>ApplySym</code> uses our newly-disambiguated <code>fi</code> to disambiguate <code>sup</code> (and <code>sig</code>, which was already non-ambiguous). So that explains why <code>sugarSym</code> doesn't require the <code>AllowAmbiguousTypes</code> extension.</p> <p>Let's now look at <code>sugar</code>. The first thing I notice is that the compiler is <em>not</em> complaining about an ambiguous type, but rather, about overlapping instances:</p> <pre><code>Overlapping instances for SyntacticN b fi arising from the ambiguity check for ‘share’ Matching givens (or their superclasses): (SyntacticN (a -&gt; (a -&gt; b) -&gt; b) fi1) Matching instances: instance [overlap ok] (Syntactic f, Domain f ~ sym, fi ~ AST sym (Full (Internal f))) =&gt; SyntacticN f fi -- Defined in ‘Data.Syntactic.Sugar’ instance [overlap ok] (Syntactic a, Domain a ~ sym, ia ~ Internal a, SyntacticN f fi) =&gt; SyntacticN (a -&gt; f) (AST sym (Full ia) -&gt; fi) -- Defined in ‘Data.Syntactic.Sugar’ (The choice depends on the instantiation of ‘b, fi’) To defer the ambiguity check to use sites, enable AllowAmbiguousTypes </code></pre> <p>So if I'm reading this right, it's not that GHC thinks that your types are ambiguous, but rather, that while checking whether your types are ambiguous, GHC encountered a different, separate problem. It's then telling you that if you told GHC not to perform the ambiguity check, it would not have encountered that separate problem. This explains why enabling AllowAmbiguousTypes allows your code to compile.</p> <p>However, the problem with the overlapping instances remain. The two instances listed by GHC (<code>SyntacticN f fi</code> and <code>SyntacticN (a -&gt; f) ...</code>) do overlap with each other. Strangely enough, it seems like the first of these should overlap with any other instance, which is suspicious. And what does <code>[overlap ok]</code> mean?</p> <p>I suspect that Syntactic is compiled with OverlappingInstances. And looking at <a href="https://github.com/emilaxelsson/syntactic/blob/f29d78e51b43699cbb6d9a911b9b286081c763cd/src/Data/Syntactic/Sugar.hs#L1">the code</a>, indeed it does.</p> <p>Experimenting a bit, it seems that GHC is okay with overlapping instances when it is clear that one is strictly more general than the other:</p> <pre><code>{-# LANGUAGE FlexibleInstances, OverlappingInstances #-} class Foo a where whichOne :: a -&gt; String instance Foo a where whichOne _ = "a" instance Foo [a] where whichOne _ = "[a]" -- | -- &gt;&gt;&gt; main -- [a] main :: IO () main = putStrLn $ whichOne (undefined :: [Int]) </code></pre> <p>But GHC is not okay with overlapping instances when neither is clearly a better fit than the other:</p> <pre><code>{-# LANGUAGE FlexibleInstances, OverlappingInstances #-} class Foo a where whichOne :: a -&gt; String instance Foo (f Int) where -- this is the line which changed whichOne _ = "f Int" instance Foo [a] where whichOne _ = "[a]" -- | -- &gt;&gt;&gt; main -- Error: Overlapping instances for Foo [Int] main :: IO () main = putStrLn $ whichOne (undefined :: [Int]) </code></pre> <p>Your type signature uses <code>SyntacticN (a -&gt; (a -&gt; b) -&gt; b) fi</code>, and neither <code>SyntacticN f fi</code> nor <code>SyntacticN (a -&gt; f) (AST sym (Full ia) -&gt; fi)</code> is a better fit than the other. If I change that part of your type signature to <code>SyntacticN a fi</code> or <code>SyntacticN (a -&gt; (a -&gt; b) -&gt; b) (AST sym (Full ia) -&gt; fi)</code>, GHC no longer complains about the overlap.</p> <p>If I were you, I would look at <a href="https://github.com/emilaxelsson/syntactic/blob/f29d78e51b43699cbb6d9a911b9b286081c763cd/src/Data/Syntactic/Sugar.hs#L63">the definition of those two possible instances</a> and determine whether one of those two implementations is the one you want.</p>
{ "question_id": 23684947, "question_date": "2014-05-15T17:27:08.957Z", "question_score": 213, "tags": "haskell|ghc|ambiguous-types", "answer_id": 29825084, "answer_date": "2015-04-23T13:34:25.820Z", "answer_score": 12 }
Please answer the following Stack Overflow question: Title: python: SyntaxError: EOL while scanning string literal <p>I have the above-mentioned error in <code>s1="some very long string............"</code> </p> <p>Does anyone know what I am doing wrong?</p>
<p>You are not putting a <code>"</code> before the end of the line. </p> <p>Use <code>"""</code> if you want to do this:</p> <pre><code>""" a very long string ...... ....that can span multiple lines """ </code></pre>
{ "question_id": 3561691, "question_date": "2010-08-24T23:04:26.770Z", "question_score": 212, "tags": "python|string|string-literals", "answer_id": 3561704, "answer_date": "2010-08-24T23:07:50.030Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: How do I upgrade the Python installation in Windows 10? <p>I have a Python 2.7.11 installed on one of my LAB stations. I would like to upgrade Python to at least 3.5.</p> <p>How should I do that ? Should I prefer to completely uninstall 2.7.11 and than install the new one ? Is there a way to update it ? Is an update a good idea ?</p>
<p>Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.</p> <p>So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.</p> <p>Current Python 3 installations come with the <code>py.exe</code> launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using <code>py</code> instead of <code>python</code> as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use <code>py script.py</code> instead of <code>python script.py</code> to use the launcher. You can also specify a version using for example <code>py -3</code> or <code>py -3.6</code> to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).</p> <p>Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use <code>py -2 script.py</code> to launch a script.</p> <hr> <p>As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install <code>pip</code>; it’s enabled by default, so you already have <code>pip</code> for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use <code>pip</code> though. Luckily, you can also simply use the <code>py.exe</code> launcher for this: <code>py -m pip</code> runs <code>pip</code>. So for example to install Beautiful Soup for Python 3.6, you could run <code>py -3.6 -m pip install beautifulsoup4</code>.</p>
{ "question_id": 45137395, "question_date": "2017-07-17T06:33:37.283Z", "question_score": 212, "tags": "python|python-3.x", "answer_id": 45138817, "answer_date": "2017-07-17T07:59:25.373Z", "answer_score": 163 }
Please answer the following Stack Overflow question: Title: How to close TCP and UDP ports via windows command line <p>Does somebody knows how to close a TCP or UDP socket for a single connection via windows command line?</p> <p>Googling about this, I saw some people asking the same thing. But the answers looked like a manual page of netstat or netsh commands focusing on how to monitor the ports. I don't want answers on how to monitor them (I already do this). I want to close/kill them.</p> <p>EDIT, for clarification: Let's say that my server listens TCP port 80. A client makes a connection and port 56789 is allocated for it. Then, I discover that this connection is undesired (e.g. this user is doing bad things, we asked them to stop but the connection didn't get dropped somewhere along the way). Normally, I would add a firewall to do the job, but this would take some time, and I was in an emergency situation. Killing the process that owns the connection is really a bad idea here because this would take down the server (all users would lose functionality when we just want to selectively and temporally drop this one connection). </p>
<p>Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.</p> <p>Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic. </p> <p>So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it. </p> <p>There is at least one program (<a href="http://www.nirsoft.net/utils/cports.html" rel="noreferrer">CurrPorts</a>) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.</p> <p>Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port. </p>
{ "question_id": 8688949, "question_date": "2011-12-31T15:35:02.367Z", "question_score": 212, "tags": "networking", "answer_id": 14626532, "answer_date": "2013-01-31T13:08:24.723Z", "answer_score": 76 }
Please answer the following Stack Overflow question: Title: How to calculate age (in years) based on Date of Birth and getDate() <p>I have a table listing people along with their date of birth (currently a nvarchar(25))</p> <p>How can I convert that to a date, and then calculate their age in years?</p> <p>My data looks as follows</p> <pre><code>ID Name DOB 1 John 1992-01-09 00:00:00 2 Sally 1959-05-20 00:00:00 </code></pre> <p>I would like to see:</p> <pre><code>ID Name AGE DOB 1 John 17 1992-01-09 00:00:00 2 Sally 50 1959-05-20 00:00:00 </code></pre>
<p>There are issues with leap year/days and the following method, see the update below:</p> <blockquote> <p>try this:</p> <pre><code>DECLARE @dob datetime SET @dob='1992-01-09 00:00:00' SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal ,CONVERT(int,ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound ,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc </code></pre> <p>OUTPUT:</p> <pre><code>AgeYearsDecimal AgeYearsIntRound AgeYearsIntTrunc --------------------------------------- ---------------- ---------------- 17.767054 18 17 (1 row(s) affected) </code></pre> </blockquote> <p><strong>UPDATE</strong> here are some more accurate methods:</p> <p><strong>BEST METHOD FOR YEARS IN INT</strong></p> <pre><code>DECLARE @Now datetime, @Dob datetime SELECT @Now='1990-05-05', @Dob='1980-05-05' --results in 10 --SELECT @Now='1990-05-04', @Dob='1980-05-05' --results in 9 --SELECT @Now='1989-05-06', @Dob='1980-05-05' --results in 9 --SELECT @Now='1990-05-06', @Dob='1980-05-05' --results in 10 --SELECT @Now='1990-12-06', @Dob='1980-05-05' --results in 10 --SELECT @Now='1991-05-04', @Dob='1980-05-05' --results in 10 SELECT (CONVERT(int,CONVERT(char(8),@Now,112))-CONVERT(char(8),@Dob,112))/10000 AS AgeIntYears </code></pre> <p>you can change the above <code>10000</code> to <code>10000.0</code> and get decimals, but it will not be as accurate as the method below.</p> <p><strong>BEST METHOD FOR YEARS IN DECIMAL</strong></p> <pre><code>DECLARE @Now datetime, @Dob datetime SELECT @Now='1990-05-05', @Dob='1980-05-05' --results in 10.000000000000 --SELECT @Now='1990-05-04', @Dob='1980-05-05' --results in 9.997260273973 --SELECT @Now='1989-05-06', @Dob='1980-05-05' --results in 9.002739726027 --SELECT @Now='1990-05-06', @Dob='1980-05-05' --results in 10.002739726027 --SELECT @Now='1990-12-06', @Dob='1980-05-05' --results in 10.589041095890 --SELECT @Now='1991-05-04', @Dob='1980-05-05' --results in 10.997260273973 SELECT 1.0* DateDiff(yy,@Dob,@Now) +CASE WHEN @Now &gt;= DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)) THEN --birthday has happened for the @now year, so add some portion onto the year difference ( 1.0 --force automatic conversions from int to decimal * DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)),@Now) --number of days difference between the @Now year birthday and the @Now day / DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),1,1),DATEFROMPARTS(DATEPART(yyyy,@Now)+1,1,1)) --number of days in the @Now year ) ELSE --birthday has not been reached for the last year, so remove some portion of the year difference -1 --remove this fractional difference onto the age * ( -1.0 --force automatic conversions from int to decimal * DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)),@Now) --number of days difference between the @Now year birthday and the @Now day / DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),1,1),DATEFROMPARTS(DATEPART(yyyy,@Now)+1,1,1)) --number of days in the @Now year ) END AS AgeYearsDecimal </code></pre>
{ "question_id": 1572110, "question_date": "2009-10-15T12:40:07.823Z", "question_score": 212, "tags": "sql|sql-server|tsql", "answer_id": 1572411, "answer_date": "2009-10-15T13:34:53.637Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: How to run the sftp command with a password from Bash script? <p>I need to transfer a log file to a remote host using <a href="http://en.wikipedia.org/wiki/Secure_file_transfer_program" rel="noreferrer">sftp</a> from a Linux host. I have been provided credentials for the same from my operations group. However, since I don't have control over other host, I cannot generate and share RSA keys with the other host. </p> <p>So is there a way to run the <code>sftp</code> command (with the username/password provided) from inside the Bash script through a <a href="http://en.wikipedia.org/wiki/Cron" rel="noreferrer">cron</a> job?</p> <p>I found a similar Stack Overflow question, <em><a href="https://stackoverflow.com/questions/5268865">Specify password to sftp in a Bash script</a></em>, but there was no satisfactory answer to my problem.</p>
<p>You have a few options other than using public key authentication:</p> <ol> <li>Use <a href="http://www.cyberciti.biz/faq/ssh-passwordless-login-with-keychain-for-scripts/" rel="noreferrer">keychain</a></li> <li>Use <a href="http://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/" rel="noreferrer">sshpass</a> (less secured but probably that meets your requirement)</li> <li>Use <a href="https://linux.die.net/man/1/expect" rel="noreferrer">expect</a> (least secured and more coding needed)</li> </ol> <p>If you decide to give sshpass a chance here is a working script snippet to do so:</p> <pre><code>export SSHPASS=your-password-here sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host &lt;&lt; ! cd incoming put your-log-file.log bye ! </code></pre>
{ "question_id": 5386482, "question_date": "2011-03-22T03:40:24.173Z", "question_score": 212, "tags": "bash|shell|unix|ssh|sftp", "answer_id": 5386587, "answer_date": "2011-03-22T03:54:15.717Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: Scroll to a div using jQuery <p>so I have a page that has a fixed link bar on the side. I'd like to scroll to the different divs. Basically the page is just one long website, where I'd like to scroll to different divs using the menu box to the side.</p> <p>Here is the jQuery I have so far</p> <pre><code>$(document).ready(function() { $('#contactlink').click = function() { $(document).scrollTo('#contact'); } }); </code></pre> <p>The issue is it is automatically going to the contact div when it loads, then when I press the <code>#contactlink</code> in the menu it scrolls back to the top.</p> <p>EDIT: HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;!-- jQuery--&gt; &lt;script src = &quot;&lt;?php echo base_url() ?&gt;assets/js/jquery.js&quot;&gt;&lt;/script&gt; &lt;!-- .js file--&gt; &lt;script src = &quot;&lt;?php echo base_url() ?&gt;assets/js/pagetwo.js&quot;&gt;&lt;/script&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;&lt;?php echo base_url()?&gt;assets/css/reset.css&quot; /&gt; &lt;!-- .css for page --&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;&lt;?php echo base_url()?&gt;assets/css/pagetwo.css&quot;/&gt; &lt;!-- page title--&gt; &lt;title&gt;&lt;!-- Insert Title --&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;container&quot;&gt; &lt;div id=&quot;sidebar&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a id = &quot;aboutlink&quot; href=&quot;#&quot;&gt;auck&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = &quot;peojectslink&quot; href=&quot;#&quot;&gt;Projects&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = &quot;resumelink&quot; href=&quot;#&quot;&gt;Resume&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = &quot;contactlink&quot; href=&quot;#&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id=&quot;content&quot;&gt; &lt;div class=&quot;&quot; id=&quot;about&quot;&gt; &lt;p class=&quot;header&quot;&gt;uck&lt;/p&gt; &lt;p class=&quot;info&quot;&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sections&quot;id=&quot;projects&quot;&gt; &lt;p class = &quot;header&quot;&gt;Projects&lt;/p&gt; &lt;p class=&quot;info&quot;&gt;Projects&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sections&quot; id=&quot;resume&quot;&gt; &lt;p class = &quot;header&quot;&gt;Resume&lt;/p&gt; &lt;p class=&quot;info&quot;&gt;Resume&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sections&quot; id=&quot;contacts&quot;&gt; &lt;p class = &quot;header&quot;&gt;Contact&lt;/p&gt; &lt;p class=&quot;info&quot;&gt;Contact&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
<p>First, your code does not contain a <code>contact</code> div, it has a <code>contacts</code> div!</p> <p>In sidebar you have <code>contact</code> in the div at the bottom of the page you have <code>contacts</code>. I removed the final <code>s</code> for the code sample. (you also misspelled the <code>projectslink</code> id in the sidebar).</p> <p>Second, take a look at some of the examples for <a href="https://api.jquery.com/click/" rel="noreferrer">click</a> on the jQuery reference page. You have to use click like, <code>object.click( function() { // Your code here } );</code> in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like <code>object.click()</code>.</p> <p>Third, <code>scrollTo</code> is a <a href="http://plugins.jquery.com/project/ScrollTo" rel="noreferrer">plugin</a> in jQuery. I don't know if you have the plugin installed. You can't use <code>scrollTo()</code> without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.</p> <p>Ok, now on to a solution.</p> <p>The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:</p> <pre><code>// This is a functions that scrolls to #{blah}link function goToByScroll(id) { // Remove &quot;link&quot; from the ID id = id.replace(&quot;link&quot;, &quot;&quot;); // Scroll $('html,body').animate({ scrollTop: $(&quot;#&quot; + id).offset().top }, 'slow'); } $(&quot;#sidebar &gt; ul &gt; li &gt; a&quot;).click(function(e) { // Prevent a page reload when a link is pressed e.preventDefault(); // Call the scroll function goToByScroll(this.id); }); </code></pre> <p><a href="https://jsfiddle.net/VPzxG/" rel="noreferrer"><strong>Live Example</strong></a></p> <p><strike>( Scroll to function taken from <a href="http://djpate.com/2009/10/07/animated-scroll-to-anchorid-function-with-jquery/" rel="noreferrer">here</a> )</strike></p> <hr /> <p>PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <code>&lt;a href=&quot;#gohere&quot;&gt;blah&lt;/a&gt;</code> ... <code>&lt;a name=&quot;gohere&quot;&gt;blah title&lt;/a&gt;</code></p>
{ "question_id": 3432656, "question_date": "2010-08-08T00:49:37.290Z", "question_score": 212, "tags": "jquery|scroll", "answer_id": 3432718, "answer_date": "2010-08-08T01:17:13.153Z", "answer_score": 358 }
Please answer the following Stack Overflow question: Title: What's the difference between RANK() and DENSE_RANK() functions in oracle? <p>What's the difference between <code>RANK()</code> and <code>DENSE_RANK()</code> functions? How to find out nth salary in the following <code>emptbl</code> table?</p> <pre><code>DEPTNO EMPNAME SAL ------------------------------ 10 rrr 10000.00 11 nnn 20000.00 11 mmm 5000.00 12 kkk 30000.00 10 fff 40000.00 10 ddd 40000.00 10 bbb 50000.00 10 ccc 50000.00 </code></pre> <p>If in the table data having <code>nulls</code>, what will happen if I want to find out <code>nth</code> salary?</p>
<p><code>RANK()</code> gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.</p> <p><code>DENSE_RANK()</code> again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.</p> <p>As for nulls, it depends on the <code>ORDER BY</code> clause. Here is a simple test script you can play with to see what happens:</p> <pre><code>with q as ( select 10 deptno, 'rrr' empname, 10000.00 sal from dual union all select 11, 'nnn', 20000.00 from dual union all select 11, 'mmm', 5000.00 from dual union all select 12, 'kkk', 30000 from dual union all select 10, 'fff', 40000 from dual union all select 10, 'ddd', 40000 from dual union all select 10, 'bbb', 50000 from dual union all select 10, 'xxx', null from dual union all select 10, 'ccc', 50000 from dual) select empname, deptno, sal , rank() over (partition by deptno order by sal nulls first) r , dense_rank() over (partition by deptno order by sal nulls first) dr1 , dense_rank() over (partition by deptno order by sal nulls last) dr2 from q; EMP DEPTNO SAL R DR1 DR2 --- ---------- ---------- ---------- ---------- ---------- xxx 10 1 1 4 rrr 10 10000 2 2 1 fff 10 40000 3 3 2 ddd 10 40000 3 3 2 ccc 10 50000 5 4 3 bbb 10 50000 5 4 3 mmm 11 5000 1 1 1 nnn 11 20000 2 2 2 kkk 12 30000 1 1 1 9 rows selected. </code></pre> <p><a href="http://www.oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions.php" rel="noreferrer">Here's a link</a> to a good explanation and some examples.</p>
{ "question_id": 11183572, "question_date": "2012-06-25T04:35:25.957Z", "question_score": 212, "tags": "sql|oracle|window-functions", "answer_id": 11183610, "answer_date": "2012-06-25T04:43:03.883Z", "answer_score": 320 }
Please answer the following Stack Overflow question: Title: How to format a DateTime in PowerShell <p>I can format the <a href="https://technet.microsoft.com/en-us/library/hh849887.aspx" rel="noreferrer"><code>Get-Date</code></a> cmdlet no problem like this:</p> <pre><code>$date = Get-Date -format "yyyyMMdd" </code></pre> <p>But once I've got <a href="https://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%29.aspx" rel="noreferrer">a date</a> in a variable, how do I format it? The statement below</p> <pre><code>$dateStr = $date -format "yyyMMdd" </code></pre> <p>returns this error:</p> <blockquote> <p>"You must provide a value expression on the right-hand side of the '-f' operator"</p> </blockquote>
<p>The same as you would in <a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings" rel="noreferrer">.NET</a>:</p> <pre><code>$DateStr = $Date.ToString("yyyyMMdd") </code></pre> <p>Or:</p> <pre><code>$DateStr = '{0:yyyyMMdd}' -f $Date </code></pre>
{ "question_id": 2249619, "question_date": "2010-02-12T04:09:59.263Z", "question_score": 212, "tags": "datetime|powershell", "answer_id": 2249639, "answer_date": "2010-02-12T04:16:24.090Z", "answer_score": 288 }
Please answer the following Stack Overflow question: Title: Mean per group in a data.frame <p>I have a <code>data.frame</code> and I need to calculate the mean per group (i.e. per <code>Month</code>, below).</p> <pre><code>Name Month Rate1 Rate2 Aira 1 12 23 Aira 2 18 73 Aira 3 19 45 Ben 1 53 19 Ben 2 22 87 Ben 3 19 45 Cat 1 22 87 Cat 2 67 43 Cat 3 45 32 </code></pre> <p>My desired output is like below, where the values for <code>Rate1</code> and <code>Rate2</code> are the group means. Please disregard the value, I have made it up for the example.</p> <pre><code>Name Rate1 Rate2 Aira 23.21 12.2 Ben 45.23 43.9 Cat 33.22 32.2 </code></pre>
<p>This type of operation is exactly what <code>aggregate</code> was designed for:</p> <pre><code>d &lt;- read.table(text= 'Name Month Rate1 Rate2 Aira 1 12 23 Aira 2 18 73 Aira 3 19 45 Ben 1 53 19 Ben 2 22 87 Ben 3 19 45 Cat 1 22 87 Cat 2 67 43 Cat 3 45 32', header=TRUE) aggregate(d[, 3:4], list(d$Name), mean) Group.1 Rate1 Rate2 1 Aira 16.33333 47.00000 2 Ben 31.33333 50.33333 3 Cat 44.66667 54.00000 </code></pre> <p>Here we aggregate columns 3 and 4 of data.frame <code>d</code>, grouping by <code>d$Name</code>, and applying the <code>mean</code> function.</p> <hr> <p>Or, using a formula interface:</p> <pre><code>aggregate(. ~ Name, d[-2], mean) </code></pre>
{ "question_id": 21982987, "question_date": "2014-02-24T08:56:59.963Z", "question_score": 212, "tags": "r|aggregate", "answer_id": 21983076, "answer_date": "2014-02-24T09:01:06.450Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: Validate phone number with JavaScript <p>I found this code in some website, and it works perfectly. It validates that the phone number is in one of these formats:<br> <strong>(123) 456-7890</strong> or <strong>123-456-7890</strong> </p> <p>The problem is that my client (I don't know why, maybe client stuffs) wants to add another format, the ten numbers consecutively, something like this: <strong>1234567890</strong>.</p> <p>I'm using this regular expression,</p> <pre><code>/^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/ </code></pre> <p>How can I add that it also validates the another format? I'm not good with regular expressions. </p>
<p>First off, your format validator is obviously only appropriate for <a href="http://en.wikipedia.org/wiki/North_American_Numbering_Plan" rel="noreferrer">NANP</a> (country code +1) numbers. Will your application be used by someone with a phone number from outside North America? If so, you don't want to prevent those people from entering a perfectly valid [international] number.</p> <p>Secondly, your validation is incorrect. NANP numbers take the form <code>NXX NXX XXXX</code> where <code>N</code> is a digit 2-9 and <code>X</code> is a digit 0-9. Additionally, area codes and exchanges may not take the form <code>N11</code> (end with two ones) to avoid confusion with special services <em>except</em> numbers in a non-geographic area code (800, 888, 877, 866, 855, 900) may have a <code>N11</code> exchange.</p> <p>So, your regex will pass the number (123) 123 4566 even though that is not a valid phone number. You can fix that by replacing <code>\d{3}</code> with <code>[2-9]{1}\d{2}</code>.</p> <p>Finally, I get the feeling you're validating user input in a web browser. Remember that client-side validation is <a href="https://stackoverflow.com/questions/1726617/form-validation-with-javascript-vs-php">only a <strong>convenience</strong> you provide to the user</a>; you still need to validate all input (again) on the server.</p> <p><strong>TL;DR</strong> don't use a regular expression to <a href="https://stackoverflow.com/a/5059082/1269037">validate complex real-world data like phone numbers</a> or <a href="https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links/21925491#21925491">URLs</a>. Use a <a href="https://github.com/googlei18n/libphonenumber" rel="noreferrer">specialized library</a>.</p>
{ "question_id": 4338267, "question_date": "2010-12-02T18:07:16.520Z", "question_score": 212, "tags": "javascript|regex", "answer_id": 4338544, "answer_date": "2010-12-02T18:36:34.603Z", "answer_score": 150 }
Please answer the following Stack Overflow question: Title: SQL WHERE.. IN clause multiple columns <p>I need to implement the following query in SQL Server:</p> <pre><code>select * from table1 WHERE (CM_PLAN_ID,Individual_ID) IN ( Select CM_PLAN_ID, Individual_ID From CRM_VCM_CURRENT_LEAD_STATUS Where Lead_Key = :_Lead_Key ) </code></pre> <p>But the WHERE..IN clause allows only 1 column. How can I compare 2 or more columns with another inner SELECT?</p>
<p>You can make a derived table from the subquery, and join table1 to this derived table:</p> <pre><code>select * from table1 LEFT JOIN ( Select CM_PLAN_ID, Individual_ID From CRM_VCM_CURRENT_LEAD_STATUS Where Lead_Key = :_Lead_Key ) table2 ON table1.CM_PLAN_ID=table2.CM_PLAN_ID AND table1.Individual=table2.Individual WHERE table2.CM_PLAN_ID IS NOT NULL </code></pre>
{ "question_id": 1136380, "question_date": "2009-07-16T07:39:46.730Z", "question_score": 212, "tags": "sql-server", "answer_id": 1136382, "answer_date": "2009-07-16T07:48:08.650Z", "answer_score": 130 }
Please answer the following Stack Overflow question: Title: MySQL select where column is not empty <p>In MySQL, can I select columns only where something exists? </p> <p>For example, I have the following query:</p> <pre><code>select phone, phone2 from jewishyellow.users where phone like '813%' and phone2 </code></pre> <p>I'm trying to select only the rows where phone starts with 813 and phone2 has something in it.</p>
<p>Compare value of <code>phone2</code> with empty string:</p> <pre><code>select phone, phone2 from jewishyellow.users where phone like '813%' and phone2&lt;&gt;'' </code></pre> <p>Note that <code>NULL</code> value is interpreted as <code>false</code>.</p>
{ "question_id": 1869264, "question_date": "2009-12-08T19:27:42.223Z", "question_score": 212, "tags": "sql|mysql", "answer_id": 1869274, "answer_date": "2009-12-08T19:29:39.413Z", "answer_score": 323 }
Please answer the following Stack Overflow question: Title: How do I use installed packages in PyCharm? <p>In <em>PyCharm</em>, I've added the Python environment <code>/usr/bin/python</code>. However,</p> <pre><code>from gnuradio import gr </code></pre> <p>fails as an <em>undefined reference</em>. However, it works fine in the Python interpreter from the command line. </p> <p>GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want it.</p> <p>Gnuradio is located at <code>/usr/local/lib/python2.7/site-packages/gnuradio</code></p> <p>Also:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.7/site-packages:/usr/local/lib/python2.7/site-packages/gnuradio</p> </blockquote>
<h2>Adding a Path</h2> <p>Go into File → Settings → Project Settings → Project Interpreter.</p> <p>Then press configure interpreter, and navigate to the "Paths" tab.</p> <p><img src="https://i.imgur.com/Q5pcWDX.jpg" alt="pycharm path tab"></p> <p>Press the + button in the Paths area. You can put the path to the module you'd like it to recognize. </p> <h3>But I don't know the path..</h3> <p>Open the python interpreter where you can import the module.</p> <pre><code>&gt;&gt; import gnuradio &gt;&gt; gnuradio.__file__ "path/to/gnuradio" </code></pre> <p>Most commonly you'll have a folder structure like this:</p> <pre><code>foobarbaz/ gnuradio/ __init__.py other_file.py </code></pre> <p>You want to add foobarbaz to the path here.</p>
{ "question_id": 19885821, "question_date": "2013-11-10T03:07:18.157Z", "question_score": 212, "tags": "python|pycharm|gnuradio", "answer_id": 19885882, "answer_date": "2013-11-10T03:17:31.003Z", "answer_score": 241 }
Please answer the following Stack Overflow question: Title: Determine the data types of a data frame's columns <p>I'm using R and have loaded data into a dataframe using <code>read.csv()</code>. How do I determine the data type of each column in the data frame?</p>
<p>Your best bet to start is to use <a href="http://stat.ethz.ch/R-manual/R-devel/library/utils/html/str.html" rel="noreferrer"><code>?str()</code></a>. To explore some examples, let's make some data: </p> <pre><code>set.seed(3221) # this makes the example exactly reproducible my.data &lt;- data.frame(y=rnorm(5), x1=c(1:5), x2=c(TRUE, TRUE, FALSE, FALSE, FALSE), X3=letters[1:5]) </code></pre> <p>@Wilmer E Henao H's solution is very streamlined: </p> <pre><code>sapply(my.data, class) y x1 x2 X3 "numeric" "integer" "logical" "factor" </code></pre> <p>Using <code>str()</code> gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable): </p> <pre><code>str(my.data) 'data.frame': 5 obs. of 4 variables: $ y : num 1.03 1.599 -0.818 0.872 -2.682 $ x1: int 1 2 3 4 5 $ x2: logi TRUE TRUE FALSE FALSE FALSE $ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5 </code></pre> <p>@Gavin Simpson's approach is also streamlined, but provides slightly different information than <code>class()</code>: </p> <pre><code>sapply(my.data, typeof) y x1 x2 X3 "double" "integer" "logical" "integer" </code></pre> <p>For more information about <code>class</code>, <code>typeof</code>, and the middle child, <code>mode</code>, see this excellent SO thread: <a href="https://stackoverflow.com/q/8855589/1217536">A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient</a>. </p>
{ "question_id": 21125222, "question_date": "2014-01-14T22:20:23.767Z", "question_score": 212, "tags": "r|dataframe|types", "answer_id": 21125793, "answer_date": "2014-01-14T22:55:31.120Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How do I change the number of open files limit in Linux? <p>When running my application I sometimes get an error about <code>too many files open</code>.</p> <p>Running <code>ulimit -a</code> reports that the limit is 1024. How do I increase the limit above 1024? </p> <p><strong>Edit</strong> <code>ulimit -n 2048</code> results in a permission error.</p>
<p>You could always try doing a <code>ulimit -n 2048</code>. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit</p> <p>Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.</p> <pre><code>set rlim_fd_max = 166384 set rlim_fd_cur = 8192 </code></pre> <p>On OS X, this same data must be set in /etc/sysctl.conf.</p> <pre><code>kern.maxfilesperproc=166384 kern.maxfiles=8192 </code></pre> <p>Under Linux, these settings are often in /etc/security/limits.conf.</p> <p>There are two kinds of limits:</p> <ul> <li><strong>soft</strong> limits are simply the currently enforced limits</li> <li><strong>hard</strong> limits mark the maximum value which cannot be exceeded by setting a soft limit</li> </ul> <p>Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.</p> <p>There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. </p>
{ "question_id": 34588, "question_date": "2008-08-29T16:14:25.417Z", "question_score": 212, "tags": "linux", "answer_id": 34645, "answer_date": "2008-08-29T16:30:04.443Z", "answer_score": 161 }
Please answer the following Stack Overflow question: Title: How to get correct timestamp in C# <p>I would like to get valid timestamp in my application so I wrote:</p> <pre><code>public static String GetTimestamp(DateTime value) { return value.ToString("yyyyMMddHHmmssffff"); } // ...later on in the code String timeStamp = GetTimestamp(new DateTime()); Console.WriteLine(timeStamp); </code></pre> <p>output:</p> <pre><code>000101010000000000 </code></pre> <p>I wanted something like:</p> <pre><code>20140112180244 </code></pre> <p>What have I done wrong?</p>
<p>Your mistake is using <code>new DateTime()</code>, which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is <a href="http://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx" rel="noreferrer">DateTime.Now</a>, so change this:</p> <pre><code>String timeStamp = GetTimestamp(new DateTime()); </code></pre> <p>to this:</p> <pre><code>String timeStamp = GetTimestamp(DateTime.Now); </code></pre>
{ "question_id": 21219797, "question_date": "2014-01-19T17:03:02.887Z", "question_score": 212, "tags": "c#|timestamp", "answer_id": 21219819, "answer_date": "2014-01-19T17:05:06.390Z", "answer_score": 240 }
Please answer the following Stack Overflow question: Title: Detecting value change of input[type=text] in jQuery <p>I want to execute a function every time the value of a specific input box changes. It <em>almost</em> works with <code>$('input').keyup(function)</code>, but nothing happens when pasting text into the box, for example. <code>$input.change(function)</code> only triggers when the input is blurred, so how would I immediately know whenever a text box has changed value?</p>
<h1>Update - 2021</h1> <p>As of 2021 you can use <code>input</code> event for all the events catering input value changes.</p> <pre><code>$(&quot;#myTextBox&quot;).on(&quot;input&quot;, function() { alert($(this).val()); }); </code></pre> <h1>Original Answer</h1> <p>just remember that 'on' is recommended over the 'bind' function, so always try to use a event listener like this:</p> <pre><code>$(&quot;#myTextBox&quot;).on(&quot;change paste keyup&quot;, function() { alert($(this).val()); }); </code></pre>
{ "question_id": 8747439, "question_date": "2012-01-05T18:05:37.717Z", "question_score": 212, "tags": "jquery", "answer_id": 17759257, "answer_date": "2013-07-20T06:06:49.353Z", "answer_score": 463 }
Please answer the following Stack Overflow question: Title: How can you dynamically create variables? <p>I want to create variables dynamically in Python. Does anyone have any creative means of doing this?</p>
<p>Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.</p> <pre><code>a = {} k = 0 while k &lt; 10: # dynamically create key key = ... # calculate value value = ... a[key] = value k += 1 </code></pre> <p>There are also some interesting data structures in the <a href="https://docs.python.org/library/collections.html" rel="noreferrer"><code>collections</code> module</a> that might be applicable.</p>
{ "question_id": 5036700, "question_date": "2011-02-18T01:14:00.710Z", "question_score": 212, "tags": "python|variables", "answer_id": 5036775, "answer_date": "2011-02-18T01:28:03.807Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Using JQuery - preventing form from submitting <p>How do I prevent a form from submitting using jquery?</p> <p>I tried everything - see 3 different options I tried below, but it all won't work: </p> <pre><code> $(document).ready(function() { //option A $("#form").submit(function(e){ e.preventDefault(); }); //option B $("#form").submit(function(e){ stopEvent(e); }); //option C $("#form").submit(function(){ return false; }); }); </code></pre> <p>What could be wrong?</p> <p>Update - here is my html:</p> <pre><code> &lt;form id="form" class="form" action="page2.php" method="post"&gt; &lt;!-- tags in the form --&gt; &lt;p class="class2"&gt; &lt;input type="submit" value="Okay!" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>Is there anything wrong here?</p>
<p>Two things stand out:<br></p> <ul> <li>It possible that your form name is not <code>form</code>. Rather refer to the tag by dropping the #.</li> <li><p>Also the <code>e.preventDefault</code> is the correct JQuery syntax, e.g.</p> <pre><code> //option A $("form").submit(function(e){ e.preventDefault(); }); </code></pre></li> </ul> <p>Option C should also work. I am not familiar with option B</p> <p>A complete example:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type='text/javascript'&gt; $(document).ready(function() { //option A $("form").submit(function(e){ alert('submit intercepted'); e.preventDefault(e); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="http://google.com" method="GET"&gt; Search &lt;input type='text' name='q' /&gt; &lt;input type='submit'/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
{ "question_id": 9347282, "question_date": "2012-02-19T06:34:20.300Z", "question_score": 212, "tags": "jquery|forms", "answer_id": 9347286, "answer_date": "2012-02-19T06:36:20.887Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: How to get the second column from command output? <p>My command's output is something like:</p> <pre><code>1540 "A B" 6 "C" 119 "D" </code></pre> <p>The first column is always a number, followed by a space, then a double-quoted string.</p> <p>My purpose is to get the second column only, like:</p> <pre><code>"A B" "C" "D" </code></pre> <p>I intended to use <code>&lt;some_command&gt; | awk '{print $2}'</code> to accomplish this. But the question is, some values in the second column contain space(s), which happens to be the default delimiter for <code>awk</code> to separate the fields. Therefore, the output is messed up:</p> <pre><code>"A "C" "D" </code></pre> <p>How do I get the second column's value (with paired quotes) cleanly?</p>
<p>Or use sed &amp; regex.</p> <pre><code>&lt;some_command&gt; | sed 's/^.* \(".*"$\)/\1/' </code></pre>
{ "question_id": 16136943, "question_date": "2013-04-21T22:36:40.990Z", "question_score": 212, "tags": "shell|awk|ksh", "answer_id": 16137100, "answer_date": "2013-04-21T22:57:17.963Z", "answer_score": 35 }
Please answer the following Stack Overflow question: Title: How do I do an initial push to a remote repository with Git? <p>I've read through countless tutorials and I keep coming up short. Here's what I've got:</p> <ul> <li>I'm running RubyMine on my Windows desktop</li> <li>I've installed Git on my WebFaction hosting account per their <a href="http://docs.webfaction.com/software/git.html?highlight=git#create-a-place-to-store-git-repositories" rel="noreferrer">instructions</a></li> <li>Git appears to be working fine on both machines</li> </ul> <p>Here's what I'm doing:</p> <ol> <li>On server: <ul> <li><code>mkdir project</code></li> <li><code>git init</code></li> <li><code>git add .</code></li> <li><code>git commit #==&gt; nothing to commit</code></li> </ul> </li> <li>On client: <ul> <li>Create new project in RubyMine</li> <li><em>Git init</em> in top directory of project</li> <li><em>Push changes</em> to server<code> #==&gt; failed to push some refs to...</code></li> </ul> </li> </ol> <p>What steps am I missing?</p>
<p>On server:</p> <pre><code>mkdir my_project.git cd my_project.git git --bare init </code></pre> <p>On client:</p> <pre><code>mkdir my_project cd my_project touch .gitignore git init git add . git commit -m "Initial commit" git remote add origin [email protected]:/path/to/my_project.git git push origin master </code></pre> <p>Note that when you add the origin, there are several formats and schemas you could use. I recommend you see what your hosting service provides.</p>
{ "question_id": 2337281, "question_date": "2010-02-25T20:15:57.487Z", "question_score": 212, "tags": "git|version-control", "answer_id": 2337373, "answer_date": "2010-02-25T20:27:21.970Z", "answer_score": 463 }
Please answer the following Stack Overflow question: Title: How do I get a UTC Timestamp in JavaScript? <p>While writing a web application, it makes sense to store (server side) <em>all</em> datetimes in the DB as UTC timestamps.</p> <p>I was astonished when I noticed that you couldn't natively do much in terms of Timezone manipulation in JavaScript.</p> <p>I extended the Date object a little. Does this function make sense? Basically, every time I send anything to the server, it's going to be a timestamp formatted with this function...</p> <p>Can you see any major problems here? Or maybe a solution from a different angle?</p> <pre><code>Date.prototype.getUTCTime = function(){ return new Date( this.getUTCFullYear(), this.getUTCMonth(), this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds() ).getTime(); } </code></pre> <p>It just seems a little convoluted to me. And I am not so sure about performance either.</p>
<ol> <li><p>Dates constructed that way use the local timezone, making the constructed date incorrect. To set the timezone of a certain date object is to construct it from a date string that includes the timezone. (I had problems getting that to work in an older Android browser.)</p></li> <li><p>Note that <code>getTime()</code> returns milliseconds, not plain seconds.</p></li> </ol> <p>For a UTC/Unix timestamp, the following should suffice:</p> <pre><code>Math.floor((new Date()).getTime() / 1000) </code></pre> <p>It will factor the current timezone offset into the result. For a string representation, <a href="https://stackoverflow.com/a/9756143/59087">David Ellis'</a> answer works.</p> <p>To clarify:</p> <pre><code>new Date(Y, M, D, h, m, s) </code></pre> <p>That input is treated as <em>local time</em>. If <em>UTC time</em> is passed in, the results will differ. Observe (I'm in GMT +02:00 right now, and it's 07:50):</p> <pre><code>&gt; var d1 = new Date(); &gt; d1.toUTCString(); "Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time &gt; Math.floor(d1.getTime()/ 1000) 1332049834 &gt; var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() ); &gt; d2.toUTCString(); "Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0! &gt; Math.floor(d2.getTime()/ 1000) 1332042634 </code></pre> <p>Also note that <code>getUTCDate()</code> cannot be substituted for <code>getUTCDay()</code>. This is because <code>getUTCDate()</code> returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate" rel="noreferrer"><em>the day of the month</em></a>; whereas, <code>getUTCDay()</code> returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay" rel="noreferrer"><em>the day of the week</em></a>.</p>
{ "question_id": 9756120, "question_date": "2012-03-18T04:57:16.563Z", "question_score": 212, "tags": "javascript|timezone|utc", "answer_id": 9756189, "answer_date": "2012-03-18T05:14:36.523Z", "answer_score": 194 }
Please answer the following Stack Overflow question: Title: Plot a legend outside of the plotting area in base graphics? <p>As the title says: <strong>How can I plot a legend outside the plotting area when using base graphics?</strong></p> <p>I thought about fiddling around with <code>layout</code> and produce an empty plot to only contain the legend, but I would be interested in a way using just the base graph facilities and e.g., <code>par(mar = )</code> to get some space on the right of the plot for the legend.</p> <hr> <p>Here an example:</p> <pre><code>plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2)) lines(1:3, rnorm(3), pch = 2, lty = 2, type="o") legend(1,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2)) </code></pre> <p>produces:</p> <p><img src="https://i.stack.imgur.com/ADmGV.png" alt="alt text"></p> <p>But as said, I would like the legend to be outside the plotting area (e.g., to the right of the graph/plot.</p>
<p>Maybe what you need is <code>par(xpd=TRUE)</code> to enable things to be drawn outside the plot region. So if you do the main plot with <code>bty='L'</code> you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do <code>par(xpd=TRUE)</code> and with a bit of adjustment you can get a legend as far right as it can go:</p> <pre><code> set.seed(1) # just to get the same random numbers par(xpd=FALSE) # this is usually the default plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L') # this legend gets clipped: legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2)) # so turn off clipping: par(xpd=TRUE) legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2)) </code></pre>
{ "question_id": 3932038, "question_date": "2010-10-14T10:01:44.340Z", "question_score": 212, "tags": "r|plot|legend", "answer_id": 3932558, "answer_date": "2010-10-14T11:15:46.800Z", "answer_score": 129 }
Please answer the following Stack Overflow question: Title: Better way to cast object to int <p>This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is </p> <pre><code>int test = int.Parse(string.Format("{0}", myobject)) </code></pre> <p>Is there a cleaner way to do this? Thanks</p>
<p>You have several options:</p> <ul> <li><p><code>(int)</code> &mdash; Cast operator. Works if the object <em>already is</em> an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.</p></li> <li><p><code>int.Parse()/int.TryParse()</code> &mdash; For converting from a string of unknown format.</p></li> <li><p><code>int.ParseExact()/int.TryParseExact()</code> &mdash; For converting from a string in a specific format</p></li> <li><p><code>Convert.ToInt32()</code> &mdash; For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.</p></li> <li><p><code>as int?</code> &mdash; Note the "?". The <code>as</code> operator is only for reference types, and so I used "?" to signify a <code>Nullable&lt;int&gt;</code>. The "<code>as</code>" operator works like <code>Convert.To____()</code>, but think <code>TryParse()</code> rather than <code>Parse()</code>: it returns <code>null</code> rather than throwing an exception if the conversion fails.</p></li> </ul> <p>Of these, I would prefer <code>(int)</code> if the object really is just a boxed integer. Otherwise use <a href="http://msdn.microsoft.com/en-us/library/system.convert.toint32.aspx" rel="noreferrer"><code>Convert.ToInt32()</code></a> in this case.</p> <p>Note that this is a very <em>general</em> answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the <em>specifics</em> here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails <code>(int)(short)</code> might work instead, and for recommending you check your debugger to find out the actual runtime type.</p>
{ "question_id": 745172, "question_date": "2009-04-13T20:02:50.417Z", "question_score": 212, "tags": "c#|interop", "answer_id": 745204, "answer_date": "2009-04-13T20:12:26.307Z", "answer_score": 429 }
Please answer the following Stack Overflow question: Title: How to define a List bean in Spring? <p>I'm using Spring to define stages in my application. It's configured that the necessary class (here called <code>Configurator</code>) is injected with the stages.<br> Now I need the List of Stages in another class, named <code>LoginBean</code>. The <code>Configurator</code> doesn't offer access to his List of Stages.</p> <p>I cannot change the class <code>Configurator</code>.</p> <p>My Idea:<br> Define a new bean called Stages and inject it to <code>Configurator</code> and <code>LoginBean</code>. My problem with this idea is that I don't know how to transform this property:</p> <pre class="lang-xml prettyprint-override"><code>&lt;property ...&gt; &lt;list&gt; &lt;bean ... &gt;...&lt;/bean&gt; &lt;bean ... &gt;...&lt;/bean&gt; &lt;bean ... &gt;...&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; </code></pre> <p>into a bean.</p> <p>Something like this does not work:</p> <pre class="lang-xml prettyprint-override"><code>&lt;bean id="stages" class="java.util.ArrayList"&gt; </code></pre> <p>Can anybody help me with this?</p>
<p>Import the spring util namespace. Then you can define a list bean as follows:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"&gt; &lt;util:list id="myList" value-type="java.lang.String"&gt; &lt;value&gt;foo&lt;/value&gt; &lt;value&gt;bar&lt;/value&gt; &lt;/util:list&gt; </code></pre> <p></p> <p>The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute <code>list-class</code>.</p>
{ "question_id": 2416056, "question_date": "2010-03-10T10:21:50.523Z", "question_score": 212, "tags": "java|spring", "answer_id": 2416145, "answer_date": "2010-03-10T10:37:39.097Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: How to run a class from Jar which is not the Main-Class in its Manifest file <p>I have a JAR with 4 classes, each one has Main method. I want to be able to run each one of those as per the need. I am trying to run it from command-line on Linux box.</p> <pre><code>E.g. The name of my JAR is MyJar.jar </code></pre> <p>It has directory structure for the main classes as follows: </p> <pre><code>com/mycomp/myproj/dir1/MainClass1.class com/mycomp/myproj/dir2/MainClass2.class com/mycomp/myproj/dir3/MainClass3.class com/mycomp/myproj/dir4/MainClass4.class </code></pre> <p>I know that I can specify one class as main in my Manifest file. But is there any way by which I can specify some argument on command line to run whichever class I wish to run?</p> <p>I tried this:</p> <pre><code>jar cfe MyJar.jar com.mycomp.myproj.dir2.MainClass2 com/mycomp/myproj/dir2/MainClass2.class /home/myhome/datasource.properties /home/myhome/input.txt </code></pre> <p>And I got this error:</p> <pre><code>com/mycomp/myproj/dir2/MainClass2.class : no such file or directory </code></pre> <p>(In the above command, '/home/myhome/datasource.properties' and '/home/myhome/input.txt' are the command line arguments).</p>
<p>You can create your jar without Main-Class in its Manifest file. Then :</p> <pre><code>java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt </code></pre>
{ "question_id": 5474666, "question_date": "2011-03-29T15:02:16.283Z", "question_score": 212, "tags": "java|jar|executable-jar", "answer_id": 5474748, "answer_date": "2011-03-29T15:08:00.543Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: Set CSS property in JavaScript? <p>I've created the following...</p> <pre><code>var menu = document.createElement('select'); </code></pre> <p>How would I now set CSS attributes e.g <code>width: 100px</code>?</p>
<p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style" rel="noreferrer"><code>element.style</code></a>:</p> <pre><code>var element = document.createElement('select'); element.style.width = "100px"; </code></pre>
{ "question_id": 5195303, "question_date": "2011-03-04T14:55:41.063Z", "question_score": 212, "tags": "javascript|css", "answer_id": 5195329, "answer_date": "2011-03-04T14:57:34.183Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: change type of input field with jQuery <pre class="lang-js prettyprint-override"><code>$(document).ready(function() { // #login-box password field $('#password').attr('type', 'text'); $('#password').val('Password'); }); </code></pre> <p>This is supposed to change the <code>#password</code> input field (with <code>id="password"</code>) that is of <code>type</code> <code>password</code> to a normal text field, and then fill in the text “Password”.</p> <p>It doesn’t work, though. Why?</p> <p>Here is the form:</p> <pre class="lang-html prettyprint-override"><code>&lt;form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in"&gt; &lt;ol&gt; &lt;li&gt; &lt;div class="element"&gt; &lt;input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" /&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="element"&gt; &lt;input type="password" name="password" id="password" value="" class="input-text" /&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="button"&gt; &lt;div class="button"&gt; &lt;input type="submit" name="sign_in" id="sign_in" value="Prihlásiť" class="input-submit" /&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; &lt;/form&gt; </code></pre>
<p>It's very likely this action is prevented as part of the browser's security model.</p> <p>Edit: indeed, testing right now in Safari, I get the error <code>type property cannot be changed</code>.</p> <p>Edit 2: that seems to be an error straight out of jQuery. Using the following straight DOM code works just fine:</p> <pre><code>var pass = document.createElement('input'); pass.type = 'password'; document.body.appendChild(pass); pass.type = 'text'; pass.value = 'Password'; </code></pre> <p>Edit 3: Straight from the jQuery source, this seems to be related to IE (and could either be a bug or part of their security model, but jQuery isn't specific):</p> <pre><code>// We can't allow the type property to be changed (since it causes problems in IE) if ( name == "type" &amp;&amp; jQuery.nodeName( elem, "input" ) &amp;&amp; elem.parentNode ) throw "type property can't be changed"; </code></pre>
{ "question_id": 1544317, "question_date": "2009-10-09T14:54:57.980Z", "question_score": 212, "tags": "javascript|jquery|html-input", "answer_id": 1544338, "answer_date": "2009-10-09T14:57:22Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: Fixed width buttons with Bootstrap <p>Does Bootstrap support fixed width buttons? Currently if I have 2 buttons, "Save" and "Download", the button size changes based on content.</p> <p>Also what is the right way of extending Bootstrap?</p>
<p>You can also use the <code>.btn-block</code> class on the button, so that it expands to the parent's width.</p> <p>If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;span2&quot;&gt; &lt;p&gt;&lt;button class=&quot;btn btn-primary btn-block&quot;&gt;Save&lt;/button&gt;&lt;/p&gt; &lt;p&gt;&lt;button class=&quot;btn btn-success btn-block&quot;&gt;Download&lt;/button&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="span2"&gt; &lt;p&gt;&lt;button class="btn btn-primary btn-block"&gt;Save&lt;/button&gt;&lt;/p&gt; &lt;p&gt;&lt;button class="btn btn-success btn-block"&gt;Download&lt;/button&gt;&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 11050269, "question_date": "2012-06-15T12:02:22.483Z", "question_score": 212, "tags": "css|twitter-bootstrap", "answer_id": 12527816, "answer_date": "2012-09-21T09:28:22.643Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: How to schedule a periodic task in Java? <p>I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?</p> <p>I'm currently using <code>java.util.Timer.scheduleAtFixedRate</code>. Does <code>java.util.Timer.scheduleAtFixedRate</code> support long time intervals? </p>
<p>Use a <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html">ScheduledExecutorService</a>:</p> <pre><code> private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS); </code></pre>
{ "question_id": 7814089, "question_date": "2011-10-18T21:38:51.270Z", "question_score": 212, "tags": "java|scheduled-tasks", "answer_id": 7814149, "answer_date": "2011-10-18T21:44:47.470Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: How to persist a property of type List<String> in JPA? <p>What is the smartest way to get an entity with a field of type List persisted?</p> <h2>Command.java</h2> <pre><code>package persistlistofstring; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Persistence; @Entity public class Command implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Basic List&lt;String&gt; arguments = new ArrayList&lt;String&gt;(); public static void main(String[] args) { Command command = new Command(); EntityManager em = Persistence .createEntityManagerFactory("pu") .createEntityManager(); em.getTransaction().begin(); em.persist(command); em.getTransaction().commit(); em.close(); System.out.println("Persisted with id=" + command.id); } } </code></pre> <hr> <p>This code produces:</p> <pre><code>&gt; Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named pu: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: &gt; oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException &gt; Local Exception Stack: &gt; Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException &gt; Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7 &gt; Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException &gt; Exception Description: predeploy for PersistenceUnit [pu] failed. &gt; Internal Exception: Exception [TOPLINK-7155] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException &gt; Exception Description: The type [interface java.util.List] for the attribute [arguments] on the entity class [class persistlistofstring.Command] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface. &gt; at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143) &gt; at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169) &gt; at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110) &gt; at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) &gt; at persistlistofstring.Command.main(Command.java:30) &gt; Caused by: &gt; ... </code></pre>
<p>Use some JPA 2 implementation: it adds a @ElementCollection annotation, similar to the Hibernate one, that does exactly what you need. There's one example <a href="http://jazzy.id.au/2008/03/24/jpa_2_0_new_features_part_1.html" rel="noreferrer">here</a>.</p> <p><b>Edit</b></p> <p>As mentioned in the comments below, the correct JPA 2 implementation is</p> <pre><code>javax.persistence.ElementCollection @ElementCollection Map&lt;Key, Value&gt; collection; </code></pre> <p><b>See: <a href="http://docs.oracle.com/javaee/6/api/javax/persistence/ElementCollection.html" rel="noreferrer">http://docs.oracle.com/javaee/6/api/javax/persistence/ElementCollection.html</a></b></p>
{ "question_id": 287201, "question_date": "2008-11-13T15:15:23.860Z", "question_score": 212, "tags": "java|orm|jpa", "answer_id": 1428480, "answer_date": "2009-09-15T17:14:43.723Z", "answer_score": 235 }
Please answer the following Stack Overflow question: Title: How to style the parent element when hovering a child element? <p>I know that there does not exist a <a href="https://stackoverflow.com/q/1014861/757830">CSS parent selector</a>, but is it possible to style a parenting element when hovering a child element without such a selector?</p> <p>To give an example: consider a <em>delete button</em> that when hovered will highlight the element that is about to become deleted:</p> <pre><code>&lt;div&gt; &lt;p&gt;Lorem ipsum ...&lt;/p&gt; &lt;button&gt;Delete&lt;/button&gt; &lt;/div&gt; </code></pre> <p>By means of pure CSS, how to change the background color of this section when the mouse is over the button?</p>
<p>I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper). </p> <p>If you set the parent to be with no <code>pointer-events</code>, and then a child <code>div</code> with <code>pointer-events</code> set to <code>auto</code>, it works:)<br> Note that <code>&lt;img&gt;</code> tag (for example) doesn't do the trick.<br> Also remember to set <code>pointer-events</code> to <code>auto</code> for other children which have their own event listener, or otherwise they will lose their click functionality.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div.parent { pointer-events: none; } div.child { pointer-events: auto; } div.parent:hover { background: yellow; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; parent - you can hover over here and it won't trigger &lt;div class="child"&gt;hover over the child instead!&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Edit:</strong><br> As <a href="https://stackoverflow.com/users/447356/shadow-wizard">Shadow Wizard</a> kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see <a href="http://caniuse.com/#feat=pointer-events" rel="noreferrer">here</a>)</p>
{ "question_id": 8114657, "question_date": "2011-11-13T20:54:28.973Z", "question_score": 212, "tags": "html|css", "answer_id": 30104683, "answer_date": "2015-05-07T14:54:34.273Z", "answer_score": 190 }
Please answer the following Stack Overflow question: Title: NodeJS - Error installing with NPM <pre><code>Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved. C:\Windows\system32&gt;npm install caress-server npm http GET https://registry.npmjs.org/caress-server npm http 304 https://registry.npmjs.org/caress-server npm http GET https://registry.npmjs.org/jspack/0.0.1 npm http GET https://registry.npmjs.org/buffertools npm http 304 https://registry.npmjs.org/jspack/0.0.1 npm http 304 https://registry.npmjs.org/buffertools &gt; [email protected] install C:\Windows\system32\node_modules\caress-server\node_ modules\buffertools &gt; node-gyp rebuild C:\Windows\system32\node_modules\caress-server\node_modules\buffertools&gt;node "G: \nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node- gyp.js" rebuild gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable. gyp ERR! stack at failNoPython (G:\nodejs\node_modules\npm\node_modules\node -gyp\lib\configure.js:101:14) gyp ERR! stack at G:\nodejs\node_modules\npm\node_modules\node-gyp\lib\confi gure.js:64:11 gyp ERR! stack at Object.oncomplete (fs.js:107:15) gyp ERR! System Windows_NT 6.2.9200 gyp ERR! command "node" "G:\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\ bin\\node-gyp.js" "rebuild" gyp ERR! cwd C:\Windows\system32\node_modules\caress-server\node_modules\buffert ools gyp ERR! node -v v0.10.25 gyp ERR! node-gyp -v v0.12.2 gyp ERR! not ok npm ERR! [email protected] install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] install script. npm ERR! This is most likely a problem with the buffertools package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls buffertools npm ERR! There is likely additional logging output above. npm ERR! System Windows_NT 6.2.9200 npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n pm-cli.js" "install" "caress-server" npm ERR! cwd C:\Windows\system32 npm ERR! node -v v0.10.25 npm ERR! npm -v 1.3.24 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR! C:\Windows\system32\npm-debug.log npm ERR! not ok code 0 C:\Windows\system32&gt; </code></pre> <p>I am installing a certain NodeJS script - <a href="http://caressjs.com/" rel="noreferrer">Caress</a>. But i am not unable to. I am using Windows 8.1, can anyone tell me what is the problem i am facing, and why is this installation not working. There seems to be a problem with the buffertools dependency, thats far as i can think. Dont know how maybe fix this?</p> <p>If i download the build from github and place it in node-modules, nothing seems to work. when i try to start, using npm start, or during implementation either.</p> <pre><code>G:\nodejs\node_modules\caress-server&gt;npm install G:\nodejs\node_modules\caress-server&gt;npm start &gt; [email protected] start G:\nodejs\node_modules\caress-server &gt; node examples/server.js info - socket.io started module.js:340 throw err; ^ Error: Cannot find module './build/Release/buffertools.node' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.&lt;anonymous&gt; (G:\nodejs\node_modules\caress-server\node_modules\buf fertools\buffertools.js:16:19) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) npm ERR! [email protected] start: `node examples/server.js` npm ERR! Exit status 8 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! This is most likely a problem with the caress-server package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node examples/server.js npm ERR! You can get their info via: npm ERR! npm owner ls caress-server npm ERR! There is likely additional logging output above. npm ERR! System Windows_NT 6.2.9200 npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n pm-cli.js" "start" npm ERR! cwd G:\nodejs\node_modules\caress-server npm ERR! node -v v0.10.25 npm ERR! npm -v 1.3.24 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR! G:\nodejs\node_modules\caress-server\npm-debug.log npm ERR! not ok code 0 G:\nodejs\node_modules\caress-server&gt; </code></pre>
As commented below you may not need to install VS on windows, check this out <p><a href="https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245" rel="noreferrer">https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245</a></p> <h3>UPDATED 02/2016</h3> <p>Some npm plugins need <strong><code>node-gyp</code></strong> to be installed.</p> <p>However, <strong><code>node-gyp</code></strong> has it's own dependencies (<a href="https://github.com/TooTallNate/node-gyp" rel="noreferrer">from the github page</a>):</p> <p><img src="https://i.imgur.com/LYtmhaB.png" alt="enter image description here"></p> <h3>UPDATED 09/2016</h3> <p>If you're using Windows you can now install all <code>node-gyp</code> dependencies with single command (NOTE: Run As Admin in Windows PowerShell):</p> <pre><code> $ npm install --global --production windows-build-tools </code></pre> <p>and then install the package</p> <pre><code> $ npm install --global node-gyp </code></pre> <h3>UPDATED 06/2018</h3> <p><a href="https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383" rel="noreferrer">https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383</a></p> <blockquote> <p>Delete your $HOME/.node-gyp directory and try again.</p> </blockquote> <p>See full documentation here: <a href="https://github.com/nodejs/node-gyp" rel="noreferrer">node-gyp</a></p>
{ "question_id": 21365714, "question_date": "2014-01-26T16:00:49.007Z", "question_score": 212, "tags": "node.js|npm", "answer_id": 21366601, "answer_date": "2014-01-26T17:16:22.020Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: How to write bytes to file? <p>I have a function that returns a string. The string contains carriage returns and newlines (0x0D, 0x0A). However when I write to a file it contains only the new line feeds. Is there a way to get the output to include the carriage return and the newline?</p> <pre><code>msg = function(arg1, arg2, arg3) f = open('/tmp/output', 'w') f.write(msg) f.close() </code></pre>
<p>If you want to write bytes then you should open the file in binary mode.</p> <pre><code>f = open('/tmp/output', 'wb') </code></pre>
{ "question_id": 12092527, "question_date": "2012-08-23T13:19:53.103Z", "question_score": 212, "tags": "python", "answer_id": 12092564, "answer_date": "2012-08-23T13:22:00.830Z", "answer_score": 369 }
Please answer the following Stack Overflow question: Title: Measuring execution time of a function in C++ <p>I want to find out how much time a certain function takes in my C++ program to execute on <strong>Linux</strong>. Afterwards, I want to make a speed comparison . I saw several time function but ended up with this from boost. Chrono:</p> <pre><code>process_user_cpu_clock, captures user-CPU time spent by the current process </code></pre> <p>Now, I am not clear if I use the above function, will I get the only time which CPU spent on that function? </p> <p>Secondly, I could not find any example of using the above function. Can any one please help me how to use the above function?</p> <p>P.S: Right now , I am using <code>std::chrono::system_clock::now()</code> to get time in seconds but this gives me different results due to different CPU load every time.</p>
<p>It is a very easy-to-use method in C++11. You have to use <code>std::chrono::high_resolution_clock</code> from <code>&lt;chrono&gt;</code> header.</p> <p>Use it like so:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;chrono&gt; /* Only needed for the sake of this example. */ #include &lt;iostream&gt; #include &lt;thread&gt; void long_operation() { /* Simulating a long, heavy operation. */ using namespace std::chrono_literals; std::this_thread::sleep_for(150ms); } int main() { using std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::duration; using std::chrono::milliseconds; auto t1 = high_resolution_clock::now(); long_operation(); auto t2 = high_resolution_clock::now(); /* Getting number of milliseconds as an integer. */ auto ms_int = duration_cast&lt;milliseconds&gt;(t2 - t1); /* Getting number of milliseconds as a double. */ duration&lt;double, std::milli&gt; ms_double = t2 - t1; std::cout &lt;&lt; ms_int.count() &lt;&lt; &quot;ms\n&quot;; std::cout &lt;&lt; ms_double.count() &lt;&lt; &quot;ms\n&quot;; return 0; } </code></pre> <p>This will measure the duration of the function <code>long_operation</code>.</p> <p>Possible output:</p> <pre><code>150ms 150.068ms </code></pre> <p>Working example: <a href="https://godbolt.org/z/oe5cMd" rel="noreferrer">https://godbolt.org/z/oe5cMd</a></p>
{ "question_id": 22387586, "question_date": "2014-03-13T18:23:30.943Z", "question_score": 212, "tags": "c++|optimization|profiling", "answer_id": 22387757, "answer_date": "2014-03-13T18:30:14.963Z", "answer_score": 395 }
Please answer the following Stack Overflow question: Title: How to suppress scientific notation when printing float values? <p>Here's my code:</p> <pre><code>x = 1.0 y = 100000.0 print x/y </code></pre> <p>My quotient displays as <code>1.00000e-05</code>.</p> <p>Is there any way to suppress scientific notation and make it display as <code>0.00001</code>? I'm going to use the result as a string.</p>
<pre><code>'%f' % (x/y) </code></pre> <p>but you need to manage precision yourself. e.g.,</p> <pre><code>'%f' % (1/10**8) </code></pre> <p>will display zeros only.<br /> <a href="https://docs.python.org/3/library/string.html#formatstrings" rel="noreferrer">details are in the docs</a></p> <p>Or for Python 3 <a href="http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations" rel="noreferrer">the equivalent old formatting</a> or the <a href="http://docs.python.org/py3k/library/string.html#string-formatting" rel="noreferrer">newer style formatting</a></p>
{ "question_id": 658763, "question_date": "2009-03-18T15:27:21.630Z", "question_score": 212, "tags": "python|floating-point", "answer_id": 658777, "answer_date": "2009-03-18T15:30:48.003Z", "answer_score": 78 }
Please answer the following Stack Overflow question: Title: Sending JWT token in the headers with Postman <p>I'm testing an implementation of JWT Token based security based off the following <a href="https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/">article</a>. I have successfully received a token from the test server. I can't figure out how to have the Chrome POSTMAN REST Client program send the token in the header.</p> <p><img src="https://i.stack.imgur.com/MqjLs.png" alt="postman screenshot"></p> <p>My questions are as follows:</p> <p>1) Am I using the right header name and/or POSTMAN interface?</p> <p>2) Do I need to base 64 encode the token? I thought I could just send the token back.</p>
<p>For the request Header name just use Authorization. Place Bearer before the Token. I just tried it out and it works for me.</p> <p>Authorization: Bearer TOKEN_STRING</p> <p>Each part of the JWT is a base64url encoded value. </p>
{ "question_id": 24709944, "question_date": "2014-07-12T05:26:23.627Z", "question_score": 212, "tags": "express|jwt|postman", "answer_id": 24710676, "answer_date": "2014-07-12T07:23:03.193Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: Return content with IHttpActionResult for non-OK response <p>For returning from a Web API 2 controller, I can return content with the response if the response is OK (status 200) like this:</p> <pre class="lang-cs prettyprint-override"><code>public IHttpActionResult Get() { string myResult = ... return Ok(myResult); } </code></pre> <p>If possible, I want to use the built-in result types here when <a href="https://msdn.microsoft.com/en-us/library/system.web.http.results(v=vs.118).aspx" rel="nofollow noreferrer">possible </a></p> <p>My question is, for another type of response (not 200), how can I return a message (string) with it? For example, I can do this:</p> <pre class="lang-cs prettyprint-override"><code>public IHttpActionResult Get() { return InternalServerError(); } </code></pre> <p>but not this:</p> <pre class="lang-cs prettyprint-override"><code>public IHttpActionResult Get() { return InternalServerError(&quot;Message describing the error here&quot;); } </code></pre> <p>Ideally, I want this to be generalized so that I can send a message back with any of the implementations of IHttpActionResult.</p> <p>Do I need to do this (and build my response message):</p> <pre class="lang-cs prettyprint-override"><code>public IHttpActionResult Get() { HttpResponseMessage responseMessage = ...; return ResponseMessage(responseMessage); } </code></pre> <p>or is there a better way?</p>
<p>I ended up going with the following solution:</p> <pre><code>public class HttpActionResult : IHttpActionResult { private readonly string _message; private readonly HttpStatusCode _statusCode; public HttpActionResult(HttpStatusCode statusCode, string message) { _statusCode = statusCode; _message = message; } public Task&lt;HttpResponseMessage&gt; ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(_statusCode) { Content = new StringContent(_message) }; return Task.FromResult(response); } } </code></pre> <p>... which can be used like this:</p> <pre><code>public IHttpActionResult Get() { return new HttpActionResult(HttpStatusCode.InternalServerError, "error message"); // can use any HTTP status code } </code></pre> <p>I'm open to suggestions for improvement. :)</p>
{ "question_id": 28588652, "question_date": "2015-02-18T16:29:34.007Z", "question_score": 212, "tags": "c#|asp.net-web-api|httpresponse", "answer_id": 28589333, "answer_date": "2015-02-18T16:59:35.617Z", "answer_score": 43 }
Please answer the following Stack Overflow question: Title: CSS/HTML: What is the correct way to make text italic? <p>What is the <strong><em>correct</em></strong> way to make text italic? I have seen the following four approaches:</p> <pre><code>&lt;i&gt;Italic Text&lt;/i&gt; &lt;em&gt;Italic Text&lt;/em&gt; &lt;span class="italic"&gt;Italic Text&lt;/span&gt; &lt;span class="footnote"&gt;Italic Text&lt;/span&gt; </code></pre> <hr> <h1><code>&lt;i&gt;</code></h1> <p>This is the "old way". <code>&lt;i&gt;</code> has no semantic meaning and only conveys the presentational effect of making the text italic. As far as I can see, this is clearly wrong because this is non-semantic.</p> <hr> <h1><code>&lt;em&gt;</code></h1> <p>This uses semantic mark up for purely presentational purposes. It just happens that <code>&lt;em&gt;</code> by default renders text in italic and so it is often used by those who are aware that <code>&lt;i&gt;</code> should be avoided but who are unaware of its semantic meaning. Not all italic text is italic because it is emphasised. Sometimes, it can be the exact opposite, like a side note or a whisper.</p> <hr> <h1><code>&lt;span class="italic"&gt;</code></h1> <p>This uses a CSS class to place presentation. This is often touted as the correct way but again, this seems wrong to me. This doesn't appear to convey any more semantic meaning that <code>&lt;i&gt;</code>. But, its proponents cry, it is much easier to change all your italic text later if you, say, wanted it bold. Yet this is not the case because I would then be left with a class called "italic" that rendered text bold. Furthermore, it is not clear why I would ever want to change all italic text on my website or at least we can think of cases in which this would not be desirable or necessary.</p> <hr> <h1><code>&lt;span class="footnote"&gt;</code></h1> <p>This uses a CSS class for semantics. So far this appears to be the best way but it actually has two problems.</p> <ol> <li><p>Not all text has sufficient meaning to warrant semantic markup. For example, is italicised text at the bottom of the page really a footnote? Or is it an aside? Or something else entirely. Perhaps it has no special meaning and only needs to be rendered in italics to separate it presentationally from the text preceding it.</p></li> <li><p>Semantic meaning can change when it is not present in sufficient strength. Lets say I went along with "footnote" based upon nothing more than the text being at the bottom of the page. What happens when a few months later I want to add more text at the bottom? It is no longer a footnote. How can we choose a semantic class that is less generic than <code>&lt;em&gt;</code> but avoids these problems?</p></li> </ol> <hr> <h1>Summary</h1> <p>It appears that the requirement of semantics seems to be overly burdensome in many instances where the desire to make something italic is not meant to carry semantic meaning. </p> <p>Furthermore, the desire to separate style from structure has led CSS to be touted as a replacement to <code>&lt;i&gt;</code> when there are occasions when this would actually be less useful. So this leaves me back with the humble <code>&lt;i&gt;</code> tag and wondering whether this train of thought is the reason why it is left in the HTML5 spec?</p> <p>Are there any good blog posts or articles on this subject as well? Perhaps by those involved in the decision to retain/create the <code>&lt;i&gt;</code> tag?</p>
<p>You should use different methods for different use cases:</p> <ol> <li>If you want to emphasise a phrase, use <code>&lt;em&gt;</code>.</li> <li>The <code>&lt;i&gt;</code> tag has a <a href="http://www.w3.org/TR/html5/text-level-semantics.html#the-i-element" rel="noreferrer">new meaning in HTML5</a>, representing "a span of text in an alternate voice or mood". So you should use this tag for things like thoughts/asides or idiomatic phrases. The spec also suggests ship names (but no longer suggests book/song/movie names; use <code>&lt;cite&gt;</code> for that instead).</li> <li>If the italicised text is part of a larger context, say an introductory paragraph, you should attach the CSS style to the larger element, i.e. <code>p.intro { font-style: italic; }</code></li> </ol>
{ "question_id": 2108318, "question_date": "2010-01-21T10:11:42.980Z", "question_score": 212, "tags": "html|css|semantic-markup", "answer_id": 2109215, "answer_date": "2010-01-21T12:44:46.513Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values <p>When you are upserting a row (PostgreSQL >= 9.5), and you want the possible INSERT to be exactly the same as the possible UPDATE, you can write it like this:</p> <pre><code>INSERT INTO tablename (id, username, password, level, email) VALUES (1, 'John', 'qwerty', 5, '[email protected]') ON CONFLICT (id) DO UPDATE SET id=EXCLUDED.id, username=EXCLUDED.username, password=EXCLUDED.password, level=EXCLUDED.level,email=EXCLUDED.email </code></pre> <p>Is there a shorter way? To just say: use all the EXCLUDE values.</p> <p>In SQLite I used to do :</p> <pre><code>INSERT OR REPLACE INTO tablename (id, user, password, level, email) VALUES (1, 'John', 'qwerty', 5, '[email protected]') </code></pre>
<p>Postgres hasn't implemented an equivalent to <code>INSERT OR REPLACE</code>. From the <a href="https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT" rel="noreferrer"><code>ON CONFLICT</code> docs</a> (emphasis mine):</p> <blockquote> <p>It can be either DO NOTHING, or a DO UPDATE clause specifying the <strong>exact details</strong> of the UPDATE action to be performed in case of a conflict.</p> </blockquote> <p>Though it doesn't give you shorthand for replacement, <code>ON CONFLICT DO UPDATE</code> applies more generally, since it lets you set new values based on preexisting data. For example:</p> <pre><code>INSERT INTO users (id, level) VALUES (1, 0) ON CONFLICT (id) DO UPDATE SET level = users.level + 1; </code></pre>
{ "question_id": 36359440, "question_date": "2016-04-01T14:52:08.423Z", "question_score": 212, "tags": "postgresql|upsert|postgresql-9.5", "answer_id": 36360189, "answer_date": "2016-04-01T15:29:42.493Z", "answer_score": 248 }
Please answer the following Stack Overflow question: Title: Percentage Height HTML 5/CSS <p>I am trying to set a <code>&lt;div&gt;</code> to a certain percentage height in CSS, but it just remains the same size as the content inside it. When I remove the HTML 5 <code>&lt;!DOCTYTPE html&gt;</code> however, it works, the <code>&lt;div&gt;</code> taking up the whole page as desired. I want the page to validate, so what should I do?</p> <p>I have this CSS on the <code>&lt;div&gt;</code>, which has an ID of <code>page</code>:</p> <pre><code>#page { padding: 10px; background-color: white; height: 90% !important; } </code></pre>
<blockquote> <p>I am trying to set a div to a certain percentage height in CSS</p> </blockquote> <p>Percentage of what?</p> <p>To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as <code>auto</code>, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.</p> <p>So the parent of the div must have an explicit <code>height</code> property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.</p> <p>If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <code>&lt;html&gt;</code> and <code>&lt;body&gt;</code>, have to have <code>height: 100%</code>, so there is a chain of explicit percentage heights down to the div.</p> <p>(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)</p> <p>Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (<code>vh</code>) and viewport width (<code>vw</code>):</p> <pre><code>div { height:100vh; } </code></pre> <p>See here for <a href="https://stackoverflow.com/questions/1575141/make-div-100-height-of-browser-window">more info</a>.</p>
{ "question_id": 1622027, "question_date": "2009-10-25T20:50:25.600Z", "question_score": 212, "tags": "html|css|height", "answer_id": 1622097, "answer_date": "2009-10-25T21:17:03.017Z", "answer_score": 413 }
Please answer the following Stack Overflow question: Title: Pandas convert dataframe to array of tuples <p>I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe.</p> <p>My DataFrame looks something like:</p> <pre><code>In [182]: data_set Out[182]: index data_date data_1 data_2 0 14303 2012-02-17 24.75 25.03 1 12009 2012-02-16 25.00 25.07 2 11830 2012-02-15 24.99 25.15 3 6274 2012-02-14 24.68 25.05 4 2302 2012-02-13 24.62 24.77 5 14085 2012-02-10 24.38 24.61 </code></pre> <p>I want to convert it to an array of tuples like:</p> <pre><code>[(datetime.date(2012,2,17),24.75,25.03), (datetime.date(2012,2,16),25.00,25.07), ...etc. ] </code></pre> <p>Any suggestion on how I can efficiently do this?</p>
<pre><code>list(data_set.itertuples(index=False)) </code></pre> <p>As of 17.1, the above will return a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.itertuples.html" rel="noreferrer">list of namedtuples</a>.</p> <p>If you want a list of ordinary tuples, pass <code>name=None</code> as an argument:</p> <pre><code>list(data_set.itertuples(index=False, name=None)) </code></pre>
{ "question_id": 9758450, "question_date": "2012-03-18T12:53:06.683Z", "question_score": 212, "tags": "python|pandas", "answer_id": 34551914, "answer_date": "2015-12-31T21:57:12.910Z", "answer_score": 270 }
Please answer the following Stack Overflow question: Title: git visual diff between branches <p>This answer is great for seeing a visual diff between two files that are checked into git: <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-a-visual-diff-program/949242#949242">How do I view &#39;git diff&#39; output with a visual diff program?</a> </p> <p>However, I'd like to see a visual diff between two branches. So far, my best bet seems to be: </p> <pre><code>git diff --name-status master dev </code></pre> <p>which isn't very informative and not very visual.</p> <p>Is there anything better out there?</p>
<p>Use <a href="https://www.kernel.org/pub/software/scm/git/docs/git-diff.html" rel="noreferrer"><code>git diff</code></a> with a <a href="https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection#_commit_ranges" rel="noreferrer">range</a>.</p> <pre><code>git diff branch1..branch2 </code></pre> <p>This will compare the tips of each branch.</p> <p>If you really want some GUI software, you can try something like <a href="https://www.sourcetreeapp.com/" rel="noreferrer">SourceTree</a> which supports Mac OS X and Windows.</p>
{ "question_id": 12912985, "question_date": "2012-10-16T10:45:53.323Z", "question_score": 212, "tags": "git|diff", "answer_id": 12913063, "answer_date": "2012-10-16T10:50:30.163Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: How to discard local changes in an SVN checkout? <p>I wanted to submit a <strong>diff</strong> for review, for an Open Source Project.</p> <p>I got the code using SVN (from terminal, Ubuntu). And I did minor edits in few files. Now there is only a single change I want to submit. Rest of the changes I made, were for debugging, and are no longer required.</p> <p>I have generated diff using <code>svn di &gt; ~/os/firstdiff.diff</code> </p> <p>So my question, How to discard my local changes?</p> <p>Is there a SVN way to do it? If not, I will have to go to each file and delete all my edits. Then I would generate a new diff, and submit it.</p>
<p>Just use the <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html" rel="noreferrer"><code>svn revert</code></a> command, for example: </p> <pre><code>svn revert some_file.php </code></pre> <p>It is (as every other svn command) well documented in the <a href="http://svnbook.red-bean.com/" rel="noreferrer">svnbook resource</a> or man page, or even with the <code>svn help</code> command.</p>
{ "question_id": 9463695, "question_date": "2012-02-27T10:47:30.907Z", "question_score": 212, "tags": "svn", "answer_id": 9463729, "answer_date": "2012-02-27T10:50:12.253Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: What is the function __construct used for? <p>I have been noticing <code>__construct</code> a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.</p> <p>I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?</p>
<p><code>__construct</code> was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.</p> <p>An example could go like this:</p> <pre><code>class Database { protected $userName; protected $password; protected $dbName; public function __construct ( $UserName, $Password, $DbName ) { $this-&gt;userName = $UserName; $this-&gt;password = $Password; $this-&gt;dbName = $DbName; } } // and you would use this as: $db = new Database ( 'user_name', 'password', 'database_name' ); </code></pre> <p>Everything else is explained in the PHP manual: <a href="http://php.net/manual/en/language.oop5.decon.php" rel="noreferrer">click here</a></p>
{ "question_id": 455910, "question_date": "2009-01-18T21:19:58.833Z", "question_score": 212, "tags": "php|constructor", "answer_id": 455929, "answer_date": "2009-01-18T21:28:26.507Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: API vs. Webservice <p>What is the difference between a webservice and an API? Is the difference more than the protocol used to transfer data? thanks. </p>
<p>An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, one that almost always operates over HTTP (though some, like SOAP, can use alternate transports, like SMTP). The <a href="http://www.w3.org/TR/ws-gloss/" rel="noreferrer">official W3C definition</a> mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless mentioned otherwise.</p> <p>For examples of web services specifically, see <a href="http://en.wikipedia.org/wiki/SOAP" rel="noreferrer">SOAP</a>, <a href="http://en.wikipedia.org/wiki/REST" rel="noreferrer">REST</a>, and <a href="http://en.wikipedia.org/wiki/XML-RPC" rel="noreferrer">XML-RPC</a>. For an example of another type of API, one written in C for use on a local machine, see the <a href="http://kernelbook.sourceforge.net/kernel-api.html/" rel="noreferrer">Linux Kernel API</a>.</p> <p>As far as the protocol goes, a Web service API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API, for example, uses <a href="http://en.wikipedia.org/wiki/Interrupt" rel="noreferrer">Interrupts</a> to invoke the system calls that comprise its API for calls from user space.</p>
{ "question_id": 808421, "question_date": "2009-04-30T18:35:39.830Z", "question_score": 212, "tags": "web-services|terminology", "answer_id": 808467, "answer_date": "2009-04-30T18:45:03.880Z", "answer_score": 179 }
Please answer the following Stack Overflow question: Title: Bigger Glyphicons <p>How do I make bigger Glyphicons in twitter bootstrap 3.0 (not 2.3.x). </p> <p>This code will make my glyphicons big:</p> <pre><code>&lt;button type="button" class="btn btn-default btn-lg"&gt; &lt;span class="glyphicon glyphicon-th-list"&gt; &lt;/span&gt; &lt;/button&gt; </code></pre> <p>How can I get this size <strong>without</strong> using the btn-lg class while using <strong>only</strong> a span ?</p> <p>This gives a small glyphicon:</p> <pre><code>&lt;span class="glyphicon glyphicon-link"&gt;&lt;/span&gt; </code></pre>
<p>You can just give the glyphicon a font-size to your liking:</p> <pre><code>span.glyphicon-link { font-size: 1.2em; } </code></pre>
{ "question_id": 18478365, "question_date": "2013-08-28T02:16:39.747Z", "question_score": 212, "tags": "css|twitter-bootstrap|twitter-bootstrap-3|glyphicons", "answer_id": 18478451, "answer_date": "2013-08-28T02:28:14.147Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: How to watch for a route change in AngularJS? <p>How would one watch/trigger an event on a route change?</p>
<p><strong>Note</strong>: This is a proper answer for a legacy version of AngularJS. See <a href="https://stackoverflow.com/questions/16344223/angularjs-cancel-route-change-event">this question</a> for updated versions.</p> <pre><code>$scope.$on('$routeChangeStart', function($event, next, current) { // ... you could trigger something here ... }); </code></pre> <p>The following events are also available (their callback functions take different arguments):</p> <ul> <li>$routeChangeSuccess</li> <li>$routeChangeError</li> <li>$routeUpdate - if <a href="http://code.angularjs.org/1.0.8/docs/api/ng.$routeProvider#when" rel="noreferrer">reloadOnSearch</a> property has been set to false</li> </ul> <p>See the <a href="http://code.angularjs.org/1.0.8/docs/api/ng.$route" rel="noreferrer">$route</a> docs.</p> <p>There are two other <a href="https://stackoverflow.com/questions/14700325/what-are-the-undocumented-features-of-angular">undocumented</a> events: </p> <ul> <li>$locationChangeStart</li> <li>$locationChangeSuccess</li> </ul> <p>See <a href="https://stackoverflow.com/questions/15006849/angularjs-whats-the-difference-between-locationchangesuccess-and-locationch">What&#39;s the difference between $locationChangeSuccess and $locationChangeStart?</a></p>
{ "question_id": 14765719, "question_date": "2013-02-08T04:33:14.223Z", "question_score": 212, "tags": "javascript|angularjs", "answer_id": 14765954, "answer_date": "2013-02-08T04:57:50.703Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: "Comparison method violates its general contract!" <p>Can someone explain me in simple terms, why does this code throw an exception, "Comparison method violates its general contract!", and how do I fix it?</p> <pre><code>private int compareParents(Foo s1, Foo s2) { if (s1.getParent() == s2) return -1; if (s2.getParent() == s1) return 1; return 0; } </code></pre>
<p><strong>Your comparator is not transitive.</strong></p> <p>Let <code>A</code> be the parent of <code>B</code>, and <code>B</code> be the parent of <code>C</code>. Since <code>A &gt; B</code> and <code>B &gt; C</code>, then it must be the case that <code>A &gt; C</code>. However, if your comparator is invoked on <code>A</code> and <code>C</code>, it would return zero, meaning <code>A == C</code>. This violates the contract and hence throws the exception.</p> <p>It's rather nice of the library to detect this and let you know, rather than behave erratically.</p> <p>One way to satisfy the transitivity requirement in <code>compareParents()</code> is to traverse the <code>getParent()</code> chain instead of only looking at the immediate ancestor.</p>
{ "question_id": 8327514, "question_date": "2011-11-30T14:31:16.887Z", "question_score": 212, "tags": "java|comparator", "answer_id": 8327575, "answer_date": "2011-11-30T14:36:32.060Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: tqdm in Jupyter Notebook prints new progress bars repeatedly <p>I am using <code>tqdm</code> to print progress in a script I'm running in a Jupyter notebook. I am printing all messages to the console via <code>tqdm.write()</code>. However, this still gives me a skewed output like so:</p> <p><a href="https://i.stack.imgur.com/xCfqE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xCfqE.jpg" alt="enter image description here" /></a></p> <p>That is, each time a new line has to be printed, a new progress bar is printed on the next line. This does not happen when I run the script via terminal. How can I solve this?</p>
<p>Try using <code>tqdm.notebook.tqdm</code> instead of <code>tqdm</code>, as outlined <a href="https://pypi.python.org/pypi/tqdm#ipython-jupyter-integration" rel="noreferrer">here</a>.</p> <p>This could be as simple as changing your import to:</p> <p><code>from tqdm.notebook import tqdm</code></p> <p>Good luck!</p> <p><strong>EDIT:</strong> After testing, it seems that <code>tqdm</code> actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a <a href="https://stackoverflow.com/help/mcve">minimal example</a>, but it looks like your problem is caused by a print statement in each iteration. The print statement is outputting a number (~0.89) in between each status bar update, which is messing up the output. Try removing the print statement.</p>
{ "question_id": 42212810, "question_date": "2017-02-13T20:19:54.953Z", "question_score": 212, "tags": "python|jupyter-notebook|tqdm", "answer_id": 42218684, "answer_date": "2017-02-14T05:41:12.987Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: Is right click a Javascript event? <p>Is right click a Javascript event? If so, how do I use it?</p>
<p>As others have mentioned, the right mouse button can be detected <a href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MouseEvent" rel="noreferrer">through the usual mouse events (mousedown, mouseup, click)</a>. However, if you're looking for a firing event when the right-click menu is brought up, you're looking in the wrong place. The right-click/context menu is also accessible via the keyboard (shift+F10 or context menu key on Windows and some Linux). In this situation, the event that you're looking for is <code>oncontextmenu</code>:</p> <pre><code>window.oncontextmenu = function () { showCustomMenu(); return false; // cancel default menu } </code></pre> <p>As for the mouse events themselves, browsers set a property to the event object that is accessible from the event handling function:</p> <pre><code>document.body.onclick = function (e) { var isRightMB; e = e || window.event; if ("which" in e) // Gecko (Firefox), WebKit (Safari/Chrome) &amp; Opera isRightMB = e.which == 3; else if ("button" in e) // IE, Opera isRightMB = e.button == 2; alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!"); } </code></pre> <p><a href="https://developer.mozilla.org/en/DOM/window.oncontextmenu" rel="noreferrer">window.oncontextmenu - MDC</a></p>
{ "question_id": 2405771, "question_date": "2010-03-09T00:19:02.080Z", "question_score": 212, "tags": "javascript", "answer_id": 2405835, "answer_date": "2010-03-09T00:30:20.510Z", "answer_score": 231 }
Please answer the following Stack Overflow question: Title: get original element from ng-click <p>I have a list of items in my view with <code>ng-click</code> attached to them:</p> <pre><code>&lt;ul id="team-filters"&gt; &lt;li ng-click="foo($event, team)" ng-repeat="team in teams"&gt; &lt;img src="{{team.logoSmall}}" alt="{{team.name}}" title="{{team.name}}"&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'm handling the click events in the <code>foo</code> function in my directive, passing <code>$event</code> as a reference to the object that's been clicked, but I'm getting a reference to the <code>img</code> tag, rather than the <code>li</code> tag. I then have to do stuff like this to get the <code>li</code>:</p> <pre><code>$scope.foo = function($event, team) { var el = (function(){ if ($event.target.nodeName === 'IMG') { return angular.element($event.target).parent(); // get li } else { return angular.element($event.target); // is li } })(); </code></pre> <p>Is there a simple way to get the reference to the element that <code>ng-click</code> is bound to, without doing DOM operations in my directive?</p>
<p>You need <code>$event.currentTarget</code> instead of <code>$event.target</code>.</p>
{ "question_id": 23107613, "question_date": "2014-04-16T11:05:08.717Z", "question_score": 212, "tags": "angularjs|angularjs-directive", "answer_id": 23107800, "answer_date": "2014-04-16T11:15:11.777Z", "answer_score": 329 }
Please answer the following Stack Overflow question: Title: How do I prevent a Gateway Timeout with FastCGI on Nginx <p>I am running Django, FastCGI, and Nginx. I am creating an api of sorts that where someone can send some data via XML which I will process and then return some status codes for each node that was sent over.</p> <p>The problem is that Nginx will throw a 504 Gateway Time-out if I take too long to process the XML -- I think longer than 60 seconds.</p> <p>So I would like to set up Nginx so that if any requests matching the location /api will not time out for 120 seconds. What setting will accomplish that.</p> <p>What I have so far is:</p> <pre><code> # Handles all api calls location ^~ /api/ { proxy_read_timeout 120; proxy_connect_timeout 120; fastcgi_pass 127.0.0.1:8080; } </code></pre> <p>Edit: What I have is not working :)</p>
<p>Proxy timeouts are well, for proxies, not for FastCGI...</p> <p>The directives that affect FastCGI timeouts are <code>client_header_timeout</code>, <code>client_body_timeout</code> and <code>send_timeout</code>.</p> <p><strong>Edit</strong>: Considering what's found on nginx wiki, the <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_send_timeout" rel="nofollow noreferrer">send_timeout directive</a> is responsible for setting general timeout of response (which was bit misleading). For FastCGI there's <code>fastcgi_read_timeout</code> which is affecting the <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_read_timeout" rel="nofollow noreferrer">FastCGI process response timeout</a>.</p>
{ "question_id": 561946, "question_date": "2009-02-18T17:01:26.293Z", "question_score": 212, "tags": "configuration|nginx|fastcgi", "answer_id": 562499, "answer_date": "2009-02-18T19:34:13.790Z", "answer_score": 252 }
Please answer the following Stack Overflow question: Title: check if variable is dataframe <p>when my function f is called with a variable I want to check if var is a pandas dataframe:</p> <pre><code>def f(var): if var == pd.DataFrame(): print "do stuff" </code></pre> <p>I guess the solution might be quite simple but even with </p> <pre><code>def f(var): if var.values != None: print "do stuff" </code></pre> <p>I can't get it to work like expected. </p>
<p>Use <a href="http://docs.python.org/2/library/functions.html#isinstance" rel="noreferrer"><code>isinstance</code></a>, nothing else:</p> <pre><code>if isinstance(x, pd.DataFrame): ... # do something </code></pre> <hr> <p><a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP8</a> says explicitly that <code>isinstance</code> is the preferred way to check types</p> <pre><code>No: type(x) is pd.DataFrame No: type(x) == pd.DataFrame Yes: isinstance(x, pd.DataFrame) </code></pre> <p>And don't even think about</p> <pre><code>if obj.__class__.__name__ = 'DataFrame': expect_problems_some_day() </code></pre> <p><code>isinstance</code> handles inheritance (see <a href="https://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python">What are the differences between type() and isinstance()?</a>). For example, it will tell you if a variable is a string (either <code>str</code> or <code>unicode</code>), because they derive from <code>basestring</code>)</p> <pre><code>if isinstance(obj, basestring): i_am_string(obj) </code></pre> <p>Specifically for <code>pandas</code> <code>DataFrame</code> objects:</p> <pre><code>import pandas as pd isinstance(var, pd.DataFrame) </code></pre>
{ "question_id": 14808945, "question_date": "2013-02-11T09:10:07.870Z", "question_score": 212, "tags": "python|pandas", "answer_id": 14809149, "answer_date": "2013-02-11T09:23:16.907Z", "answer_score": 307 }
Please answer the following Stack Overflow question: Title: Output array to CSV in Ruby <p>It's easy enough to read a CSV file into an array with Ruby but I can't find any good documentation on how to write an array into a CSV file. Can anyone tell me how to do this?</p> <p>I'm using Ruby 1.9.2 if that matters.</p>
<p>To a file:</p> <pre><code>require 'csv' CSV.open("myfile.csv", "w") do |csv| csv &lt;&lt; ["row", "of", "CSV", "data"] csv &lt;&lt; ["another", "row"] # ... end </code></pre> <p>To a string:</p> <pre><code>require 'csv' csv_string = CSV.generate do |csv| csv &lt;&lt; ["row", "of", "CSV", "data"] csv &lt;&lt; ["another", "row"] # ... end </code></pre> <p>Here's the current documentation on CSV: <a href="http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html" rel="noreferrer">http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html</a></p>
{ "question_id": 4822422, "question_date": "2011-01-27T22:02:22.500Z", "question_score": 212, "tags": "ruby|csv", "answer_id": 4822442, "answer_date": "2011-01-27T22:04:37.097Z", "answer_score": 375 }
Please answer the following Stack Overflow question: Title: Array to Hash Ruby <p>Convert this Array:</p> <pre><code>a = [&quot;item 1&quot;, &quot;item 2&quot;, &quot;item 3&quot;, &quot;item 4&quot;] </code></pre> <p>...to a Hash:</p> <pre><code>{ &quot;item 1&quot; =&gt; &quot;item 2&quot;, &quot;item 3&quot; =&gt; &quot;item 4&quot; } </code></pre> <p>i.e. elements at <em>even</em> indexes are <em>keys</em> and <em>odd</em> ones are <em>values</em>.</p>
<pre><code>a = ["item 1", "item 2", "item 3", "item 4"] h = Hash[*a] # =&gt; { "item 1" =&gt; "item 2", "item 3" =&gt; "item 4" } </code></pre> <p>That's it. The <code>*</code> is called the <em>splat</em> operator.</p> <p>One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."</p> <p>So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Łukasz Niemier (also in the comments) offers this method for large data sets:</p> <pre><code>h = Hash[a.each_slice(2).to_a] </code></pre>
{ "question_id": 4028329, "question_date": "2010-10-26T21:51:00.617Z", "question_score": 212, "tags": "ruby|arrays|hashmap", "answer_id": 4028362, "answer_date": "2010-10-26T21:55:39.547Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: Can someone explain mappedBy in JPA and Hibernate? <p>I am new to hibernate and need to use one-to-many and many-to-one relations. It is a bi-directional relationship in my objects, so that I can traverse from either direction. <code>mappedBy</code> is the recommended way to go about it, however, I couldn't understand it. Can someone explain:</p> <ul> <li>what is the recommended way to use it?</li> <li>what purpose does it solve?</li> </ul> <p>For the sake of my example, here are my classes with annotations:</p> <ul> <li><code>Airline</code> <strong>OWNS many</strong> <code>AirlineFlights</code></li> <li><strong>Many</strong> <code>AirlineFlights</code> belong to <strong>ONE</strong> <code>Airline</code></li> </ul> <p><strong>Airline</strong>:</p> <pre><code>@Entity @Table(name="Airline") public class Airline { private Integer idAirline; private String name; private String code; private String aliasName; private Set&lt;AirlineFlight&gt; airlineFlights = new HashSet&lt;AirlineFlight&gt;(0); public Airline(){} public Airline(String name, String code, String aliasName, Set&lt;AirlineFlight&gt; flights) { setName(name); setCode(code); setAliasName(aliasName); setAirlineFlights(flights); } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="IDAIRLINE", nullable=false) public Integer getIdAirline() { return idAirline; } private void setIdAirline(Integer idAirline) { this.idAirline = idAirline; } @Column(name="NAME", nullable=false) public String getName() { return name; } public void setName(String name) { this.name = DAOUtil.convertToDBString(name); } @Column(name="CODE", nullable=false, length=3) public String getCode() { return code; } public void setCode(String code) { this.code = DAOUtil.convertToDBString(code); } @Column(name="ALIAS", nullable=true) public String getAliasName() { return aliasName; } public void setAliasName(String aliasName) { if(aliasName != null) this.aliasName = DAOUtil.convertToDBString(aliasName); } @OneToMany(fetch=FetchType.LAZY, cascade = {CascadeType.ALL}) @JoinColumn(name="IDAIRLINE") public Set&lt;AirlineFlight&gt; getAirlineFlights() { return airlineFlights; } public void setAirlineFlights(Set&lt;AirlineFlight&gt; flights) { this.airlineFlights = flights; } } </code></pre> <p><strong>AirlineFlights:</strong></p> <pre><code>@Entity @Table(name="AirlineFlight") public class AirlineFlight { private Integer idAirlineFlight; private Airline airline; private String flightNumber; public AirlineFlight(){} public AirlineFlight(Airline airline, String flightNumber) { setAirline(airline); setFlightNumber(flightNumber); } @Id @GeneratedValue(generator="identity") @GenericGenerator(name="identity", strategy="identity") @Column(name="IDAIRLINEFLIGHT", nullable=false) public Integer getIdAirlineFlight() { return idAirlineFlight; } private void setIdAirlineFlight(Integer idAirlineFlight) { this.idAirlineFlight = idAirlineFlight; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="IDAIRLINE", nullable=false) public Airline getAirline() { return airline; } public void setAirline(Airline airline) { this.airline = airline; } @Column(name="FLIGHTNUMBER", nullable=false) public String getFlightNumber() { return flightNumber; } public void setFlightNumber(String flightNumber) { this.flightNumber = DAOUtil.convertToDBString(flightNumber); } } </code></pre> <p><strong>EDIT:</strong></p> <p>Database schema:</p> <p>AirlineFlights has the idAirline as ForeignKey and Airline has no idAirlineFlights. This makes, AirlineFlights as the owner/identifying entity ?</p> <p>Theoretically, I would like airline to be the owner of airlineFlights.</p> <p><img src="https://i.stack.imgur.com/gQvDs.png" alt="enter image description here"></p>
<p>By specifying the <code>@JoinColumn</code> on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the <code>@JoinColumn</code> off of the <code>@OneToMany</code> side entirely, and instead add mappedBy to the <code>@OneToMany</code>.</p> <pre><code>@OneToMany(cascade = CascadeType.ALL, mappedBy="airline") public Set&lt;AirlineFlight&gt; getAirlineFlights() { return airlineFlights; } </code></pre> <p>That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."</p>
{ "question_id": 9108224, "question_date": "2012-02-02T06:46:31.163Z", "question_score": 212, "tags": "java|hibernate|jpa|jakarta-ee|hibernate-mapping", "answer_id": 9108623, "answer_date": "2012-02-02T07:32:22.217Z", "answer_score": 161 }